blob: 6f5125a08476e476d80ae317713d7866a75e4207 [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"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000022#include "lldb/Core/Module.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000023#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000026#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000027#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Host/Host.h"
Greg Clayton44d93782014-01-27 23:43:24 +000030#include "lldb/Host/Terminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000032#include "lldb/Target/DynamicLoader.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000033#include "lldb/Target/JITLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000034#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000035#include "lldb/Target/LanguageRuntime.h"
36#include "lldb/Target/CPPLanguageRuntime.h"
37#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000038#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000040#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000041#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Target/Target.h"
43#include "lldb/Target/TargetList.h"
44#include "lldb/Target/Thread.h"
45#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000046#include "lldb/Target/ThreadPlanBase.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000047#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048
Charles Davis510938e2013-08-27 05:04:57 +000049#ifndef LLDB_DISABLE_POSIX
50#include <spawn.h>
51#endif
52
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053using namespace lldb;
54using namespace lldb_private;
55
Greg Clayton67cc0632012-08-22 17:17:09 +000056
57// Comment out line below to disable memory caching, overriding the process setting
58// target.process.disable-memory-cache
59#define ENABLE_MEMORY_CACHING
60
61#ifdef ENABLE_MEMORY_CACHING
62#define DISABLE_MEM_CACHE_DEFAULT false
63#else
64#define DISABLE_MEM_CACHE_DEFAULT true
65#endif
66
67class ProcessOptionValueProperties : public OptionValueProperties
68{
69public:
70 ProcessOptionValueProperties (const ConstString &name) :
71 OptionValueProperties (name)
72 {
73 }
74
75 // This constructor is used when creating ProcessOptionValueProperties when it
76 // is part of a new lldb_private::Process instance. It will copy all current
77 // global property values as needed
78 ProcessOptionValueProperties (ProcessProperties *global_properties) :
79 OptionValueProperties(*global_properties->GetValueProperties())
80 {
81 }
82
83 virtual const Property *
84 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
85 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000086 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000087 // try and grab the setting from the current process if there is one. Else we just
88 // use the one from this instance.
89 if (exe_ctx)
90 {
91 Process *process = exe_ctx->GetProcessPtr();
92 if (process)
93 {
94 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
95 if (this != instance_properties)
96 return instance_properties->ProtectedGetPropertyAtIndex (idx);
97 }
98 }
99 return ProtectedGetPropertyAtIndex (idx);
100 }
101};
102
103static PropertyDefinition
104g_properties[] =
105{
106 { "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 +0000107 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
108 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000109 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
110 { "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 +0000111 { "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 +0000112 { "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 +0000113 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000114 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
115};
116
117enum {
118 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000119 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000120 ePropertyIgnoreBreakpointsInExpressions,
121 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000122 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000123 ePropertyStopOnSharedLibraryEvents,
124 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000125};
126
127ProcessProperties::ProcessProperties (bool is_global) :
128 Properties ()
129{
130 if (is_global)
131 {
132 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
133 m_collection_sp->Initialize(g_properties);
134 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000135 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000136 true,
137 Thread::GetGlobalProperties()->GetValueProperties());
138 }
139 else
140 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
141}
142
143ProcessProperties::~ProcessProperties()
144{
145}
146
147bool
148ProcessProperties::GetDisableMemoryCache() const
149{
150 const uint32_t idx = ePropertyDisableMemCache;
151 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
152}
153
154Args
155ProcessProperties::GetExtraStartupCommands () const
156{
157 Args args;
158 const uint32_t idx = ePropertyExtraStartCommand;
159 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
160 return args;
161}
162
163void
164ProcessProperties::SetExtraStartupCommands (const Args &args)
165{
166 const uint32_t idx = ePropertyExtraStartCommand;
167 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
168}
169
Greg Claytonc9d645d2012-10-18 22:40:37 +0000170FileSpec
171ProcessProperties::GetPythonOSPluginPath () const
172{
173 const uint32_t idx = ePropertyPythonOSPluginPath;
174 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
175}
176
177void
178ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
179{
180 const uint32_t idx = ePropertyPythonOSPluginPath;
181 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
182}
183
Jim Ingham184e9812013-01-15 02:47:48 +0000184
185bool
186ProcessProperties::GetIgnoreBreakpointsInExpressions () const
187{
188 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
189 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
190}
191
192void
193ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
194{
195 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
196 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
197}
198
199bool
200ProcessProperties::GetUnwindOnErrorInExpressions () const
201{
202 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
203 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
204}
205
206void
207ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
208{
209 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
210 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
211}
212
Jim Ingham29950772013-01-26 02:19:28 +0000213bool
214ProcessProperties::GetStopOnSharedLibraryEvents () const
215{
216 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
217 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
218}
219
220void
221ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
222{
223 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
224 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
225}
226
Jim Inghamacff8952013-05-02 00:27:30 +0000227bool
228ProcessProperties::GetDetachKeepsStopped () const
229{
230 const uint32_t idx = ePropertyDetachKeepsStopped;
231 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
232}
233
234void
235ProcessProperties::SetDetachKeepsStopped (bool stop)
236{
237 const uint32_t idx = ePropertyDetachKeepsStopped;
238 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
239}
240
Greg Clayton32e0a752011-03-30 18:16:51 +0000241void
Greg Clayton8b82f082011-04-12 05:54:46 +0000242ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000243{
244 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000245 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000246 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000247
248 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000249 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000250
251 if (m_executable)
252 {
253 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
254 s.PutCString (" file = ");
255 m_executable.Dump(&s);
256 s.EOL();
257 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000258 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000259 if (argc > 0)
260 {
261 for (uint32_t i=0; i<argc; i++)
262 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000263 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000264 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000265 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000266 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000267 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000268 }
269 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000270
271 const uint32_t envc = m_environment.GetArgumentCount();
272 if (envc > 0)
273 {
274 for (uint32_t i=0; i<envc; i++)
275 {
276 const char *env = m_environment.GetArgumentAtIndex(i);
277 if (i < 10)
278 s.Printf (" env[%u] = %s\n", i, env);
279 else
280 s.Printf ("env[%u] = %s\n", i, env);
281 }
282 }
283
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000284 if (m_arch.IsValid())
285 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
286
Greg Clayton8b82f082011-04-12 05:54:46 +0000287 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000288 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000289 cstr = platform->GetUserName (m_uid);
290 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000291 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000293 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000294 cstr = platform->GetGroupName (m_gid);
295 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000296 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000298 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 cstr = platform->GetUserName (m_euid);
300 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000301 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000302 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000303 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000304 cstr = platform->GetGroupName (m_egid);
305 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000306 }
307}
308
309void
Greg Clayton8b82f082011-04-12 05:54:46 +0000310ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000311{
Greg Clayton8b82f082011-04-12 05:54:46 +0000312 const char *label;
313 if (show_args || verbose)
314 label = "ARGUMENTS";
315 else
316 label = "NAME";
317
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000318 if (verbose)
319 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000320 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000321 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
322 }
323 else
324 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000325 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000326 s.PutCString ("====== ====== ========== ======= ============================\n");
327 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000328}
329
330void
Greg Clayton8b82f082011-04-12 05:54:46 +0000331ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000332{
333 if (m_pid != LLDB_INVALID_PROCESS_ID)
334 {
335 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000336 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000337
Greg Clayton32e0a752011-03-30 18:16:51 +0000338
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000339 if (verbose)
340 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000341 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000342 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
343 s.Printf ("%-10s ", cstr);
344 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000345 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000346
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000348 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
349 s.Printf ("%-10s ", cstr);
350 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000351 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000352
Greg Clayton8b82f082011-04-12 05:54:46 +0000353 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000354 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
355 s.Printf ("%-10s ", cstr);
356 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000357 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000358
Greg Clayton8b82f082011-04-12 05:54:46 +0000359 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000360 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
361 s.Printf ("%-10s ", cstr);
362 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000363 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000364 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
365 }
366 else
367 {
Jason Molendafd54b362011-09-20 21:44:10 +0000368 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000369 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000370 (int)m_arch.GetTriple().getArchName().size(),
371 m_arch.GetTriple().getArchName().data());
372 }
373
Greg Clayton8b82f082011-04-12 05:54:46 +0000374 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000375 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000376 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000377 if (argc > 0)
378 {
379 for (uint32_t i=0; i<argc; i++)
380 {
381 if (i > 0)
382 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000383 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000384 }
385 }
386 }
387 else
388 {
389 s.PutCString (GetName());
390 }
391
392 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000393 }
394}
395
Greg Clayton8b82f082011-04-12 05:54:46 +0000396Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000397ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000398{
399 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000400 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000401
402 switch (short_option)
403 {
404 case 's': // Stop at program entry point
405 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
406 break;
407
Greg Clayton8b82f082011-04-12 05:54:46 +0000408 case 'i': // STDIN for read only
409 {
410 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000411 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000412 launch_info.AppendFileAction (action);
413 }
414 break;
415
416 case 'o': // Open STDOUT for write only
417 {
418 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000419 if (action.Open (STDOUT_FILENO, option_arg, false, true))
420 launch_info.AppendFileAction (action);
421 }
422 break;
423
424 case 'e': // STDERR for write only
425 {
426 ProcessLaunchInfo::FileAction action;
427 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000428 launch_info.AppendFileAction (action);
429 }
430 break;
431
Greg Clayton9845a8d2012-03-06 04:01:04 +0000432
Greg Clayton8b82f082011-04-12 05:54:46 +0000433 case 'p': // Process plug-in name
434 launch_info.SetProcessPluginName (option_arg);
435 break;
436
437 case 'n': // Disable STDIO
438 {
439 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000440 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000441 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000442 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000443 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000444 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000445 launch_info.AppendFileAction (action);
446 }
447 break;
448
449 case 'w':
450 launch_info.SetWorkingDirectory (option_arg);
451 break;
452
453 case 't': // Open process in new terminal window
454 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
455 break;
456
457 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000458 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
459 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000460 break;
461
462 case 'A':
463 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
464 break;
465
Greg Clayton982c9762011-11-03 21:22:33 +0000466 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000467 if (option_arg && option_arg[0])
468 launch_info.SetShell (option_arg);
469 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000470 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000471 break;
472
Greg Clayton8b82f082011-04-12 05:54:46 +0000473 case 'v':
474 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
475 break;
476
477 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000478 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000479 break;
480
481 }
482 return error;
483}
484
485OptionDefinition
486ProcessLaunchCommandOptions::g_option_table[] =
487{
Virgile Belloe2607b52013-09-05 16:42:23 +0000488{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
489{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
490{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
491{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
492{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
493{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
494{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000495
Virgile Belloe2607b52013-09-05 16:42:23 +0000496{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
497{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
498{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000499
Virgile Belloe2607b52013-09-05 16:42:23 +0000500{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000501
Virgile Belloe2607b52013-09-05 16:42:23 +0000502{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000503
504{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
505};
506
507
508
509bool
510ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000511{
512 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
513 return true;
514 const char *match_name = m_match_info.GetName();
515 if (!match_name)
516 return true;
517
518 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
519}
520
521bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000522ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000523{
524 if (!NameMatches (proc_info.GetName()))
525 return false;
526
527 if (m_match_info.ProcessIDIsValid() &&
528 m_match_info.GetProcessID() != proc_info.GetProcessID())
529 return false;
530
531 if (m_match_info.ParentProcessIDIsValid() &&
532 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
533 return false;
534
Greg Clayton8b82f082011-04-12 05:54:46 +0000535 if (m_match_info.UserIDIsValid () &&
536 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000537 return false;
538
Greg Clayton8b82f082011-04-12 05:54:46 +0000539 if (m_match_info.GroupIDIsValid () &&
540 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000541 return false;
542
543 if (m_match_info.EffectiveUserIDIsValid () &&
544 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
545 return false;
546
547 if (m_match_info.EffectiveGroupIDIsValid () &&
548 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
549 return false;
550
551 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000552 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000553 return false;
554 return true;
555}
556
557bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000558ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000559{
560 if (m_name_match_type != eNameMatchIgnore)
561 return false;
562
563 if (m_match_info.ProcessIDIsValid())
564 return false;
565
566 if (m_match_info.ParentProcessIDIsValid())
567 return false;
568
Greg Clayton8b82f082011-04-12 05:54:46 +0000569 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000570 return false;
571
Greg Clayton8b82f082011-04-12 05:54:46 +0000572 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000573 return false;
574
575 if (m_match_info.EffectiveUserIDIsValid ())
576 return false;
577
578 if (m_match_info.EffectiveGroupIDIsValid ())
579 return false;
580
581 if (m_match_info.GetArchitecture().IsValid())
582 return false;
583
584 if (m_match_all_users)
585 return false;
586
587 return true;
588
589}
590
591void
Greg Clayton8b82f082011-04-12 05:54:46 +0000592ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000593{
594 m_match_info.Clear();
595 m_name_match_type = eNameMatchIgnore;
596 m_match_all_users = false;
597}
Greg Clayton58be07b2011-01-07 06:08:19 +0000598
Greg Claytonc3776bf2012-02-09 06:16:32 +0000599ProcessSP
600Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601{
Greg Clayton949e8222013-01-16 17:29:04 +0000602 static uint32_t g_process_unique_id = 0;
603
Greg Claytonc3776bf2012-02-09 06:16:32 +0000604 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000605 ProcessCreateInstance create_callback = NULL;
606 if (plugin_name)
607 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000608 ConstString const_plugin_name(plugin_name);
609 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000610 if (create_callback)
611 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000612 process_sp = create_callback(target, listener, crash_file_path);
613 if (process_sp)
614 {
Greg Clayton949e8222013-01-16 17:29:04 +0000615 if (process_sp->CanDebug(target, true))
616 {
617 process_sp->m_process_unique_id = ++g_process_unique_id;
618 }
619 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000620 process_sp.reset();
621 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622 }
623 }
624 else
625 {
Greg Claytonc982c762010-07-09 20:39:50 +0000626 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000628 process_sp = create_callback(target, listener, crash_file_path);
629 if (process_sp)
630 {
Greg Clayton949e8222013-01-16 17:29:04 +0000631 if (process_sp->CanDebug(target, false))
632 {
633 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000634 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000635 }
636 else
637 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000638 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 }
640 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000641 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642}
643
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000644ConstString &
645Process::GetStaticBroadcasterClass ()
646{
647 static ConstString class_name ("lldb.process");
648 return class_name;
649}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650
651//----------------------------------------------------------------------
652// Process constructor
653//----------------------------------------------------------------------
654Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000655 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000657 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 m_public_state (eStateUnloaded),
660 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000661 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
662 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 m_private_state_listener ("lldb.process.internal_state_listener"),
664 m_private_state_control_wait(),
665 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000666 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000667 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000669 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 m_exit_status (-1),
671 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000672 m_thread_mutex (Mutex::eMutexTypeRecursive),
673 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000674 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000675 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000676 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000677 m_queue_list (this),
678 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000680 m_image_tokens (),
681 m_listener (listener),
682 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000683 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000684 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000685 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000686 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000687 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000688 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000689 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000690 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000691 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
692 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000693 m_memory_cache (*this),
694 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000695 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000696 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000697 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000698 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000699 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000700 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000701 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000702 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000703 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000704 m_destroy_in_process (false),
705 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000707 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000708
Greg Clayton5160ce52013-03-27 23:08:40 +0000709 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000711 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000713 SetEventName (eBroadcastBitStateChanged, "state-changed");
714 SetEventName (eBroadcastBitInterrupt, "interrupt");
715 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
716 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000717 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000718
Greg Clayton35a4cc52012-10-29 20:52:08 +0000719 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
720 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
721 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
722
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 listener.StartListeningForEvents (this,
724 eBroadcastBitStateChanged |
725 eBroadcastBitInterrupt |
726 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000727 eBroadcastBitSTDERR |
728 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729
730 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000731 eBroadcastBitStateChanged |
732 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733
734 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
735 eBroadcastInternalStateControlStop |
736 eBroadcastInternalStateControlPause |
737 eBroadcastInternalStateControlResume);
738}
739
740//----------------------------------------------------------------------
741// Destructor
742//----------------------------------------------------------------------
743Process::~Process()
744{
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 StopPrivateStateThread();
749}
750
Greg Clayton67cc0632012-08-22 17:17:09 +0000751const ProcessPropertiesSP &
752Process::GetGlobalProperties()
753{
754 static ProcessPropertiesSP g_settings_sp;
755 if (!g_settings_sp)
756 g_settings_sp.reset (new ProcessProperties (true));
757 return g_settings_sp;
758}
759
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760void
761Process::Finalize()
762{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000763 switch (GetPrivateState())
764 {
765 case eStateConnected:
766 case eStateAttaching:
767 case eStateLaunching:
768 case eStateStopped:
769 case eStateRunning:
770 case eStateStepping:
771 case eStateCrashed:
772 case eStateSuspended:
773 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000774 {
775 // FIXME: This will have to be a process setting:
776 bool keep_stopped = false;
777 Detach(keep_stopped);
778 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000779 else
780 Destroy();
781 break;
782
783 case eStateInvalid:
784 case eStateUnloaded:
785 case eStateDetached:
786 case eStateExited:
787 break;
788 }
789
Greg Clayton1ed54f52011-10-01 00:45:15 +0000790 // Clear our broadcaster before we proceed with destroying
791 Broadcaster::Clear();
792
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793 // Do any cleanup needed prior to being destructed... Subclasses
794 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000795
796 // We need to destroy the loader before the derived Process class gets destroyed
797 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000798 m_dynamic_checkers_ap.reset();
799 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000800 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000801 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000802 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000803 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000804 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000805 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000806 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000807 m_queue_list.Clear();
808 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000809 std::vector<Notifications> empty_notifications;
810 m_notifications.swap(empty_notifications);
811 m_image_tokens.clear();
812 m_memory_cache.Clear();
813 m_allocated_memory_cache.Clear();
814 m_language_runtimes.clear();
815 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000816//#ifdef LLDB_CONFIGURATION_DEBUG
817// StreamFile s(stdout, false);
818// EventSP event_sp;
819// while (m_private_state_listener.GetNextEvent(event_sp))
820// {
821// event_sp->Dump (&s);
822// s.EOL();
823// }
824//#endif
825 // We have to be very careful here as the m_private_state_listener might
826 // contain events that have ProcessSP values in them which can keep this
827 // process around forever. These events need to be cleared out.
828 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000829 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
830 m_public_run_lock.SetStopped();
831 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
832 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000833 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834}
835
836void
837Process::RegisterNotificationCallbacks (const Notifications& callbacks)
838{
839 m_notifications.push_back(callbacks);
840 if (callbacks.initialize != NULL)
841 callbacks.initialize (callbacks.baton, this);
842}
843
844bool
845Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
846{
847 std::vector<Notifications>::iterator pos, end = m_notifications.end();
848 for (pos = m_notifications.begin(); pos != end; ++pos)
849 {
850 if (pos->baton == callbacks.baton &&
851 pos->initialize == callbacks.initialize &&
852 pos->process_state_changed == callbacks.process_state_changed)
853 {
854 m_notifications.erase(pos);
855 return true;
856 }
857 }
858 return false;
859}
860
861void
862Process::SynchronouslyNotifyStateChanged (StateType state)
863{
864 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
865 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
866 {
867 if (notification_pos->process_state_changed)
868 notification_pos->process_state_changed (notification_pos->baton, this, state);
869 }
870}
871
872// FIXME: We need to do some work on events before the general Listener sees them.
873// For instance if we are continuing from a breakpoint, we need to ensure that we do
874// the little "insert real insn, step & stop" trick. But we can't do that when the
875// event is delivered by the broadcaster - since that is done on the thread that is
876// waiting for new events, so if we needed more than one event for our handling, we would
877// stall. So instead we do it when we fetch the event off of the queue.
878//
879
880StateType
881Process::GetNextEvent (EventSP &event_sp)
882{
883 StateType state = eStateInvalid;
884
885 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
886 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
887
888 return state;
889}
890
891
892StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000893Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894{
Jim Ingham4b536182011-08-09 02:12:22 +0000895 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
896 // We have to actually check each event, and in the case of a stopped event check the restarted flag
897 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000898 if (event_sp_ptr)
899 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000900 StateType state = GetState();
901 // If we are exited or detached, we won't ever get back to any
902 // other valid state...
903 if (state == eStateDetached || state == eStateExited)
904 return state;
905
Daniel Malea9e9919f2013-10-09 16:56:28 +0000906 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
907 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000908 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
909 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000910
911 if (!wait_always &&
912 StateIsStoppedState(state, true) &&
913 StateIsStoppedState(GetPrivateState(), true)) {
914 if (log)
915 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
916 __FUNCTION__);
917 return state;
918 }
919
Jim Ingham4b536182011-08-09 02:12:22 +0000920 while (state != eStateInvalid)
921 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000922 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000923 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000924 if (event_sp_ptr && event_sp)
925 *event_sp_ptr = event_sp;
926
Jim Ingham4b536182011-08-09 02:12:22 +0000927 switch (state)
928 {
929 case eStateCrashed:
930 case eStateDetached:
931 case eStateExited:
932 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000933 // We need to toggle the run lock as this won't get done in
934 // SetPublicState() if the process is hijacked.
935 if (hijack_listener)
936 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000937 return state;
938 case eStateStopped:
939 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
940 continue;
941 else
Greg Clayton44d93782014-01-27 23:43:24 +0000942 {
943 // We need to toggle the run lock as this won't get done in
944 // SetPublicState() if the process is hijacked.
945 if (hijack_listener)
946 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000947 return state;
Greg Clayton44d93782014-01-27 23:43:24 +0000948 }
Jim Ingham4b536182011-08-09 02:12:22 +0000949 default:
950 continue;
951 }
952 }
953 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954}
955
956
957StateType
958Process::WaitForState
959(
960 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +0000961 const StateType *match_states,
962 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963)
964{
965 EventSP event_sp;
966 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000967 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 while (state != eStateInvalid)
969 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000970 // If we are exited or detached, we won't ever get back to any
971 // other valid state...
972 if (state == eStateDetached || state == eStateExited)
973 return state;
974
Greg Clayton44d93782014-01-27 23:43:24 +0000975 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976
977 for (i=0; i<num_match_states; ++i)
978 {
979 if (match_states[i] == state)
980 return state;
981 }
982 }
983 return state;
984}
985
Jim Ingham30f9b212010-10-11 23:53:14 +0000986bool
987Process::HijackProcessEvents (Listener *listener)
988{
989 if (listener != NULL)
990 {
Jim Inghamcfc09352012-07-27 23:57:19 +0000991 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +0000992 }
993 else
994 return false;
995}
996
997void
998Process::RestoreProcessEvents ()
999{
1000 RestoreBroadcaster();
1001}
1002
Jim Ingham0f16e732011-02-08 05:20:59 +00001003bool
1004Process::HijackPrivateProcessEvents (Listener *listener)
1005{
1006 if (listener != NULL)
1007 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001008 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001009 }
1010 else
1011 return false;
1012}
1013
1014void
1015Process::RestorePrivateProcessEvents ()
1016{
1017 m_private_state_broadcaster.RestoreBroadcaster();
1018}
1019
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001021Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022{
Greg Clayton5160ce52013-03-27 23:08:40 +00001023 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024
1025 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001026 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1027 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028
Greg Clayton44d93782014-01-27 23:43:24 +00001029 Listener *listener = hijack_listener;
1030 if (listener == NULL)
1031 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001032
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001034 if (listener->WaitForEventForBroadcasterWithType (timeout,
1035 this,
1036 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1037 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001038 {
1039 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1040 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1041 else if (log)
1042 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1043 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044
1045 if (log)
1046 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001047 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 StateAsCString(state));
1049 return state;
1050}
1051
1052Event *
1053Process::PeekAtStateChangedEvents ()
1054{
Greg Clayton5160ce52013-03-27 23:08:40 +00001055 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056
1057 if (log)
1058 log->Printf ("Process::%s...", __FUNCTION__);
1059
1060 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001061 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1062 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063 if (log)
1064 {
1065 if (event_ptr)
1066 {
1067 log->Printf ("Process::%s (event_ptr) => %s",
1068 __FUNCTION__,
1069 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1070 }
1071 else
1072 {
1073 log->Printf ("Process::%s no events found",
1074 __FUNCTION__);
1075 }
1076 }
1077 return event_ptr;
1078}
1079
1080StateType
1081Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1082{
Greg Clayton5160ce52013-03-27 23:08:40 +00001083 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084
1085 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001086 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1087 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088
1089 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001090 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1091 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001092 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001093 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001094 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1095 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096
1097 // This is a bit of a hack, but when we wait here we could very well return
1098 // to the command-line, and that could disable the log, which would render the
1099 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001101 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1102 __FUNCTION__, static_cast<const void *>(timeout),
1103 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 return state;
1105}
1106
1107bool
1108Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1109{
Greg Clayton5160ce52013-03-27 23:08:40 +00001110 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111
1112 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001113 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1114 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115
1116 if (control_only)
1117 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1118 else
1119 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1120}
1121
1122bool
1123Process::IsRunning () const
1124{
1125 return StateIsRunningState (m_public_state.GetValue());
1126}
1127
1128int
1129Process::GetExitStatus ()
1130{
1131 if (m_public_state.GetValue() == eStateExited)
1132 return m_exit_status;
1133 return -1;
1134}
1135
Greg Clayton85851dd2010-12-04 00:10:17 +00001136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137const char *
1138Process::GetExitDescription ()
1139{
1140 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1141 return m_exit_string.c_str();
1142 return NULL;
1143}
1144
Greg Clayton6779606a2011-01-22 23:43:18 +00001145bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146Process::SetExitStatus (int status, const char *cstr)
1147{
Greg Clayton5160ce52013-03-27 23:08:40 +00001148 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001149 if (log)
1150 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1151 status, status,
1152 cstr ? "\"" : "",
1153 cstr ? cstr : "NULL",
1154 cstr ? "\"" : "");
1155
Greg Clayton6779606a2011-01-22 23:43:18 +00001156 // We were already in the exited state
1157 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001158 {
Greg Clayton385d6032011-01-26 23:47:29 +00001159 if (log)
1160 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001161 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001162 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001163
1164 m_exit_status = status;
1165 if (cstr)
1166 m_exit_string = cstr;
1167 else
1168 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001169
Greg Clayton6779606a2011-01-22 23:43:18 +00001170 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001171
Greg Clayton6779606a2011-01-22 23:43:18 +00001172 SetPrivateState (eStateExited);
1173 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174}
1175
1176// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001177// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178// found in the global target list (we want to be completely sure that the
1179// lldb_private::Process doesn't go away before we can deliver the signal.
1180bool
Greg Claytone4e45922011-11-16 05:37:56 +00001181Process::SetProcessExitStatus (void *callback_baton,
1182 lldb::pid_t pid,
1183 bool exited,
1184 int signo, // Zero for no signal
1185 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186)
1187{
Greg Clayton5160ce52013-03-27 23:08:40 +00001188 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001189 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001190 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001191 callback_baton,
1192 pid,
1193 exited,
1194 signo,
1195 exit_status);
1196
1197 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198 {
Greg Clayton66111032010-06-23 01:19:29 +00001199 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200 if (target_sp)
1201 {
1202 ProcessSP process_sp (target_sp->GetProcessSP());
1203 if (process_sp)
1204 {
1205 const char *signal_cstr = NULL;
1206 if (signo)
1207 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1208
1209 process_sp->SetExitStatus (exit_status, signal_cstr);
1210 }
1211 }
1212 return true;
1213 }
1214 return false;
1215}
1216
1217
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001218void
1219Process::UpdateThreadListIfNeeded ()
1220{
1221 const uint32_t stop_id = GetStopID();
1222 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1223 {
Greg Clayton2637f822011-11-17 01:23:07 +00001224 const StateType state = GetPrivateState();
1225 if (StateIsStoppedState (state, true))
1226 {
1227 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001228 // m_thread_list does have its own mutex, but we need to
1229 // hold onto the mutex between the call to UpdateThreadList(...)
1230 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001231 ThreadList &old_thread_list = m_thread_list;
1232 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001233 ThreadList new_thread_list(this);
1234 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001235 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001236 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001237 {
Jim Ingham09437922013-03-01 20:04:25 +00001238 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1239 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1240 // shutting us down, causing a deadlock.
1241 if (!m_destroy_in_process)
1242 {
1243 OperatingSystem *os = GetOperatingSystem ();
1244 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001245 {
1246 // Clear any old backing threads where memory threads might have been
1247 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001248 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001249 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001250 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001251
1252 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001253 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1254 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1255 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 +00001256 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001257 else
1258 {
1259 // No OS plug-in, the new thread list is the same as the real thread list
1260 new_thread_list = real_thread_list;
1261 }
Jim Ingham09437922013-03-01 20:04:25 +00001262 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001263
1264 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001265 m_thread_list.Update (new_thread_list);
1266 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001267
Jason Molenda4ff13262013-11-20 00:31:38 +00001268 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1269 {
1270 // Clear any extended threads that we may have accumulated previously
1271 m_extended_thread_list.Clear();
1272 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001273
1274 m_queue_list.Clear();
1275 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001276 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001277 }
Greg Clayton2637f822011-11-17 01:23:07 +00001278 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001279 }
1280}
1281
Jason Molenda5e8dce42013-12-13 00:29:16 +00001282void
1283Process::UpdateQueueListIfNeeded ()
1284{
1285 if (m_system_runtime_ap.get())
1286 {
1287 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1288 {
1289 const StateType state = GetPrivateState();
1290 if (StateIsStoppedState (state, true))
1291 {
1292 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1293 m_queue_list_stop_id = GetLastNaturalStopID();
1294 }
1295 }
1296 }
1297}
1298
Greg Claytona4d87472013-01-18 23:41:08 +00001299ThreadSP
1300Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1301{
1302 OperatingSystem *os = GetOperatingSystem ();
1303 if (os)
1304 return os->CreateThread(tid, context);
1305 return ThreadSP();
1306}
1307
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001308uint32_t
1309Process::GetNextThreadIndexID (uint64_t thread_id)
1310{
1311 return AssignIndexIDToThread(thread_id);
1312}
1313
1314bool
1315Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1316{
1317 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1318 if (iterator == m_thread_id_to_index_id_map.end())
1319 {
1320 return false;
1321 }
1322 else
1323 {
1324 return true;
1325 }
1326}
1327
1328uint32_t
1329Process::AssignIndexIDToThread(uint64_t thread_id)
1330{
1331 uint32_t result = 0;
1332 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1333 if (iterator == m_thread_id_to_index_id_map.end())
1334 {
1335 result = ++m_thread_index_id;
1336 m_thread_id_to_index_id_map[thread_id] = result;
1337 }
1338 else
1339 {
1340 result = iterator->second;
1341 }
1342
1343 return result;
1344}
1345
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346StateType
1347Process::GetState()
1348{
1349 // If any other threads access this we will need a mutex for it
1350 return m_public_state.GetValue ();
1351}
1352
1353void
Jim Ingham221d51c2013-05-08 00:35:16 +00001354Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355{
Greg Clayton5160ce52013-03-27 23:08:40 +00001356 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001358 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001359 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001361
1362 // On the transition from Run to Stopped, we unlock the writer end of the
1363 // run lock. The lock gets locked in Resume, which is the public API
1364 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001365 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1366 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001367 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001368 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001369 if (log)
1370 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001371 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001372 }
1373 else
1374 {
1375 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1376 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001377 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001378 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001379 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001380 {
1381 if (log)
1382 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001383 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001384 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001385 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001386 }
1387 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388}
1389
Jim Ingham3b8285d2012-04-19 01:40:33 +00001390Error
1391Process::Resume ()
1392{
Greg Clayton5160ce52013-03-27 23:08:40 +00001393 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001394 if (log)
1395 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001396 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001397 {
1398 Error error("Resume request failed - process still running.");
1399 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001400 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001401 return error;
1402 }
1403 return PrivateResume();
1404}
1405
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001406StateType
1407Process::GetPrivateState ()
1408{
1409 return m_private_state.GetValue();
1410}
1411
1412void
1413Process::SetPrivateState (StateType new_state)
1414{
Greg Clayton5160ce52013-03-27 23:08:40 +00001415 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 bool state_changed = false;
1417
1418 if (log)
1419 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1420
Andrew Kaylor29d65742013-05-10 17:19:04 +00001421 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001422 Mutex::Locker locker(m_private_state.GetMutex());
1423
1424 const StateType old_state = m_private_state.GetValueNoLock ();
1425 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001426
Greg Claytonaa49c832013-05-03 22:25:56 +00001427 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1428 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1429 if (old_state_is_stopped != new_state_is_stopped)
1430 {
1431 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001432 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001433 else
Ed Maste64fad602013-07-29 20:58:06 +00001434 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001435 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001436
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 if (state_changed)
1438 {
1439 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001440 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001442 // Note, this currently assumes that all threads in the list
1443 // stop when the process stops. In the future we will want to
1444 // support a debugging model where some threads continue to run
1445 // while others are stopped. When that happens we will either need
1446 // a way for the thread list to identify which threads are stopping
1447 // or create a special thread list containing only threads which
1448 // actually stopped.
1449 //
1450 // The process plugin is responsible for managing the actual
1451 // behavior of the threads and should have stopped any threads
1452 // that are going to stop before we get here.
1453 m_thread_list.DidStop();
1454
Jim Ingham4b536182011-08-09 02:12:22 +00001455 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001456 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001457 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001458 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001459 }
1460 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001461 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1462 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1463 else
1464 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465 }
1466 else
1467 {
1468 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001469 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470 }
1471}
1472
Jim Ingham0faa43f2011-11-08 03:00:11 +00001473void
1474Process::SetRunningUserExpression (bool on)
1475{
1476 m_mod_id.SetRunningUserExpression (on);
1477}
1478
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001479addr_t
1480Process::GetImageInfoAddress()
1481{
1482 return LLDB_INVALID_ADDRESS;
1483}
1484
Greg Clayton8f343b02010-11-04 01:54:29 +00001485//----------------------------------------------------------------------
1486// LoadImage
1487//
1488// This function provides a default implementation that works for most
1489// unix variants. Any Process subclasses that need to do shared library
1490// loading differently should override LoadImage and UnloadImage and
1491// do what is needed.
1492//----------------------------------------------------------------------
1493uint32_t
1494Process::LoadImage (const FileSpec &image_spec, Error &error)
1495{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001496 char path[PATH_MAX];
1497 image_spec.GetPath(path, sizeof(path));
1498
Greg Clayton8f343b02010-11-04 01:54:29 +00001499 DynamicLoader *loader = GetDynamicLoader();
1500 if (loader)
1501 {
1502 error = loader->CanLoadImage();
1503 if (error.Fail())
1504 return LLDB_INVALID_IMAGE_TOKEN;
1505 }
1506
1507 if (error.Success())
1508 {
1509 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001510
1511 if (thread_sp)
1512 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001513 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001514
1515 if (frame_sp)
1516 {
1517 ExecutionContext exe_ctx;
1518 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001519 EvaluateExpressionOptions expr_options;
1520 expr_options.SetUnwindOnError(true);
1521 expr_options.SetIgnoreBreakpoints(true);
1522 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001523 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001524 expr.Printf("dlopen (\"%s\", 2)", path);
1525 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001526 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001527 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001528 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001529 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001530 expr.GetData(),
1531 prefix,
1532 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001533 expr_error);
1534 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001535 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001536 error = result_valobj_sp->GetError();
1537 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001538 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001539 Scalar scalar;
1540 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001541 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001542 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1543 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1544 {
1545 uint32_t image_token = m_image_tokens.size();
1546 m_image_tokens.push_back (image_ptr);
1547 return image_token;
1548 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001549 }
1550 }
1551 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001552 else
1553 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001554 }
1555 }
1556 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001557 if (!error.AsCString())
1558 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001559 return LLDB_INVALID_IMAGE_TOKEN;
1560}
1561
1562//----------------------------------------------------------------------
1563// UnloadImage
1564//
1565// This function provides a default implementation that works for most
1566// unix variants. Any Process subclasses that need to do shared library
1567// loading differently should override LoadImage and UnloadImage and
1568// do what is needed.
1569//----------------------------------------------------------------------
1570Error
1571Process::UnloadImage (uint32_t image_token)
1572{
1573 Error error;
1574 if (image_token < m_image_tokens.size())
1575 {
1576 const addr_t image_addr = m_image_tokens[image_token];
1577 if (image_addr == LLDB_INVALID_ADDRESS)
1578 {
1579 error.SetErrorString("image already unloaded");
1580 }
1581 else
1582 {
1583 DynamicLoader *loader = GetDynamicLoader();
1584 if (loader)
1585 error = loader->CanLoadImage();
1586
1587 if (error.Success())
1588 {
1589 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001590
1591 if (thread_sp)
1592 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001593 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001594
1595 if (frame_sp)
1596 {
1597 ExecutionContext exe_ctx;
1598 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001599 EvaluateExpressionOptions expr_options;
1600 expr_options.SetUnwindOnError(true);
1601 expr_options.SetIgnoreBreakpoints(true);
1602 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001603 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001604 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001605 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001606 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001607 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001608 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001609 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001610 expr.GetData(),
1611 prefix,
1612 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001613 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001614 if (result_valobj_sp->GetError().Success())
1615 {
1616 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001617 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001618 {
1619 if (scalar.UInt(1))
1620 {
1621 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1622 }
1623 else
1624 {
1625 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1626 }
1627 }
1628 }
1629 else
1630 {
1631 error = result_valobj_sp->GetError();
1632 }
1633 }
1634 }
1635 }
1636 }
1637 }
1638 else
1639 {
1640 error.SetErrorString("invalid image token");
1641 }
1642 return error;
1643}
1644
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001645const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001646Process::GetABI()
1647{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001648 if (!m_abi_sp)
1649 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1650 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001651}
1652
Jim Ingham22777012010-09-23 02:01:19 +00001653LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001654Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001655{
1656 LanguageRuntimeCollection::iterator pos;
1657 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001658 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001659 {
Jim Inghamab175242012-03-10 00:22:19 +00001660 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001661
Jim Inghamab175242012-03-10 00:22:19 +00001662 m_language_runtimes[language] = runtime_sp;
1663 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001664 }
1665 else
1666 return (*pos).second.get();
1667}
1668
1669CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001670Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001671{
Jim Inghamab175242012-03-10 00:22:19 +00001672 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001673 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1674 return static_cast<CPPLanguageRuntime *> (runtime);
1675 return NULL;
1676}
1677
1678ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001679Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001680{
Jim Inghamab175242012-03-10 00:22:19 +00001681 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001682 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1683 return static_cast<ObjCLanguageRuntime *> (runtime);
1684 return NULL;
1685}
1686
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001687bool
1688Process::IsPossibleDynamicValue (ValueObject& in_value)
1689{
1690 if (in_value.IsDynamic())
1691 return false;
1692 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1693
1694 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1695 {
1696 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1697 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1698 }
1699
1700 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1701 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1702 return true;
1703
1704 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1705 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1706}
1707
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001708BreakpointSiteList &
1709Process::GetBreakpointSiteList()
1710{
1711 return m_breakpoint_site_list;
1712}
1713
1714const BreakpointSiteList &
1715Process::GetBreakpointSiteList() const
1716{
1717 return m_breakpoint_site_list;
1718}
1719
1720
1721void
1722Process::DisableAllBreakpointSites ()
1723{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001724 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1725// bp_site->SetEnabled(true);
1726 DisableBreakpointSite(bp_site);
1727 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728}
1729
1730Error
1731Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1732{
1733 Error error (DisableBreakpointSiteByID (break_id));
1734
1735 if (error.Success())
1736 m_breakpoint_site_list.Remove(break_id);
1737
1738 return error;
1739}
1740
1741Error
1742Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1743{
1744 Error error;
1745 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1746 if (bp_site_sp)
1747 {
1748 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001749 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750 }
1751 else
1752 {
Daniel Malead01b2952012-11-29 21:49:15 +00001753 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754 }
1755
1756 return error;
1757}
1758
1759Error
1760Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1761{
1762 Error error;
1763 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1764 if (bp_site_sp)
1765 {
1766 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001767 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001768 }
1769 else
1770 {
Daniel Malead01b2952012-11-29 21:49:15 +00001771 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001772 }
1773 return error;
1774}
1775
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001776lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001777Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001778{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001779 addr_t load_addr = LLDB_INVALID_ADDRESS;
1780
1781 bool show_error = true;
1782 switch (GetState())
1783 {
1784 case eStateInvalid:
1785 case eStateUnloaded:
1786 case eStateConnected:
1787 case eStateAttaching:
1788 case eStateLaunching:
1789 case eStateDetached:
1790 case eStateExited:
1791 show_error = false;
1792 break;
1793
1794 case eStateStopped:
1795 case eStateRunning:
1796 case eStateStepping:
1797 case eStateCrashed:
1798 case eStateSuspended:
1799 show_error = IsAlive();
1800 break;
1801 }
1802
1803 // Reset the IsIndirect flag here, in case the location changes from
1804 // pointing to a indirect symbol to a regular symbol.
1805 owner->SetIsIndirect (false);
1806
1807 if (owner->ShouldResolveIndirectFunctions())
1808 {
1809 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1810 if (symbol && symbol->IsIndirect())
1811 {
1812 Error error;
1813 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1814 if (!error.Success() && show_error)
1815 {
Greg Clayton44d93782014-01-27 23:43:24 +00001816 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1817 symbol->GetAddress().GetLoadAddress(&m_target),
1818 owner->GetBreakpoint().GetID(),
1819 owner->GetID(),
1820 error.AsCString() ? error.AsCString() : "unkown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001821 return LLDB_INVALID_BREAK_ID;
1822 }
1823 Address resolved_address(load_addr);
1824 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1825 owner->SetIsIndirect(true);
1826 }
1827 else
1828 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1829 }
1830 else
1831 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1832
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833 if (load_addr != LLDB_INVALID_ADDRESS)
1834 {
1835 BreakpointSiteSP bp_site_sp;
1836
1837 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1838 // create a new breakpoint site and add it.
1839
1840 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1841
1842 if (bp_site_sp)
1843 {
1844 bp_site_sp->AddOwner (owner);
1845 owner->SetBreakpointSite (bp_site_sp);
1846 return bp_site_sp->GetID();
1847 }
1848 else
1849 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001850 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001851 if (bp_site_sp)
1852 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001853 Error error = EnableBreakpointSite (bp_site_sp.get());
1854 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855 {
1856 owner->SetBreakpointSite (bp_site_sp);
1857 return m_breakpoint_site_list.Add (bp_site_sp);
1858 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001859 else
1860 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001861 if (show_error)
1862 {
1863 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001864 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1865 load_addr,
1866 owner->GetBreakpoint().GetID(),
1867 owner->GetID(),
1868 error.AsCString() ? error.AsCString() : "unkown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001869 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001870 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871 }
1872 }
1873 }
1874 // We failed to enable the breakpoint
1875 return LLDB_INVALID_BREAK_ID;
1876
1877}
1878
1879void
1880Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1881{
1882 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1883 if (num_owners == 0)
1884 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001885 // Don't try to disable the site if we don't have a live process anymore.
1886 if (IsAlive())
1887 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1889 }
1890}
1891
1892
1893size_t
1894Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1895{
1896 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001897 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001898
Jim Ingham20c77192011-06-29 19:42:28 +00001899 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001900 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001901 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1902 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001903 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001904 addr_t intersect_addr;
1905 size_t intersect_size;
1906 size_t opcode_offset;
1907 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001908 {
1909 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1910 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00001911 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001912 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00001913 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001914 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00001916 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001917 }
1918 return bytes_removed;
1919}
1920
1921
Greg Claytonded470d2011-03-19 01:12:21 +00001922
1923size_t
1924Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1925{
1926 PlatformSP platform_sp (m_target.GetPlatform());
1927 if (platform_sp)
1928 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1929 return 0;
1930}
1931
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001932Error
1933Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1934{
1935 Error error;
1936 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00001937 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938 const addr_t bp_addr = bp_site->GetLoadAddress();
1939 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001940 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941 if (bp_site->IsEnabled())
1942 {
1943 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001944 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 +00001945 return error;
1946 }
1947
1948 if (bp_addr == LLDB_INVALID_ADDRESS)
1949 {
1950 error.SetErrorString("BreakpointSite contains an invalid load address.");
1951 return error;
1952 }
1953 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1954 // trap for the breakpoint site
1955 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1956
1957 if (bp_opcode_size == 0)
1958 {
Daniel Malead01b2952012-11-29 21:49:15 +00001959 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 }
1961 else
1962 {
1963 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1964
1965 if (bp_opcode_bytes == NULL)
1966 {
1967 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1968 return error;
1969 }
1970
1971 // Save the original opcode by reading it
1972 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1973 {
1974 // Write a software breakpoint in place of the original opcode
1975 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1976 {
1977 uint8_t verify_bp_opcode_bytes[64];
1978 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1979 {
1980 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1981 {
1982 bp_site->SetEnabled(true);
1983 bp_site->SetType (BreakpointSite::eSoftware);
1984 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001985 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986 bp_site->GetID(),
1987 (uint64_t)bp_addr);
1988 }
1989 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001990 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001991 }
1992 else
1993 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1994 }
1995 else
1996 error.SetErrorString("Unable to write breakpoint trap to memory.");
1997 }
1998 else
1999 error.SetErrorString("Unable to read memory at breakpoint address.");
2000 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002001 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002002 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003 bp_site->GetID(),
2004 (uint64_t)bp_addr,
2005 error.AsCString());
2006 return error;
2007}
2008
2009Error
2010Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2011{
2012 Error error;
2013 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002014 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002015 addr_t bp_addr = bp_site->GetLoadAddress();
2016 lldb::user_id_t breakID = bp_site->GetID();
2017 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002018 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002019
2020 if (bp_site->IsHardware())
2021 {
2022 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2023 }
2024 else if (bp_site->IsEnabled())
2025 {
2026 const size_t break_op_size = bp_site->GetByteSize();
2027 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2028 if (break_op_size > 0)
2029 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002030 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002031 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002032 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002033 bool break_op_found = false;
2034
2035 // Read the breakpoint opcode
2036 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2037 {
2038 bool verify = false;
2039 // Make sure we have the a breakpoint opcode exists at this address
2040 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2041 {
2042 break_op_found = true;
2043 // We found a valid breakpoint opcode at this address, now restore
2044 // the saved opcode.
2045 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2046 {
2047 verify = true;
2048 }
2049 else
2050 error.SetErrorString("Memory write failed when restoring original opcode.");
2051 }
2052 else
2053 {
2054 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2055 // Set verify to true and so we can check if the original opcode has already been restored
2056 verify = true;
2057 }
2058
2059 if (verify)
2060 {
Greg Claytonc982c762010-07-09 20:39:50 +00002061 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002062 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002063 // Verify that our original opcode made it back to the inferior
2064 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2065 {
2066 // compare the memory we just read with the original opcode
2067 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2068 {
2069 // SUCCESS
2070 bp_site->SetEnabled(false);
2071 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002072 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 +00002073 return error;
2074 }
2075 else
2076 {
2077 if (break_op_found)
2078 error.SetErrorString("Failed to restore original opcode.");
2079 }
2080 }
2081 else
2082 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2083 }
2084 }
2085 else
2086 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2087 }
2088 }
2089 else
2090 {
2091 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002092 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 +00002093 return error;
2094 }
2095
2096 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002097 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 bp_site->GetID(),
2099 (uint64_t)bp_addr,
2100 error.AsCString());
2101 return error;
2102
2103}
2104
Greg Clayton58be07b2011-01-07 06:08:19 +00002105// Uncomment to verify memory caching works after making changes to caching code
2106//#define VERIFY_MEMORY_READS
2107
Sean Callanan64c0cf22012-06-07 22:26:42 +00002108size_t
2109Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2110{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002111 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002112 if (!GetDisableMemoryCache())
2113 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002114#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002115 // Memory caching is enabled, with debug verification
2116
2117 if (buf && size)
2118 {
2119 // Uncomment the line below to make sure memory caching is working.
2120 // I ran this through the test suite and got no assertions, so I am
2121 // pretty confident this is working well. If any changes are made to
2122 // memory caching, uncomment the line below and test your changes!
2123
2124 // Verify all memory reads by using the cache first, then redundantly
2125 // reading the same memory from the inferior and comparing to make sure
2126 // everything is exactly the same.
2127 std::string verify_buf (size, '\0');
2128 assert (verify_buf.size() == size);
2129 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2130 Error verify_error;
2131 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2132 assert (cache_bytes_read == verify_bytes_read);
2133 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2134 assert (verify_error.Success() == error.Success());
2135 return cache_bytes_read;
2136 }
2137 return 0;
2138#else // !defined(VERIFY_MEMORY_READS)
2139 // Memory caching is enabled, without debug verification
2140
2141 return m_memory_cache.Read (addr, buf, size, error);
2142#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002143 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002144 else
2145 {
2146 // Memory caching is disabled
2147
2148 return ReadMemoryFromInferior (addr, buf, size, error);
2149 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002150}
Greg Clayton58be07b2011-01-07 06:08:19 +00002151
Greg Clayton4c82d422012-05-18 23:20:01 +00002152size_t
2153Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2154{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002155 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002156 out_str.clear();
2157 addr_t curr_addr = addr;
2158 while (1)
2159 {
2160 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2161 if (length == 0)
2162 break;
2163 out_str.append(buf, length);
2164 // If we got "length - 1" bytes, we didn't get the whole C string, we
2165 // need to read some more characters
2166 if (length == sizeof(buf) - 1)
2167 curr_addr += length;
2168 else
2169 break;
2170 }
2171 return out_str.size();
2172}
2173
Greg Clayton58be07b2011-01-07 06:08:19 +00002174
2175size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002176Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2177 size_t type_width)
2178{
2179 size_t total_bytes_read = 0;
2180 if (dst && max_bytes && type_width && max_bytes >= type_width)
2181 {
2182 // Ensure a null terminator independent of the number of bytes that is read.
2183 memset (dst, 0, max_bytes);
2184 size_t bytes_left = max_bytes - type_width;
2185
2186 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2187 assert(sizeof(terminator) >= type_width &&
2188 "Attempting to validate a string with more than 4 bytes per character!");
2189
2190 addr_t curr_addr = addr;
2191 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2192 char *curr_dst = dst;
2193
2194 error.Clear();
2195 while (bytes_left > 0 && error.Success())
2196 {
2197 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2198 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2199 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2200
2201 if (bytes_read == 0)
2202 break;
2203
2204 // Search for a null terminator of correct size and alignment in bytes_read
2205 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2206 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2207 if (::strncmp(&dst[i], terminator, type_width) == 0)
2208 {
2209 error.Clear();
2210 return i;
2211 }
2212
2213 total_bytes_read += bytes_read;
2214 curr_dst += bytes_read;
2215 curr_addr += bytes_read;
2216 bytes_left -= bytes_read;
2217 }
2218 }
2219 else
2220 {
2221 if (max_bytes)
2222 error.SetErrorString("invalid arguments");
2223 }
2224 return total_bytes_read;
2225}
2226
2227// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2228// null terminators.
2229size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002230Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002231{
2232 size_t total_cstr_len = 0;
2233 if (dst && dst_max_len)
2234 {
Greg Claytone91b7952011-12-15 03:14:23 +00002235 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002236 // NULL out everything just to be safe
2237 memset (dst, 0, dst_max_len);
2238 Error error;
2239 addr_t curr_addr = addr;
2240 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2241 size_t bytes_left = dst_max_len - 1;
2242 char *curr_dst = dst;
2243
2244 while (bytes_left > 0)
2245 {
2246 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2247 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2248 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2249
2250 if (bytes_read == 0)
2251 {
Greg Claytone91b7952011-12-15 03:14:23 +00002252 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002253 dst[total_cstr_len] = '\0';
2254 break;
2255 }
2256 const size_t len = strlen(curr_dst);
2257
2258 total_cstr_len += len;
2259
2260 if (len < bytes_to_read)
2261 break;
2262
2263 curr_dst += bytes_read;
2264 curr_addr += bytes_read;
2265 bytes_left -= bytes_read;
2266 }
2267 }
Greg Claytone91b7952011-12-15 03:14:23 +00002268 else
2269 {
2270 if (dst == NULL)
2271 result_error.SetErrorString("invalid arguments");
2272 else
2273 result_error.Clear();
2274 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002275 return total_cstr_len;
2276}
2277
2278size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002279Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2280{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 if (buf == NULL || size == 0)
2282 return 0;
2283
2284 size_t bytes_read = 0;
2285 uint8_t *bytes = (uint8_t *)buf;
2286
2287 while (bytes_read < size)
2288 {
2289 const size_t curr_size = size - bytes_read;
2290 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2291 bytes + bytes_read,
2292 curr_size,
2293 error);
2294 bytes_read += curr_bytes_read;
2295 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2296 break;
2297 }
2298
2299 // Replace any software breakpoint opcodes that fall into this range back
2300 // into "buf" before we return
2301 if (bytes_read > 0)
2302 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2303 return bytes_read;
2304}
2305
Greg Clayton58a4c462010-12-16 20:01:20 +00002306uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002307Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002308{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002309 Scalar scalar;
2310 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2311 return scalar.ULongLong(fail_value);
2312 return fail_value;
2313}
2314
2315addr_t
2316Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2317{
2318 Scalar scalar;
2319 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2320 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2321 return LLDB_INVALID_ADDRESS;
2322}
2323
2324
2325bool
2326Process::WritePointerToMemory (lldb::addr_t vm_addr,
2327 lldb::addr_t ptr_value,
2328 Error &error)
2329{
2330 Scalar scalar;
2331 const uint32_t addr_byte_size = GetAddressByteSize();
2332 if (addr_byte_size <= 4)
2333 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002334 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002335 scalar = ptr_value;
2336 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002337}
2338
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339size_t
2340Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2341{
2342 size_t bytes_written = 0;
2343 const uint8_t *bytes = (const uint8_t *)buf;
2344
2345 while (bytes_written < size)
2346 {
2347 const size_t curr_size = size - bytes_written;
2348 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2349 bytes + bytes_written,
2350 curr_size,
2351 error);
2352 bytes_written += curr_bytes_written;
2353 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2354 break;
2355 }
2356 return bytes_written;
2357}
2358
2359size_t
2360Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2361{
Greg Clayton58be07b2011-01-07 06:08:19 +00002362#if defined (ENABLE_MEMORY_CACHING)
2363 m_memory_cache.Flush (addr, size);
2364#endif
2365
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 if (buf == NULL || size == 0)
2367 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002368
Jim Ingham4b536182011-08-09 02:12:22 +00002369 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002370
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371 // We need to write any data that would go where any current software traps
2372 // (enabled software breakpoints) any software traps (breakpoints) that we
2373 // may have placed in our tasks memory.
2374
Greg Claytond8cf1a12013-06-12 00:46:38 +00002375 BreakpointSiteList bp_sites_in_range;
2376
2377 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002379 // No breakpoint sites overlap
2380 if (bp_sites_in_range.IsEmpty())
2381 return WriteMemoryPrivate (addr, buf, size, error);
2382 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002384 const uint8_t *ubuf = (const uint8_t *)buf;
2385 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386
Greg Claytond8cf1a12013-06-12 00:46:38 +00002387 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2388
2389 if (error.Success())
2390 {
2391 addr_t intersect_addr;
2392 size_t intersect_size;
2393 size_t opcode_offset;
2394 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2395 assert(intersects);
2396 assert(addr <= intersect_addr && intersect_addr < addr + size);
2397 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2398 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2399
2400 // Check for bytes before this breakpoint
2401 const addr_t curr_addr = addr + bytes_written;
2402 if (intersect_addr > curr_addr)
2403 {
2404 // There are some bytes before this breakpoint that we need to
2405 // just write to memory
2406 size_t curr_size = intersect_addr - curr_addr;
2407 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2408 ubuf + bytes_written,
2409 curr_size,
2410 error);
2411 bytes_written += curr_bytes_written;
2412 if (curr_bytes_written != curr_size)
2413 {
2414 // We weren't able to write all of the requested bytes, we
2415 // are done looping and will return the number of bytes that
2416 // we have written so far.
2417 if (error.Success())
2418 error.SetErrorToGenericError();
2419 }
2420 }
2421 // Now write any bytes that would cover up any software breakpoints
2422 // directly into the breakpoint opcode buffer
2423 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2424 bytes_written += intersect_size;
2425 }
2426 });
2427
2428 if (bytes_written < size)
2429 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2430 ubuf + bytes_written,
2431 size - bytes_written,
2432 error);
2433 }
2434 }
2435 else
2436 {
2437 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002438 }
2439
2440 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002441 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002442}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002443
2444size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002445Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002446{
2447 if (byte_size == UINT32_MAX)
2448 byte_size = scalar.GetByteSize();
2449 if (byte_size > 0)
2450 {
2451 uint8_t buf[32];
2452 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2453 if (mem_size > 0)
2454 return WriteMemory(addr, buf, mem_size, error);
2455 else
2456 error.SetErrorString ("failed to get scalar as memory data");
2457 }
2458 else
2459 {
2460 error.SetErrorString ("invalid scalar value");
2461 }
2462 return 0;
2463}
2464
2465size_t
2466Process::ReadScalarIntegerFromMemory (addr_t addr,
2467 uint32_t byte_size,
2468 bool is_signed,
2469 Scalar &scalar,
2470 Error &error)
2471{
Greg Clayton7060f892013-05-01 23:41:30 +00002472 uint64_t uval = 0;
2473 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002474 {
Greg Clayton7060f892013-05-01 23:41:30 +00002475 error.SetErrorString ("byte size is zero");
2476 }
2477 else if (byte_size & (byte_size - 1))
2478 {
2479 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2480 }
2481 else if (byte_size <= sizeof(uval))
2482 {
2483 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002484 if (bytes_read == byte_size)
2485 {
2486 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002487 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002488 if (byte_size <= 4)
2489 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002490 else
Greg Clayton7060f892013-05-01 23:41:30 +00002491 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002492 if (is_signed)
2493 scalar.SignExtend(byte_size * 8);
2494 return bytes_read;
2495 }
2496 }
2497 else
2498 {
2499 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2500 }
2501 return 0;
2502}
2503
Greg Claytond495c532011-05-17 03:37:42 +00002504#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002505addr_t
2506Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2507{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002508 if (GetPrivateState() != eStateStopped)
2509 return LLDB_INVALID_ADDRESS;
2510
Greg Claytond495c532011-05-17 03:37:42 +00002511#if defined (USE_ALLOCATE_MEMORY_CACHE)
2512 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2513#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002514 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002515 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002516 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002517 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 +00002518 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002519 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002520 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002521 m_mod_id.GetStopID(),
2522 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002523 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002524#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002525}
2526
Sean Callanan90539452011-09-20 23:01:51 +00002527bool
2528Process::CanJIT ()
2529{
Sean Callanana7b443a2012-02-14 22:50:38 +00002530 if (m_can_jit == eCanJITDontKnow)
2531 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002532 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002533 Error err;
2534
2535 uint64_t allocated_memory = AllocateMemory(8,
2536 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2537 err);
2538
2539 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002540 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002541 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002542 if (log)
2543 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2544 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002545 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002546 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002547 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002548 if (log)
2549 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2550 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002551
2552 DeallocateMemory (allocated_memory);
2553 }
2554
Sean Callanan90539452011-09-20 23:01:51 +00002555 return m_can_jit == eCanJITYes;
2556}
2557
2558void
2559Process::SetCanJIT (bool can_jit)
2560{
2561 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2562}
2563
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002564Error
2565Process::DeallocateMemory (addr_t ptr)
2566{
Greg Claytond495c532011-05-17 03:37:42 +00002567 Error error;
2568#if defined (USE_ALLOCATE_MEMORY_CACHE)
2569 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2570 {
Daniel Malead01b2952012-11-29 21:49:15 +00002571 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002572 }
2573#else
2574 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002575
Greg Clayton5160ce52013-03-27 23:08:40 +00002576 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002577 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002578 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 +00002579 ptr,
2580 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002581 m_mod_id.GetStopID(),
2582 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002583#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002584 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585}
2586
Han Ming Ongc811d382012-11-17 00:33:14 +00002587
Greg Claytonc9660542012-02-05 02:38:54 +00002588ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002589Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002590 lldb::addr_t header_addr,
2591 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002592{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002593 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002594 if (module_sp)
2595 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002596 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002597 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002598 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002599 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002600 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002601 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002602}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002603
2604Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002605Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002606{
2607 Error error;
2608 error.SetErrorString("watchpoints are not supported");
2609 return error;
2610}
2611
2612Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002613Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614{
2615 Error error;
2616 error.SetErrorString("watchpoints are not supported");
2617 return error;
2618}
2619
2620StateType
2621Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2622{
2623 StateType state;
2624 // Now wait for the process to launch and return control to us, and then
2625 // call DidLaunch:
2626 while (1)
2627 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002628 event_sp.reset();
2629 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2630
Greg Clayton2637f822011-11-17 01:23:07 +00002631 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002633
2634 // If state is invalid, then we timed out
2635 if (state == eStateInvalid)
2636 break;
2637
2638 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002639 HandlePrivateEvent (event_sp);
2640 }
2641 return state;
2642}
2643
2644Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002645Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002646{
2647 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002648 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002649 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002650 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002651 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002652 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002653 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654
Greg Claytonaa149cb2011-08-11 02:48:45 +00002655 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002656 if (exe_module)
2657 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002658 char local_exec_file_path[PATH_MAX];
2659 char platform_exec_file_path[PATH_MAX];
2660 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2661 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662 if (exe_module->GetFileSpec().Exists())
2663 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002664 // Install anything that might need to be installed prior to launching.
2665 // For host systems, this will do nothing, but if we are connected to a
2666 // remote platform it will install any needed binaries
2667 error = GetTarget().Install(&launch_info);
2668 if (error.Fail())
2669 return error;
2670
Greg Clayton71337622011-02-24 22:24:29 +00002671 if (PrivateStateThreadIsValid ())
2672 PausePrivateStateThread ();
2673
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002674 error = WillLaunch (exe_module);
2675 if (error.Success())
2676 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002677 const bool restarted = false;
2678 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002679 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002680
Ed Maste64fad602013-07-29 20:58:06 +00002681 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002682 {
2683 // Now launch using these arguments.
2684 error = DoLaunch (exe_module, launch_info);
2685 }
2686 else
2687 {
2688 // This shouldn't happen
2689 error.SetErrorString("failed to acquire process run lock");
2690 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691
2692 if (error.Fail())
2693 {
2694 if (GetID() != LLDB_INVALID_PROCESS_ID)
2695 {
2696 SetID (LLDB_INVALID_PROCESS_ID);
2697 const char *error_string = error.AsCString();
2698 if (error_string == NULL)
2699 error_string = "launch failed";
2700 SetExitStatus (-1, error_string);
2701 }
2702 }
2703 else
2704 {
2705 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002706 TimeValue timeout_time;
2707 timeout_time = TimeValue::Now();
2708 timeout_time.OffsetWithSeconds(10);
2709 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710
Greg Clayton1a38ea72011-06-22 01:42:17 +00002711 if (state == eStateInvalid || event_sp.get() == NULL)
2712 {
2713 // We were able to launch the process, but we failed to
2714 // catch the initial stop.
2715 SetExitStatus (0, "failed to catch stop after launch");
2716 Destroy();
2717 }
2718 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002720
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721 DidLaunch ();
2722
Greg Claytonc859e2d2012-02-13 23:10:39 +00002723 DynamicLoader *dyld = GetDynamicLoader ();
2724 if (dyld)
2725 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002726
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002727 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002728
Jason Molendaeef51062013-11-05 03:57:19 +00002729 SystemRuntime *system_runtime = GetSystemRuntime ();
2730 if (system_runtime)
2731 system_runtime->DidLaunch();
2732
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002733 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734 // This delays passing the stopped event to listeners till DidLaunch gets
2735 // a chance to complete...
2736 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002737
2738 if (PrivateStateThreadIsValid ())
2739 ResumePrivateStateThread ();
2740 else
2741 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742 }
2743 else if (state == eStateExited)
2744 {
2745 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2746 // not likely to work, and return an invalid pid.
2747 HandlePrivateEvent (event_sp);
2748 }
2749 }
2750 }
2751 }
2752 else
2753 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002754 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002755 }
2756 }
2757 return error;
2758}
2759
Greg Claytonc3776bf2012-02-09 06:16:32 +00002760
2761Error
2762Process::LoadCore ()
2763{
2764 Error error = DoLoadCore();
2765 if (error.Success())
2766 {
2767 if (PrivateStateThreadIsValid ())
2768 ResumePrivateStateThread ();
2769 else
2770 StartPrivateStateThread ();
2771
Greg Claytonc859e2d2012-02-13 23:10:39 +00002772 DynamicLoader *dyld = GetDynamicLoader ();
2773 if (dyld)
2774 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002775
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002776 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002777
Jason Molendaeef51062013-11-05 03:57:19 +00002778 SystemRuntime *system_runtime = GetSystemRuntime ();
2779 if (system_runtime)
2780 system_runtime->DidAttach();
2781
Greg Claytonc859e2d2012-02-13 23:10:39 +00002782 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002783 // We successfully loaded a core file, now pretend we stopped so we can
2784 // show all of the threads in the core file and explore the crashed
2785 // state.
2786 SetPrivateState (eStateStopped);
2787
2788 }
2789 return error;
2790}
2791
Greg Claytonc859e2d2012-02-13 23:10:39 +00002792DynamicLoader *
2793Process::GetDynamicLoader ()
2794{
2795 if (m_dyld_ap.get() == NULL)
2796 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2797 return m_dyld_ap.get();
2798}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002799
Todd Fialaaf245d12014-06-30 21:05:18 +00002800const lldb::DataBufferSP
2801Process::GetAuxvData()
2802{
2803 return DataBufferSP ();
2804}
2805
Andrew MacPherson17220c12014-03-05 10:12:43 +00002806JITLoaderList &
2807Process::GetJITLoaders ()
2808{
2809 if (!m_jit_loaders_ap)
2810 {
2811 m_jit_loaders_ap.reset(new JITLoaderList());
2812 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2813 }
2814 return *m_jit_loaders_ap;
2815}
2816
Jason Molendaeef51062013-11-05 03:57:19 +00002817SystemRuntime *
2818Process::GetSystemRuntime ()
2819{
2820 if (m_system_runtime_ap.get() == NULL)
2821 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2822 return m_system_runtime_ap.get();
2823}
2824
Greg Claytonc3776bf2012-02-09 06:16:32 +00002825
Jim Inghambb3a2832011-01-29 01:49:25 +00002826Process::NextEventAction::EventActionResult
2827Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828{
Jim Inghambb3a2832011-01-29 01:49:25 +00002829 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2830 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002831 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002832 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002833 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002834 return eEventActionRetry;
2835
2836 case eStateStopped:
2837 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002838 {
2839 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002840 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002841 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002842 // We don't want these events to be reported, so go set the ShouldReportStop here:
2843 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2844
Greg Claytonc9ed4782011-11-12 02:10:56 +00002845 if (m_exec_count > 0)
2846 {
2847 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00002848 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002849 return eEventActionRetry;
2850 }
2851 else
2852 {
2853 m_process->CompleteAttach ();
2854 return eEventActionSuccess;
2855 }
2856 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002857 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002858
Greg Clayton513c26c2011-01-29 07:10:55 +00002859 default:
2860 case eStateExited:
2861 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002862 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002863 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002864
2865 m_exit_string.assign ("No valid Process");
2866 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002867}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868
Jim Inghambb3a2832011-01-29 01:49:25 +00002869Process::NextEventAction::EventActionResult
2870Process::AttachCompletionHandler::HandleBeingInterrupted()
2871{
2872 return eEventActionSuccess;
2873}
2874
2875const char *
2876Process::AttachCompletionHandler::GetExitString ()
2877{
2878 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879}
2880
2881Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002882Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002885 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002886 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002887 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002888 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002889 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002890
Greg Clayton144f3a92011-11-15 03:53:30 +00002891 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002892 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002893 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002894 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002895 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002896
Greg Clayton144f3a92011-11-15 03:53:30 +00002897 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002898 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002899 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2900
2901 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002902 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002903 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2904 if (error.Success())
2905 {
Ed Maste64fad602013-07-29 20:58:06 +00002906 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002907 {
2908 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002909 const bool restarted = false;
2910 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002911 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00002912 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00002913 }
2914 else
2915 {
2916 // This shouldn't happen
2917 error.SetErrorString("failed to acquire process run lock");
2918 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002919
Greg Clayton144f3a92011-11-15 03:53:30 +00002920 if (error.Fail())
2921 {
2922 if (GetID() != LLDB_INVALID_PROCESS_ID)
2923 {
2924 SetID (LLDB_INVALID_PROCESS_ID);
2925 if (error.AsCString() == NULL)
2926 error.SetErrorString("attach failed");
2927
2928 SetExitStatus(-1, error.AsCString());
2929 }
2930 }
2931 else
2932 {
2933 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2934 StartPrivateStateThread();
2935 }
2936 return error;
2937 }
Greg Claytone996fd32011-03-08 22:40:15 +00002938 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002939 else
Greg Claytone996fd32011-03-08 22:40:15 +00002940 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002941 ProcessInstanceInfoList process_infos;
2942 PlatformSP platform_sp (m_target.GetPlatform ());
2943
2944 if (platform_sp)
2945 {
2946 ProcessInstanceInfoMatch match_info;
2947 match_info.GetProcessInfo() = attach_info;
2948 match_info.SetNameMatchType (eNameMatchEquals);
2949 platform_sp->FindProcesses (match_info, process_infos);
2950 const uint32_t num_matches = process_infos.GetSize();
2951 if (num_matches == 1)
2952 {
2953 attach_pid = process_infos.GetProcessIDAtIndex(0);
2954 // Fall through and attach using the above process ID
2955 }
2956 else
2957 {
2958 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2959 if (num_matches > 1)
2960 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2961 else
2962 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2963 }
2964 }
2965 else
2966 {
2967 error.SetErrorString ("invalid platform, can't find processes by name");
2968 return error;
2969 }
Greg Claytone996fd32011-03-08 22:40:15 +00002970 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971 }
2972 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002973 {
2974 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002975 }
2976 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002977
2978 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002979 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002980 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002981 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002983
Ed Maste64fad602013-07-29 20:58:06 +00002984 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002985 {
2986 // Now attach using these arguments.
2987 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002988 const bool restarted = false;
2989 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002990 error = DoAttachToProcessWithID (attach_pid, attach_info);
2991 }
2992 else
2993 {
2994 // This shouldn't happen
2995 error.SetErrorString("failed to acquire process run lock");
2996 }
2997
Greg Clayton144f3a92011-11-15 03:53:30 +00002998 if (error.Success())
2999 {
3000
3001 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3002 StartPrivateStateThread();
3003 }
3004 else
Greg Claytone996fd32011-03-08 22:40:15 +00003005 {
3006 if (GetID() != LLDB_INVALID_PROCESS_ID)
3007 {
3008 SetID (LLDB_INVALID_PROCESS_ID);
3009 const char *error_string = error.AsCString();
3010 if (error_string == NULL)
3011 error_string = "attach failed";
3012
3013 SetExitStatus(-1, error_string);
3014 }
3015 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 }
3017 }
3018 return error;
3019}
3020
Greg Clayton93d3c8332011-02-16 04:46:07 +00003021void
3022Process::CompleteAttach ()
3023{
3024 // Let the process subclass figure out at much as it can about the process
3025 // before we go looking for a dynamic loader plug-in.
3026 DidAttach();
3027
Jim Ingham4299fdb2011-09-15 01:10:17 +00003028 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3029 // the same as the one we've already set, switch architectures.
3030 PlatformSP platform_sp (m_target.GetPlatform ());
3031 assert (platform_sp.get());
3032 if (platform_sp)
3033 {
Greg Clayton70512312012-05-08 01:45:38 +00003034 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003035 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003036 {
3037 ArchSpec platform_arch;
3038 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3039 if (platform_sp)
3040 {
3041 m_target.SetPlatform (platform_sp);
3042 m_target.SetArchitecture(platform_arch);
3043 }
3044 }
3045 else
3046 {
3047 ProcessInstanceInfo process_info;
3048 platform_sp->GetProcessInfo (GetID(), process_info);
3049 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003050 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003051 m_target.SetArchitecture (process_arch);
3052 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003053 }
3054
3055 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003056 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003057 DynamicLoader *dyld = GetDynamicLoader ();
3058 if (dyld)
3059 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003060
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003061 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003062
Jason Molendaeef51062013-11-05 03:57:19 +00003063 SystemRuntime *system_runtime = GetSystemRuntime ();
3064 if (system_runtime)
3065 system_runtime->DidAttach();
3066
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003067 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003068 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003069 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003070 Mutex::Locker modules_locker(target_modules.GetMutex());
3071 size_t num_modules = target_modules.GetSize();
3072 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003073
Andy Gibbsa297a972013-06-19 19:04:53 +00003074 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003075 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003076 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003077 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003078 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003079 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003080 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003081 break;
3082 }
3083 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003084 if (new_executable_module_sp)
3085 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003086}
3087
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003089Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003090{
Greg Claytonb766a732011-02-04 01:58:07 +00003091 m_abi_sp.reset();
3092 m_process_input_reader.reset();
3093
3094 // Find the process and its architecture. Make sure it matches the architecture
3095 // of the current Target, and if not adjust it.
3096
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003097 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003098 if (error.Success())
3099 {
Greg Clayton71337622011-02-24 22:24:29 +00003100 if (GetID() != LLDB_INVALID_PROCESS_ID)
3101 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003102 EventSP event_sp;
3103 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3104
3105 if (state == eStateStopped || state == eStateCrashed)
3106 {
3107 // If we attached and actually have a process on the other end, then
3108 // this ended up being the equivalent of an attach.
3109 CompleteAttach ();
3110
3111 // This delays passing the stopped event to listeners till
3112 // CompleteAttach gets a chance to complete...
3113 HandlePrivateEvent (event_sp);
3114
3115 }
Greg Clayton71337622011-02-24 22:24:29 +00003116 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003117
3118 if (PrivateStateThreadIsValid ())
3119 ResumePrivateStateThread ();
3120 else
3121 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003122 }
3123 return error;
3124}
3125
3126
3127Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003128Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129{
Greg Clayton5160ce52013-03-27 23:08:40 +00003130 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003132 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003133 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003134 StateAsCString(m_public_state.GetValue()),
3135 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136
3137 Error error (WillResume());
3138 // Tell the process it is about to resume before the thread list
3139 if (error.Success())
3140 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003141 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142 // can let all of our threads know that they are about to be
3143 // resumed. Threads will each be called with
3144 // Thread::WillResume(StateType) where StateType contains the state
3145 // that they are supposed to have when the process is resumed
3146 // (suspended/running/stepping). Threads should also check
3147 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003148 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003149 if (m_thread_list.WillResume())
3150 {
Jim Ingham372787f2012-04-07 00:00:41 +00003151 // Last thing, do the PreResumeActions.
3152 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153 {
Jim Ingham0161b492013-02-09 01:29:05 +00003154 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003155 }
3156 else
3157 {
3158 m_mod_id.BumpResumeID();
3159 error = DoResume();
3160 if (error.Success())
3161 {
3162 DidResume();
3163 m_thread_list.DidResume();
3164 if (log)
3165 log->Printf ("Process thinks the process has resumed.");
3166 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003167 }
3168 }
3169 else
3170 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003171 // Somebody wanted to run without running. So generate a continue & a stopped event,
3172 // and let the world handle them.
3173 if (log)
3174 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3175
3176 SetPrivateState(eStateRunning);
3177 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178 }
3179 }
Jim Ingham444586b2011-01-24 06:34:17 +00003180 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003181 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003182 return error;
3183}
3184
3185Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003186Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003188 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3189 // in case it was already set and some thread plan logic calls halt on its
3190 // own.
3191 m_clear_thread_plans_on_stop |= clear_thread_plans;
3192
Jim Inghamaacc3182012-06-06 00:29:30 +00003193 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3194 // we could just straightaway get another event. It just narrows the window...
3195 m_currently_handling_event.WaitForValueEqualTo(false);
3196
3197
Jim Inghambb3a2832011-01-29 01:49:25 +00003198 // Pause our private state thread so we can ensure no one else eats
3199 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003200 Listener halt_listener ("lldb.process.halt_listener");
3201 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003202
Jim Inghambb3a2832011-01-29 01:49:25 +00003203 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003204 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003205
Greg Clayton513c26c2011-01-29 07:10:55 +00003206 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003207 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003208
Greg Clayton513c26c2011-01-29 07:10:55 +00003209 bool caused_stop = false;
3210
3211 // Ask the process subclass to actually halt our process
3212 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003213 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003214 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003215 if (m_public_state.GetValue() == eStateAttaching)
3216 {
3217 SetExitStatus(SIGKILL, "Cancelled async attach.");
3218 Destroy ();
3219 }
3220 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003221 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003222 // If "caused_stop" is true, then DoHalt stopped the process. If
3223 // "caused_stop" is false, the process was already stopped.
3224 // If the DoHalt caused the process to stop, then we want to catch
3225 // this event and set the interrupted bool to true before we pass
3226 // this along so clients know that the process was interrupted by
3227 // a halt command.
3228 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003229 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003230 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003231 TimeValue timeout_time;
3232 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003233 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003234 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3235 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003236
Jim Ingham0f16e732011-02-08 05:20:59 +00003237 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003238 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003239 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003240 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003241 }
3242 else
3243 {
Greg Clayton2637f822011-11-17 01:23:07 +00003244 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003245 {
3246 // We caused the process to interrupt itself, so mark this
3247 // as such in the stop event so clients can tell an interrupted
3248 // process from a natural stop
3249 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3250 }
3251 else
3252 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003253 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003254 if (log)
3255 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3256 error.SetErrorString ("Did not get stopped event after halt.");
3257 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003258 }
3259 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003260 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003261 }
3262 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003264 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003265 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003266
3267 // Post any event we might have consumed. If all goes well, we will have
3268 // stopped the process, intercepted the event and set the interrupted
3269 // bool in the event. Post it to the private event queue and that will end up
3270 // correctly setting the state.
3271 if (event_sp)
3272 m_private_state_broadcaster.BroadcastEvent(event_sp);
3273
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003274 return error;
3275}
3276
3277Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003278Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3279{
3280 Error error;
3281 if (m_public_state.GetValue() == eStateRunning)
3282 {
3283 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3284 if (log)
3285 log->Printf("Process::Destroy() About to halt.");
3286 error = Halt();
3287 if (error.Success())
3288 {
3289 // Consume the halt event.
3290 TimeValue timeout (TimeValue::Now());
3291 timeout.OffsetWithSeconds(1);
3292 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3293
3294 // If the process exited while we were waiting for it to stop, put the exited event into
3295 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3296 // they don't have a process anymore...
3297
3298 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3299 {
3300 if (log)
3301 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3302 return error;
3303 }
3304 else
3305 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3306
3307 if (state != eStateStopped)
3308 {
3309 if (log)
3310 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3311 // If we really couldn't stop the process then we should just error out here, but if the
3312 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3313 StateType private_state = m_private_state.GetValue();
3314 if (private_state != eStateStopped)
3315 {
3316 return error;
3317 }
3318 }
3319 }
3320 else
3321 {
3322 if (log)
3323 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3324 }
3325 }
3326 return error;
3327}
3328
3329Error
Jim Inghamacff8952013-05-02 00:27:30 +00003330Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003332 EventSP exit_event_sp;
3333 Error error;
3334 m_destroy_in_process = true;
3335
3336 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003337
3338 if (error.Success())
3339 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003340 if (DetachRequiresHalt())
3341 {
3342 error = HaltForDestroyOrDetach (exit_event_sp);
3343 if (!error.Success())
3344 {
3345 m_destroy_in_process = false;
3346 return error;
3347 }
3348 else if (exit_event_sp)
3349 {
3350 // We shouldn't need to do anything else here. There's no process left to detach from...
3351 StopPrivateStateThread();
3352 m_destroy_in_process = false;
3353 return error;
3354 }
3355 }
3356
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003357 m_thread_list.DiscardThreadPlans();
3358 DisableAllBreakpointSites();
3359
Jim Inghamacff8952013-05-02 00:27:30 +00003360 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361 if (error.Success())
3362 {
3363 DidDetach();
3364 StopPrivateStateThread();
3365 }
Jim Inghamacff8952013-05-02 00:27:30 +00003366 else
3367 {
3368 return error;
3369 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003371 m_destroy_in_process = false;
3372
3373 // If we exited when we were waiting for a process to stop, then
3374 // forward the event here so we don't lose the event
3375 if (exit_event_sp)
3376 {
3377 // Directly broadcast our exited event because we shut down our
3378 // private state thread above
3379 BroadcastEvent(exit_event_sp);
3380 }
3381
3382 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3383 // the last events through the event system, in which case we might strand the write lock. Unlock
3384 // it here so when we do to tear down the process we don't get an error destroying the lock.
3385
Ed Maste64fad602013-07-29 20:58:06 +00003386 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003387 return error;
3388}
3389
3390Error
3391Process::Destroy ()
3392{
Jim Ingham09437922013-03-01 20:04:25 +00003393
3394 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3395 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3396 // failed and the process stays around for some reason it won't be in a confused state.
3397
3398 m_destroy_in_process = true;
3399
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400 Error error (WillDestroy());
3401 if (error.Success())
3402 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003403 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003404 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003405 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003406 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003407 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003408
Jim Inghamaacc3182012-06-06 00:29:30 +00003409 if (m_public_state.GetValue() != eStateRunning)
3410 {
3411 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3412 // kill it, we don't want it hitting a breakpoint...
3413 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3414 // we're not going to have much luck doing this now.
3415 m_thread_list.DiscardThreadPlans();
3416 DisableAllBreakpointSites();
3417 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003418
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419 error = DoDestroy();
3420 if (error.Success())
3421 {
3422 DidDestroy();
3423 StopPrivateStateThread();
3424 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003425 m_stdio_communication.StopReadThread();
3426 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003427
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003428 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003429 {
3430 m_process_input_reader->SetIsDone(true);
3431 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003432 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003433 }
3434
Greg Clayton85fb1b92012-09-11 02:33:37 +00003435 // If we exited when we were waiting for a process to stop, then
3436 // forward the event here so we don't lose the event
3437 if (exit_event_sp)
3438 {
3439 // Directly broadcast our exited event because we shut down our
3440 // private state thread above
3441 BroadcastEvent(exit_event_sp);
3442 }
3443
Jim Inghamb1e2e842012-04-12 18:49:31 +00003444 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3445 // the last events through the event system, in which case we might strand the write lock. Unlock
3446 // 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 +00003447 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003448 }
Jim Ingham09437922013-03-01 20:04:25 +00003449
3450 m_destroy_in_process = false;
3451
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452 return error;
3453}
3454
3455Error
3456Process::Signal (int signal)
3457{
3458 Error error (WillSignal());
3459 if (error.Success())
3460 {
3461 error = DoSignal(signal);
3462 if (error.Success())
3463 DidSignal();
3464 }
3465 return error;
3466}
3467
Greg Clayton514487e2011-02-15 21:59:32 +00003468lldb::ByteOrder
3469Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003470{
Greg Clayton514487e2011-02-15 21:59:32 +00003471 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003472}
3473
3474uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003475Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003476{
Greg Clayton514487e2011-02-15 21:59:32 +00003477 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003478}
3479
Greg Clayton514487e2011-02-15 21:59:32 +00003480
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003481bool
3482Process::ShouldBroadcastEvent (Event *event_ptr)
3483{
3484 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3485 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003486 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003487
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488 switch (state)
3489 {
Greg Claytonb766a732011-02-04 01:58:07 +00003490 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003491 case eStateAttaching:
3492 case eStateLaunching:
3493 case eStateDetached:
3494 case eStateExited:
3495 case eStateUnloaded:
3496 // These events indicate changes in the state of the debugging session, always report them.
3497 return_value = true;
3498 break;
3499 case eStateInvalid:
3500 // We stopped for no apparent reason, don't report it.
3501 return_value = false;
3502 break;
3503 case eStateRunning:
3504 case eStateStepping:
3505 // If we've started the target running, we handle the cases where we
3506 // are already running and where there is a transition from stopped to
3507 // running differently.
3508 // running -> running: Automatically suppress extra running events
3509 // stopped -> running: Report except when there is one or more no votes
3510 // and no yes votes.
3511 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003512 if (m_force_next_event_delivery)
3513 return_value = true;
3514 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003515 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003516 switch (m_last_broadcast_state)
3517 {
3518 case eStateRunning:
3519 case eStateStepping:
3520 // We always suppress multiple runnings with no PUBLIC stop in between.
3521 return_value = false;
3522 break;
3523 default:
3524 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003525 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003526 // events. If I run the lldb/test/thread/a.out file and
3527 // break at main.cpp:58, run and hit the breakpoints on
3528 // multiple threads, then somehow during the stepping over
3529 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003530
Jim Ingham1460e4b2014-01-10 23:46:59 +00003531 // This is a transition from stop to run.
3532 switch (m_thread_list.ShouldReportRun (event_ptr))
3533 {
3534 case eVoteYes:
3535 case eVoteNoOpinion:
3536 return_value = true;
3537 break;
3538 case eVoteNo:
3539 return_value = false;
3540 break;
3541 }
3542 break;
3543 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544 }
3545 break;
3546 case eStateStopped:
3547 case eStateCrashed:
3548 case eStateSuspended:
3549 {
3550 // We've stopped. First see if we're going to restart the target.
3551 // If we are going to stop, then we always broadcast the event.
3552 // 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 +00003553 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003554
Jim Inghamcb4ca112012-05-16 01:32:14 +00003555 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003556 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003557 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003558 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003559 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003560 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003561 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003562 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3563 // so they can properly set their state.
3564 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003565 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003566 }
3567 else
3568 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003569 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3570 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003571
Jim Ingham0161b492013-02-09 01:29:05 +00003572 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3573 // Asking the thread list is also not likely to go well, since we are running again.
3574 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003575
Jim Ingham0161b492013-02-09 01:29:05 +00003576 if (!was_restarted)
3577 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003578
Jim Ingham221d51c2013-05-08 00:35:16 +00003579 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580 {
Jim Ingham0161b492013-02-09 01:29:05 +00003581 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3582 if (log)
3583 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003584 should_resume, StateAsCString(state),
3585 was_restarted, stop_vote);
3586
Jim Ingham0161b492013-02-09 01:29:05 +00003587 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588 {
3589 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003590 return_value = true;
3591 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003592 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003593 case eVoteNo:
3594 return_value = false;
3595 break;
3596 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003597
Jim Inghamcb95f342012-09-05 21:13:56 +00003598 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003599 {
3600 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003601 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3602 static_cast<void*>(event_ptr),
3603 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003604 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003605 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003606 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003607
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608 }
3609 else
3610 {
3611 return_value = true;
3612 SynchronouslyNotifyStateChanged (state);
3613 }
3614 }
3615 }
Jim Ingham0161b492013-02-09 01:29:05 +00003616 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003618
Jim Ingham1460e4b2014-01-10 23:46:59 +00003619 // Forcing the next event delivery is a one shot deal. So reset it here.
3620 m_force_next_event_delivery = false;
3621
Jim Ingham0161b492013-02-09 01:29:05 +00003622 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3623 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3624 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3625 // because the PublicState reflects the last event pulled off the queue, and there may be several
3626 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3627 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003628
Jim Ingham0161b492013-02-09 01:29:05 +00003629 if (return_value)
3630 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003631
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003633 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003634 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003635 StateAsCString(m_last_broadcast_state),
3636 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 return return_value;
3638}
3639
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003640
3641bool
Jim Ingham372787f2012-04-07 00:00:41 +00003642Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003643{
Greg Clayton5160ce52013-03-27 23:08:40 +00003644 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645
Greg Clayton8b82f082011-04-12 05:54:46 +00003646 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003648 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3649
Jim Ingham372787f2012-04-07 00:00:41 +00003650 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003651 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003652
3653 // Create a thread that watches our internal state and controls which
3654 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003655 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003656 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003657 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003658 else
Daniel Malead01b2952012-11-29 21:49:15 +00003659 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003660
3661 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003662 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003663 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3664 if (success)
3665 {
3666 ResumePrivateStateThread();
3667 return true;
3668 }
3669 else
3670 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003671}
3672
3673void
3674Process::PausePrivateStateThread ()
3675{
3676 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3677}
3678
3679void
3680Process::ResumePrivateStateThread ()
3681{
3682 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3683}
3684
3685void
3686Process::StopPrivateStateThread ()
3687{
Greg Clayton8b82f082011-04-12 05:54:46 +00003688 if (PrivateStateThreadIsValid ())
3689 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003690 else
3691 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003692 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003693 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003694 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003695 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003696}
3697
3698void
3699Process::ControlPrivateStateThread (uint32_t signal)
3700{
Greg Clayton5160ce52013-03-27 23:08:40 +00003701 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003702
3703 assert (signal == eBroadcastInternalStateControlStop ||
3704 signal == eBroadcastInternalStateControlPause ||
3705 signal == eBroadcastInternalStateControlResume);
3706
3707 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003708 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003710 // Signal the private state thread. First we should copy this is case the
3711 // thread starts exiting since the private state thread will NULL this out
3712 // when it exits
3713 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003714 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003715 {
3716 TimeValue timeout_time;
3717 bool timed_out;
3718
3719 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3720
3721 timeout_time = TimeValue::Now();
3722 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003723 if (log)
3724 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3726 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3727
3728 if (signal == eBroadcastInternalStateControlStop)
3729 {
3730 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003731 {
3732 Error error;
3733 Host::ThreadCancel (private_state_thread, &error);
3734 if (log)
3735 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3736 }
3737 else
3738 {
3739 if (log)
3740 log->Printf ("The control event killed the private state thread without having to cancel.");
3741 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742
3743 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003744 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003745 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003746 }
3747 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003748 else
3749 {
3750 if (log)
3751 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3752 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003753}
3754
3755void
Jim Inghamcfc09352012-07-27 23:57:19 +00003756Process::SendAsyncInterrupt ()
3757{
3758 if (PrivateStateThreadIsValid())
3759 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3760 else
3761 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3762}
3763
3764void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765Process::HandlePrivateEvent (EventSP &event_sp)
3766{
Greg Clayton5160ce52013-03-27 23:08:40 +00003767 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003768 m_resume_requested = false;
3769
Jim Inghamaacc3182012-06-06 00:29:30 +00003770 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003771
Greg Clayton414f5d32011-01-25 02:58:48 +00003772 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003773
3774 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003775 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003776 {
Jim Ingham754ab982011-01-29 04:05:41 +00003777 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003778 if (log)
3779 log->Printf ("Ran next event action, result was %d.", action_result);
3780
Jim Inghambb3a2832011-01-29 01:49:25 +00003781 switch (action_result)
3782 {
3783 case NextEventAction::eEventActionSuccess:
3784 SetNextEventAction(NULL);
3785 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003786
Jim Inghambb3a2832011-01-29 01:49:25 +00003787 case NextEventAction::eEventActionRetry:
3788 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003789
Jim Inghambb3a2832011-01-29 01:49:25 +00003790 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003791 // Handle Exiting Here. If we already got an exited event,
3792 // we should just propagate it. Otherwise, swallow this event,
3793 // and set our state to exit so the next event will kill us.
3794 if (new_state != eStateExited)
3795 {
3796 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003797 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003798 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003799 SetNextEventAction(NULL);
3800 return;
3801 }
3802 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003803 break;
3804 }
3805 }
3806
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003807 // See if we should broadcast this state to external clients?
3808 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003809
3810 if (should_broadcast)
3811 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003812 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003813 if (log)
3814 {
Daniel Malead01b2952012-11-29 21:49:15 +00003815 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003816 __FUNCTION__,
3817 GetID(),
3818 StateAsCString(new_state),
3819 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003820 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821 }
Jim Ingham9575d842011-03-11 03:53:59 +00003822 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003823 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003824 {
3825 // Only push the input handler if we aren't fowarding events,
3826 // as this means the curses GUI is in use...
3827 if (!GetTarget().GetDebugger().IsForwardingEvents())
3828 PushProcessIOHandler ();
3829 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003830 else if (StateIsStoppedState(new_state, false))
3831 {
3832 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3833 {
3834 // If the lldb_private::Debugger is handling the events, we don't
3835 // want to pop the process IOHandler here, we want to do it when
3836 // we receive the stopped event so we can carefully control when
3837 // the process IOHandler is popped because when we stop we want to
3838 // display some text stating how and why we stopped, then maybe some
3839 // process/thread/frame info, and then we want the "(lldb) " prompt
3840 // to show up. If we pop the process IOHandler here, then we will
3841 // cause the command interpreter to become the top IOHandler after
3842 // the process pops off and it will update its prompt right away...
3843 // See the Debugger.cpp file where it calls the function as
3844 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3845 // Otherwise we end up getting overlapping "(lldb) " prompts and
3846 // garbled output.
3847 //
3848 // If we aren't handling the events in the debugger (which is indicated
3849 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3850 // are hijacked, then we always pop the process IO handler manually.
3851 // Hijacking happens when the internal process state thread is running
3852 // thread plans, or when commands want to run in synchronous mode
3853 // and they call "process->WaitForProcessToStop()". An example of something
3854 // that will hijack the events is a simple expression:
3855 //
3856 // (lldb) expr (int)puts("hello")
3857 //
3858 // This will cause the internal process state thread to resume and halt
3859 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3860 // events) and we do need the IO handler to be pushed and popped
3861 // correctly.
3862
3863 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
3864 PopProcessIOHandler ();
3865 }
3866 }
Jim Ingham9575d842011-03-11 03:53:59 +00003867
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868 BroadcastEvent (event_sp);
3869 }
3870 else
3871 {
3872 if (log)
3873 {
Daniel Malead01b2952012-11-29 21:49:15 +00003874 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003875 __FUNCTION__,
3876 GetID(),
3877 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003878 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879 }
3880 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003881 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003882}
3883
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003884thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003885Process::PrivateStateThread (void *arg)
3886{
3887 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003888 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003889 return result;
3890}
3891
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003892thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003893Process::RunPrivateStateThread ()
3894{
Jim Ingham076b3042012-04-10 01:21:57 +00003895 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003896 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003897
Greg Clayton5160ce52013-03-27 23:08:40 +00003898 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003899 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003900 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3901 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003902
3903 bool exit_now = false;
3904 while (!exit_now)
3905 {
3906 EventSP event_sp;
3907 WaitForEventsPrivate (NULL, event_sp, control_only);
3908 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3909 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003910 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003911 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
3912 __FUNCTION__, static_cast<void*>(this), GetID(),
3913 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00003914
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003915 switch (event_sp->GetType())
3916 {
3917 case eBroadcastInternalStateControlStop:
3918 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003919 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003920
3921 case eBroadcastInternalStateControlPause:
3922 control_only = true;
3923 break;
3924
3925 case eBroadcastInternalStateControlResume:
3926 control_only = false;
3927 break;
3928 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003929
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003931 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003932 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003933 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3934 {
3935 if (m_public_state.GetValue() == eStateAttaching)
3936 {
3937 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003938 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
3939 __FUNCTION__, static_cast<void*>(this),
3940 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00003941 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3942 }
3943 else
3944 {
3945 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003946 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
3947 __FUNCTION__, static_cast<void*>(this),
3948 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00003949 Halt();
3950 }
3951 continue;
3952 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003953
3954 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3955
3956 if (internal_state != eStateInvalid)
3957 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00003958 if (m_clear_thread_plans_on_stop &&
3959 StateIsStoppedState(internal_state, true))
3960 {
3961 m_clear_thread_plans_on_stop = false;
3962 m_thread_list.DiscardThreadPlans();
3963 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964 HandlePrivateEvent (event_sp);
3965 }
3966
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003967 if (internal_state == eStateInvalid ||
3968 internal_state == eStateExited ||
3969 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003970 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003971 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003972 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
3973 __FUNCTION__, static_cast<void*>(this), GetID(),
3974 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003975
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003976 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003977 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978 }
3979
Caroline Tice20ad3c42010-10-29 21:48:37 +00003980 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003982 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3983 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003984
Ed Maste64fad602013-07-29 20:58:06 +00003985 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00003986 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3987 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988 return NULL;
3989}
3990
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991//------------------------------------------------------------------
3992// Process Event Data
3993//------------------------------------------------------------------
3994
3995Process::ProcessEventData::ProcessEventData () :
3996 EventData (),
3997 m_process_sp (),
3998 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003999 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004000 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004001 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004002{
4003}
4004
4005Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4006 EventData (),
4007 m_process_sp (process_sp),
4008 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004009 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004010 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004011 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004012{
4013}
4014
4015Process::ProcessEventData::~ProcessEventData()
4016{
4017}
4018
4019const ConstString &
4020Process::ProcessEventData::GetFlavorString ()
4021{
4022 static ConstString g_flavor ("Process::ProcessEventData");
4023 return g_flavor;
4024}
4025
4026const ConstString &
4027Process::ProcessEventData::GetFlavor () const
4028{
4029 return ProcessEventData::GetFlavorString ();
4030}
4031
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004032void
4033Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4034{
4035 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004036 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4037 // the public event queue, then other times when we're pretending that this is where we stopped at the
4038 // end of expression evaluation. m_update_state is used to distinguish these
4039 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004040 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004041 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004043
Jim Ingham221d51c2013-05-08 00:35:16 +00004044 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004045
4046 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4047 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4048 // end up restarting the process.
4049 if (m_interrupted)
4050 return;
4051
4052 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004054 {
4055 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004056 uint32_t num_threads = curr_thread_list.GetSize();
4057 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004058
Jim Ingham4b536182011-08-09 02:12:22 +00004059 // The actions might change one of the thread's stop_info's opinions about whether we should
4060 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004061
4062 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4063 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4064 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4065 // 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
4066 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004067 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004068 for (idx = 0; idx < num_threads; ++idx)
4069 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4070
Jim Inghamc7078c22012-12-13 22:24:15 +00004071 // Use this to track whether we should continue from here. We will only continue the target running if
4072 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4073 // then it doesn't matter what the other threads say...
4074
4075 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004076
Jim Ingham0ad7e052013-04-25 02:04:59 +00004077 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4078 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4079 // thing to do is, and it's better to let the user decide than continue behind their backs.
4080
4081 bool does_anybody_have_an_opinion = false;
4082
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004083 for (idx = 0; idx < num_threads; ++idx)
4084 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004085 curr_thread_list = m_process_sp->GetThreadList();
4086 if (curr_thread_list.GetSize() != num_threads)
4087 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004088 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004089 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004090 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 +00004091 break;
4092 }
4093
4094 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4095
4096 if (thread_sp->GetIndexID() != thread_index_array[idx])
4097 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004098 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004099 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004100 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004101 idx,
4102 thread_index_array[idx],
4103 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004104 break;
4105 }
4106
Jim Inghamb15bfc72010-10-20 00:39:53 +00004107 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004108 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004109 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004110 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004111 bool this_thread_wants_to_stop;
4112 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004113 {
Jim Ingham0161b492013-02-09 01:29:05 +00004114 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4115 }
4116 else
4117 {
4118 stop_info_sp->PerformAction(event_ptr);
4119 // The stop action might restart the target. If it does, then we want to mark that in the
4120 // event so that whoever is receiving it will know to wait for the running event and reflect
4121 // that state appropriately.
4122 // We also need to stop processing actions, since they aren't expecting the target to be running.
4123
4124 // FIXME: we might have run.
4125 if (stop_info_sp->HasTargetRunSinceMe())
4126 {
4127 SetRestarted (true);
4128 break;
4129 }
4130
4131 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004132 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004133
Jim Inghamc7078c22012-12-13 22:24:15 +00004134 if (still_should_stop == false)
4135 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004136 }
4137 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004138
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004139
Jim Inghama8ca6e22013-05-03 23:04:37 +00004140 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004141 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004142 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004143 {
4144 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004145 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004146 // Use the public resume method here, since this is just
4147 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004148 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004149 }
4150 else
4151 {
4152 // If we didn't restart, run the Stop Hooks here:
4153 // They might also restart the target, so watch for that.
4154 m_process_sp->GetTarget().RunStopHooks();
4155 if (m_process_sp->GetPrivateState() == eStateRunning)
4156 SetRestarted(true);
4157 }
Jim Ingham9575d842011-03-11 03:53:59 +00004158 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004159 }
4160}
4161
4162void
4163Process::ProcessEventData::Dump (Stream *s) const
4164{
4165 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004166 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4167 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004168
Greg Clayton8b82f082011-04-12 05:54:46 +00004169 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004170}
4171
4172const Process::ProcessEventData *
4173Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4174{
4175 if (event_ptr)
4176 {
4177 const EventData *event_data = event_ptr->GetData();
4178 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4179 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4180 }
4181 return NULL;
4182}
4183
4184ProcessSP
4185Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4186{
4187 ProcessSP process_sp;
4188 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4189 if (data)
4190 process_sp = data->GetProcessSP();
4191 return process_sp;
4192}
4193
4194StateType
4195Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4196{
4197 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4198 if (data == NULL)
4199 return eStateInvalid;
4200 else
4201 return data->GetState();
4202}
4203
4204bool
4205Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4206{
4207 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4208 if (data == NULL)
4209 return false;
4210 else
4211 return data->GetRestarted();
4212}
4213
4214void
4215Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4216{
4217 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4218 if (data != NULL)
4219 data->SetRestarted(new_value);
4220}
4221
Jim Ingham0161b492013-02-09 01:29:05 +00004222size_t
4223Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4224{
4225 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4226 if (data != NULL)
4227 return data->GetNumRestartedReasons();
4228 else
4229 return 0;
4230}
4231
4232const char *
4233Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4234{
4235 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4236 if (data != NULL)
4237 return data->GetRestartedReasonAtIndex(idx);
4238 else
4239 return NULL;
4240}
4241
4242void
4243Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4244{
4245 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4246 if (data != NULL)
4247 data->AddRestartedReason(reason);
4248}
4249
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004250bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004251Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4252{
4253 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4254 if (data == NULL)
4255 return false;
4256 else
4257 return data->GetInterrupted ();
4258}
4259
4260void
4261Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4262{
4263 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4264 if (data != NULL)
4265 data->SetInterrupted(new_value);
4266}
4267
4268bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004269Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4270{
4271 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4272 if (data)
4273 {
4274 data->SetUpdateStateOnRemoval();
4275 return true;
4276 }
4277 return false;
4278}
4279
Greg Claytond9e416c2012-02-18 05:35:26 +00004280lldb::TargetSP
4281Process::CalculateTarget ()
4282{
4283 return m_target.shared_from_this();
4284}
4285
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004286void
Greg Clayton0603aa92010-10-04 01:05:56 +00004287Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004288{
Greg Claytonc14ee322011-09-22 04:58:26 +00004289 exe_ctx.SetTargetPtr (&m_target);
4290 exe_ctx.SetProcessPtr (this);
4291 exe_ctx.SetThreadPtr(NULL);
4292 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004293}
4294
Greg Claytone996fd32011-03-08 22:40:15 +00004295//uint32_t
4296//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4297//{
4298// return 0;
4299//}
4300//
4301//ArchSpec
4302//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4303//{
4304// return Host::GetArchSpecForExistingProcess (pid);
4305//}
4306//
4307//ArchSpec
4308//Process::GetArchSpecForExistingProcess (const char *process_name)
4309//{
4310// return Host::GetArchSpecForExistingProcess (process_name);
4311//}
4312//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004313void
4314Process::AppendSTDOUT (const char * s, size_t len)
4315{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004316 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004317 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004318 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004319}
4320
4321void
Greg Clayton93e86192011-11-13 04:45:22 +00004322Process::AppendSTDERR (const char * s, size_t len)
4323{
4324 Mutex::Locker locker (m_stdio_communication_mutex);
4325 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004326 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004327}
4328
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004329void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004330Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004331{
4332 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004333 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004334 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4335}
4336
4337size_t
4338Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4339{
4340 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004341 if (m_profile_data.empty())
4342 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004343
4344 std::string &one_profile_data = m_profile_data.front();
4345 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004346 if (bytes_available > 0)
4347 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004348 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004349 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004350 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4351 static_cast<void*>(buf),
4352 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004353 if (bytes_available > buf_size)
4354 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004355 memcpy(buf, one_profile_data.c_str(), buf_size);
4356 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004357 bytes_available = buf_size;
4358 }
4359 else
4360 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004361 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004362 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004363 }
4364 }
4365 return bytes_available;
4366}
4367
4368
Greg Clayton93e86192011-11-13 04:45:22 +00004369//------------------------------------------------------------------
4370// Process STDIO
4371//------------------------------------------------------------------
4372
4373size_t
4374Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4375{
4376 Mutex::Locker locker(m_stdio_communication_mutex);
4377 size_t bytes_available = m_stdout_data.size();
4378 if (bytes_available > 0)
4379 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004380 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004381 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004382 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4383 static_cast<void*>(buf),
4384 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004385 if (bytes_available > buf_size)
4386 {
4387 memcpy(buf, m_stdout_data.c_str(), buf_size);
4388 m_stdout_data.erase(0, buf_size);
4389 bytes_available = buf_size;
4390 }
4391 else
4392 {
4393 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4394 m_stdout_data.clear();
4395 }
4396 }
4397 return bytes_available;
4398}
4399
4400
4401size_t
4402Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4403{
4404 Mutex::Locker locker(m_stdio_communication_mutex);
4405 size_t bytes_available = m_stderr_data.size();
4406 if (bytes_available > 0)
4407 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004408 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004409 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004410 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4411 static_cast<void*>(buf),
4412 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004413 if (bytes_available > buf_size)
4414 {
4415 memcpy(buf, m_stderr_data.c_str(), buf_size);
4416 m_stderr_data.erase(0, buf_size);
4417 bytes_available = buf_size;
4418 }
4419 else
4420 {
4421 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4422 m_stderr_data.clear();
4423 }
4424 }
4425 return bytes_available;
4426}
4427
4428void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004429Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4430{
4431 Process *process = (Process *) baton;
4432 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4433}
4434
Greg Clayton44d93782014-01-27 23:43:24 +00004435class IOHandlerProcessSTDIO :
4436 public IOHandler
4437{
4438public:
4439 IOHandlerProcessSTDIO (Process *process,
4440 int write_fd) :
4441 IOHandler(process->GetTarget().GetDebugger()),
4442 m_process (process),
4443 m_read_file (),
4444 m_write_file (write_fd, false),
4445 m_pipe_read(),
4446 m_pipe_write()
4447 {
4448 m_read_file.SetDescriptor(GetInputFD(), false);
4449 }
4450
4451 virtual
4452 ~IOHandlerProcessSTDIO ()
4453 {
4454
4455 }
4456
4457 bool
4458 OpenPipes ()
4459 {
4460 if (m_pipe_read.IsValid() && m_pipe_write.IsValid())
4461 return true;
4462
4463 int fds[2];
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004464#ifdef _WIN32
Deepak Panickal914b8d92014-01-31 18:48:46 +00004465 // pipe is not supported on windows so default to a fail condition
4466 int err = 1;
4467#else
Greg Clayton44d93782014-01-27 23:43:24 +00004468 int err = pipe(fds);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004469#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004470 if (err == 0)
4471 {
4472 m_pipe_read.SetDescriptor(fds[0], true);
4473 m_pipe_write.SetDescriptor(fds[1], true);
4474 return true;
4475 }
4476 return false;
4477 }
4478
4479 void
4480 ClosePipes()
4481 {
4482 m_pipe_read.Close();
4483 m_pipe_write.Close();
4484 }
4485
4486 // Each IOHandler gets to run until it is done. It should read data
4487 // from the "in" and place output into "out" and "err and return
4488 // when done.
4489 virtual void
4490 Run ()
4491 {
4492 if (m_read_file.IsValid() && m_write_file.IsValid())
4493 {
4494 SetIsDone(false);
4495 if (OpenPipes())
4496 {
4497 const int read_fd = m_read_file.GetDescriptor();
4498 const int pipe_read_fd = m_pipe_read.GetDescriptor();
4499 TerminalState terminal_state;
4500 terminal_state.Save (read_fd, false);
4501 Terminal terminal(read_fd);
4502 terminal.SetCanonical(false);
4503 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004504// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004505#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004506 while (!GetIsDone())
4507 {
4508 fd_set read_fdset;
4509 FD_ZERO (&read_fdset);
4510 FD_SET (read_fd, &read_fdset);
4511 FD_SET (pipe_read_fd, &read_fdset);
4512 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4513 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4514 if (num_set_fds < 0)
4515 {
4516 const int select_errno = errno;
4517
4518 if (select_errno != EINTR)
4519 SetIsDone(true);
4520 }
4521 else if (num_set_fds > 0)
4522 {
4523 char ch = 0;
4524 size_t n;
4525 if (FD_ISSET (read_fd, &read_fdset))
4526 {
4527 n = 1;
4528 if (m_read_file.Read(&ch, n).Success() && n == 1)
4529 {
4530 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4531 SetIsDone(true);
4532 }
4533 else
4534 SetIsDone(true);
4535 }
4536 if (FD_ISSET (pipe_read_fd, &read_fdset))
4537 {
4538 // Consume the interrupt byte
4539 n = 1;
4540 m_pipe_read.Read (&ch, n);
Greg Clayton19e11352014-02-26 22:47:33 +00004541 switch (ch)
4542 {
4543 case 'q':
4544 SetIsDone(true);
4545 break;
4546 case 'i':
4547 if (StateIsRunningState(m_process->GetState()))
4548 m_process->Halt();
4549 break;
4550 }
Greg Clayton44d93782014-01-27 23:43:24 +00004551 }
4552 }
4553 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004554#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004555 terminal_state.Restore();
4556
4557 }
4558 else
4559 SetIsDone(true);
4560 }
4561 else
4562 SetIsDone(true);
4563 }
4564
4565 // Hide any characters that have been displayed so far so async
4566 // output can be displayed. Refresh() will be called after the
4567 // output has been displayed.
4568 virtual void
4569 Hide ()
4570 {
4571
4572 }
4573 // Called when the async output has been received in order to update
4574 // the input reader (refresh the prompt and redisplay any current
4575 // line(s) that are being edited
4576 virtual void
4577 Refresh ()
4578 {
4579
4580 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004581
Greg Clayton44d93782014-01-27 23:43:24 +00004582 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004583 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004584 {
4585 size_t n = 1;
Greg Clayton19e11352014-02-26 22:47:33 +00004586 char ch = 'q'; // Send 'q' for quit
Greg Clayton44d93782014-01-27 23:43:24 +00004587 m_pipe_write.Write (&ch, n);
4588 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004589
Greg Claytonf0066ad2014-05-02 00:45:31 +00004590 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004591 Interrupt ()
4592 {
Greg Clayton19e11352014-02-26 22:47:33 +00004593#ifdef _MSC_VER
4594 // Windows doesn't support pipes, so we will send an async interrupt
4595 // event to stop the process
Greg Claytone68f5d62014-02-24 22:50:57 +00004596 if (StateIsRunningState(m_process->GetState()))
Ed Maste96e51b82014-02-25 14:20:14 +00004597 m_process->SendAsyncInterrupt();
Greg Clayton19e11352014-02-26 22:47:33 +00004598#else
4599 // Do only things that are safe to do in an interrupt context (like in
4600 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4601 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4602 // that was written to the pipe and then call m_process->Halt() from a
4603 // much safer location in code.
4604 size_t n = 1;
4605 char ch = 'i'; // Send 'i' for interrupt
4606 m_pipe_write.Write (&ch, n);
4607#endif
Greg Claytonf0066ad2014-05-02 00:45:31 +00004608 return true;
Greg Claytone68f5d62014-02-24 22:50:57 +00004609 }
Greg Clayton44d93782014-01-27 23:43:24 +00004610
4611 virtual void
4612 GotEOF()
4613 {
4614
4615 }
4616
4617protected:
4618 Process *m_process;
4619 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4620 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
4621 File m_pipe_read;
4622 File m_pipe_write;
4623
4624};
4625
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004626void
Greg Clayton44d93782014-01-27 23:43:24 +00004627Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004628{
4629 // First set up the Read Thread for reading/handling process I/O
4630
Greg Clayton44d93782014-01-27 23:43:24 +00004631 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004632
4633 if (conn_ap.get())
4634 {
4635 m_stdio_communication.SetConnection (conn_ap.release());
4636 if (m_stdio_communication.IsConnected())
4637 {
4638 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4639 m_stdio_communication.StartReadThread();
4640
4641 // Now read thread is set up, set up input reader.
4642
4643 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004644 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004645 }
4646 }
4647}
4648
Greg Claytonb4874f12014-02-28 18:22:24 +00004649bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004650Process::ProcessIOHandlerIsActive ()
4651{
4652 IOHandlerSP io_handler_sp (m_process_input_reader);
4653 if (io_handler_sp)
4654 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4655 return false;
4656}
4657bool
Greg Clayton44d93782014-01-27 23:43:24 +00004658Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004659{
Greg Clayton44d93782014-01-27 23:43:24 +00004660 IOHandlerSP io_handler_sp (m_process_input_reader);
4661 if (io_handler_sp)
4662 {
4663 io_handler_sp->SetIsDone(false);
4664 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004665 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004666 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004667 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004668}
4669
Greg Claytonb4874f12014-02-28 18:22:24 +00004670bool
Greg Clayton44d93782014-01-27 23:43:24 +00004671Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004672{
Greg Clayton44d93782014-01-27 23:43:24 +00004673 IOHandlerSP io_handler_sp (m_process_input_reader);
4674 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004675 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4676 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004677}
4678
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004679// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004680void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004681Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004682{
Greg Clayton6920b522012-08-22 18:39:03 +00004683 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004684}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004685
Greg Clayton99d0faf2010-11-18 23:32:35 +00004686void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004687Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004688{
Greg Clayton6920b522012-08-22 18:39:03 +00004689 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004690}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004691
Jim Ingham1624a2d2014-05-05 02:26:40 +00004692ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004693Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004694 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004695 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004696 Stream &errors)
4697{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004698 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004699
Jim Ingham77787032011-01-20 02:03:18 +00004700 if (thread_plan_sp.get() == NULL)
4701 {
4702 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004703 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004704 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004705
Jim Ingham7d7931d2013-03-28 00:05:34 +00004706 if (!thread_plan_sp->ValidatePlan(NULL))
4707 {
4708 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004709 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004710 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004711
Greg Claytonc14ee322011-09-22 04:58:26 +00004712 if (exe_ctx.GetProcessPtr() != this)
4713 {
4714 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004715 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004716 }
4717
4718 Thread *thread = exe_ctx.GetThreadPtr();
4719 if (thread == NULL)
4720 {
4721 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004722 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004723 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004724
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004725 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4726 // For that to be true the plan can't be private - since private plans suppress themselves in the
4727 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004728
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004729 bool orig_plan_private = thread_plan_sp->GetPrivate();
4730 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004731
Jim Ingham444586b2011-01-24 06:34:17 +00004732 if (m_private_state.GetValue() != eStateStopped)
4733 {
4734 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004735 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004736 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004737
Jim Ingham66243842011-08-13 00:56:10 +00004738 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004739 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004740 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004741 if (!selected_frame_sp)
4742 {
4743 thread->SetSelectedFrame(0);
4744 selected_frame_sp = thread->GetSelectedFrame();
4745 if (!selected_frame_sp)
4746 {
4747 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004748 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004749 }
4750 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004751
Jim Ingham11b0e052013-02-19 23:22:45 +00004752 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004753
4754 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4755 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004756
Greg Claytonc14ee322011-09-22 04:58:26 +00004757 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004758
Jim Ingham66243842011-08-13 00:56:10 +00004759 uint32_t selected_tid;
4760 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004761 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004762 {
4763 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004764 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004765 }
4766 else
4767 {
4768 selected_tid = LLDB_INVALID_THREAD_ID;
4769 }
4770
Jim Ingham372787f2012-04-07 00:00:41 +00004771 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004772 lldb::StateType old_state;
4773 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004774
Greg Clayton5160ce52013-03-27 23:08:40 +00004775 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004776 if (Host::GetCurrentThread() == m_private_state_thread)
4777 {
Jim Ingham076b3042012-04-10 01:21:57 +00004778 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4779 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004780 // 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 +00004781 // we are fielding public events here.
4782 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004783 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 +00004784
Jim Ingham372787f2012-04-07 00:00:41 +00004785 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004786
4787 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4788 // returning control here.
4789 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4790 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4791 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4792 // do just what we want.
4793 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4794 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4795 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4796 old_state = m_public_state.GetValue();
4797 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004798
Jim Ingham076b3042012-04-10 01:21:57 +00004799 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004800 StartPrivateStateThread(true);
4801 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004802
Jim Ingham372787f2012-04-07 00:00:41 +00004803 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004804
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004805 if (options.GetDebug())
4806 {
4807 // In this case, we aren't actually going to run, we just want to stop right away.
4808 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4809 // FIXME: To make this prettier we should invent some stop reason for this, but that
4810 // is only cosmetic, and this functionality is only of use to lldb developers who can
4811 // live with not pretty...
4812 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004813 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004814 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004815
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004816 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004817
Sean Callanana46ec452012-07-11 21:31:24 +00004818 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004819
Jim Ingham77787032011-01-20 02:03:18 +00004820 {
Sean Callanana46ec452012-07-11 21:31:24 +00004821 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4822 // restored on exit to the function.
4823 //
4824 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4825 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004826
Sean Callanana46ec452012-07-11 21:31:24 +00004827 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004828
Jim Inghamf48169b2010-11-30 02:22:11 +00004829 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004830 {
4831 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004832 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004833 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004834 thread->GetIndexID(),
4835 thread->GetID(),
4836 s.GetData());
4837 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004838
Sean Callanana46ec452012-07-11 21:31:24 +00004839 bool got_event;
4840 lldb::EventSP event_sp;
4841 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004842
Sean Callanana46ec452012-07-11 21:31:24 +00004843 TimeValue* timeout_ptr = NULL;
4844 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004845
Jim Ingham0161b492013-02-09 01:29:05 +00004846 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 +00004847 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004848 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004849 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004850
Jim Ingham0161b492013-02-09 01:29:05 +00004851 // This is just for accounting:
4852 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004853
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004854 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00004855 uint32_t one_thread_timeout_usec;
4856 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00004857
4858 // If we are going to run all threads the whole time, or if we are only going to run one thread,
4859 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
4860 // first timeout already.
4861
4862 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00004863 {
4864 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00004865 one_thread_timeout_usec = 0;
4866 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00004867 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004868 else
Jim Ingham0161b492013-02-09 01:29:05 +00004869 {
Jim Inghamfd95f892014-04-22 01:41:52 +00004870 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004871
Jim Ingham914f4e72014-03-28 21:58:28 +00004872 // If the overall wait is forever, then we only need to set the one thread timeout:
4873 if (timeout_usec == 0)
4874 {
Ed Maste801335c2014-03-31 19:28:14 +00004875 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00004876 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00004877 else
Jim Inghamfd95f892014-04-22 01:41:52 +00004878 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00004879 }
Jim Ingham0161b492013-02-09 01:29:05 +00004880 else
4881 {
Jim Ingham914f4e72014-03-28 21:58:28 +00004882 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
4883 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
4884 uint64_t computed_one_thread_timeout;
4885 if (option_one_thread_timeout != 0)
4886 {
4887 if (timeout_usec < option_one_thread_timeout)
4888 {
4889 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004890 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00004891 }
4892 computed_one_thread_timeout = option_one_thread_timeout;
4893 }
4894 else
4895 {
4896 computed_one_thread_timeout = timeout_usec / 2;
4897 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
4898 computed_one_thread_timeout = default_one_thread_timeout_usec;
4899 }
Jim Inghamfd95f892014-04-22 01:41:52 +00004900 one_thread_timeout_usec = computed_one_thread_timeout;
4901 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
4902
Jim Ingham0161b492013-02-09 01:29:05 +00004903 }
Jim Ingham0161b492013-02-09 01:29:05 +00004904 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004905
4906 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00004907 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 +00004908 options.GetStopOthers(),
4909 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00004910 before_first_timeout,
4911 one_thread_timeout_usec,
4912 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00004913
Jim Ingham1460e4b2014-01-10 23:46:59 +00004914 // This isn't going to work if there are unfetched events on the queue.
4915 // Are there cases where we might want to run the remaining events here, and then try to
4916 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004917
Jim Ingham1460e4b2014-01-10 23:46:59 +00004918 Event *other_events = listener.PeekAtNextEvent();
4919 if (other_events != NULL)
4920 {
4921 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004922 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00004923 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004924
Jim Ingham1460e4b2014-01-10 23:46:59 +00004925 // We also need to make sure that the next event is delivered. We might be calling a function as part of
4926 // a thread plan, in which case the last delivered event could be the running event, and we don't want
4927 // event coalescing to cause us to lose OUR running event...
4928 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004929
Jim Ingham8559a352012-11-26 23:52:18 +00004930 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4931 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00004932
4933#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4934 // It's pretty much impossible to write test cases for things like:
4935 // One thread timeout expires, I go to halt, but the process already stopped
4936 // on the function call stop breakpoint. Turning on this define will make us not
4937 // fetch the first event till after the halt. So if you run a quick function, it will have
4938 // completed, and the completion event will be waiting, when you interrupt for halt.
4939 // The expression evaluation should still succeed.
4940 bool miss_first_event = true;
4941#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00004942 TimeValue one_thread_timeout;
4943 TimeValue final_timeout;
4944
Jim Ingham35878c42014-04-08 21:33:21 +00004945
Sean Callanana46ec452012-07-11 21:31:24 +00004946 while (1)
4947 {
4948 // We usually want to resume the process if we get to the top of the loop.
4949 // The only exception is if we get two running events with no intervening
4950 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004951 if (log)
4952 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4953 do_resume,
4954 handle_running_event,
4955 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004956
Jim Ingham184e9812013-01-15 02:47:48 +00004957 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00004958 {
4959 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004960
Jim Ingham184e9812013-01-15 02:47:48 +00004961 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00004962 {
Jim Ingham0161b492013-02-09 01:29:05 +00004963 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00004964 Error resume_error = PrivateResume ();
4965 if (!resume_error.Success())
4966 {
Jim Ingham0161b492013-02-09 01:29:05 +00004967 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4968 num_resumes,
4969 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00004970 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00004971 break;
4972 }
Sean Callanana46ec452012-07-11 21:31:24 +00004973 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004974
Jim Ingham0161b492013-02-09 01:29:05 +00004975 TimeValue resume_timeout = TimeValue::Now();
4976 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004977
Jim Ingham0161b492013-02-09 01:29:05 +00004978 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00004979 if (!got_event)
4980 {
4981 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004982 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4983 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004984
Jim Ingham0161b492013-02-09 01:29:05 +00004985 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004986 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00004987 break;
4988 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004989
Sean Callanana46ec452012-07-11 21:31:24 +00004990 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00004991
Sean Callanana46ec452012-07-11 21:31:24 +00004992 if (stop_state != eStateRunning)
4993 {
Jim Ingham0161b492013-02-09 01:29:05 +00004994 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004995
Jim Ingham0161b492013-02-09 01:29:05 +00004996 if (stop_state == eStateStopped)
4997 {
4998 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4999 if (log)
5000 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5001 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5002 num_resumes,
5003 StateAsCString(stop_state),
5004 restarted,
5005 do_resume,
5006 handle_running_event);
5007 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005008
Jim Ingham0161b492013-02-09 01:29:05 +00005009 if (restarted)
5010 {
5011 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5012 // event here. But if I do, the best thing is to Halt and then get out of here.
5013 Halt();
5014 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005015
Jim Ingham35e1bda2012-10-16 21:41:58 +00005016 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5017 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005018 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005019 break;
5020 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005021
Sean Callanana46ec452012-07-11 21:31:24 +00005022 if (log)
5023 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5024 // We need to call the function synchronously, so spin waiting for it to return.
5025 // If we get interrupted while executing, we're going to lose our context, and
5026 // won't be able to gather the result at this point.
5027 // We set the timeout AFTER the resume, since the resume takes some time and we
5028 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005029 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005030 else
5031 {
Sean Callanana46ec452012-07-11 21:31:24 +00005032 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005033 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005034 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005035
Jim Ingham0161b492013-02-09 01:29:05 +00005036 if (before_first_timeout)
5037 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005038 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005039 {
5040 one_thread_timeout = TimeValue::Now();
5041 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005042 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005043 }
Jim Ingham0161b492013-02-09 01:29:05 +00005044 else
5045 {
5046 if (timeout_usec == 0)
5047 timeout_ptr = NULL;
5048 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005049 {
5050 final_timeout = TimeValue::Now();
5051 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005052 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005053 }
Jim Ingham0161b492013-02-09 01:29:05 +00005054 }
5055 }
5056 else
5057 {
5058 if (timeout_usec == 0)
5059 timeout_ptr = NULL;
5060 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005061 {
5062 final_timeout = TimeValue::Now();
5063 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005064 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005065 }
Jim Ingham0161b492013-02-09 01:29:05 +00005066 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005067
Jim Ingham0161b492013-02-09 01:29:05 +00005068 do_resume = true;
5069 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005070
Sean Callanana46ec452012-07-11 21:31:24 +00005071 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005072 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005073
Jim Ingham0f16e732011-02-08 05:20:59 +00005074 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005075 {
Sean Callanana46ec452012-07-11 21:31:24 +00005076 if (timeout_ptr)
5077 {
Matt Kopec676a4872013-02-21 23:55:31 +00005078 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005079 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5080 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005081 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005082 else
Sean Callanana46ec452012-07-11 21:31:24 +00005083 {
5084 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5085 }
5086 }
Jim Ingham35878c42014-04-08 21:33:21 +00005087
5088#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5089 // See comment above...
5090 if (miss_first_event)
5091 {
5092 usleep(1000);
5093 miss_first_event = false;
5094 got_event = false;
5095 }
5096 else
5097#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005098 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005099
Sean Callanana46ec452012-07-11 21:31:24 +00005100 if (got_event)
5101 {
5102 if (event_sp.get())
5103 {
5104 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005105 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005106 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005107 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005108 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005109 errors.Printf ("Execution halted by user interrupt.");
5110 if (log)
5111 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005112 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005113 }
5114 else
5115 {
5116 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5117 if (log)
5118 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005119
Jim Inghamcfc09352012-07-27 23:57:19 +00005120 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005121 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005122 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005123 {
Jim Ingham0161b492013-02-09 01:29:05 +00005124 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005125 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5126 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005127 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005128 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005129 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005130 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005131 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005132 }
5133 else
5134 {
Jim Ingham0161b492013-02-09 01:29:05 +00005135 // If we were restarted, we just need to go back up to fetch another event.
5136 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005137 {
5138 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005139 {
5140 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5141 }
5142 keep_going = true;
5143 do_resume = false;
5144 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005145
Jim Inghamcfc09352012-07-27 23:57:19 +00005146 }
5147 else
5148 {
Jim Ingham0161b492013-02-09 01:29:05 +00005149 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5150 StopReason stop_reason = eStopReasonInvalid;
5151 if (stop_info_sp)
5152 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005153
Jim Ingham0161b492013-02-09 01:29:05 +00005154 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5155 // it is OUR plan that is complete?
5156 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005157 {
5158 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005159 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5160 // Now mark this plan as private so it doesn't get reported as the stop reason
5161 // after this point.
5162 if (thread_plan_sp)
5163 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005164 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005165 }
5166 else
5167 {
Jim Ingham0161b492013-02-09 01:29:05 +00005168 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005169 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005170 {
5171 if (log)
5172 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005173 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005174 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005175 {
5176 event_to_broadcast_sp = event_sp;
5177 }
Jim Ingham0161b492013-02-09 01:29:05 +00005178 }
Jim Ingham184e9812013-01-15 02:47:48 +00005179 else
Jim Ingham0161b492013-02-09 01:29:05 +00005180 {
5181 if (log)
5182 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005183 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005184 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005185 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005186 }
Jim Ingham184e9812013-01-15 02:47:48 +00005187 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005188 }
Sean Callanana46ec452012-07-11 21:31:24 +00005189 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005190 }
5191 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005192
Jim Inghamcfc09352012-07-27 23:57:19 +00005193 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005194 // This shouldn't really happen, but sometimes we do get two running events without an
5195 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005196 do_resume = false;
5197 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005198 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005199 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005200
Jim Inghamcfc09352012-07-27 23:57:19 +00005201 default:
5202 if (log)
5203 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005204
Jim Inghamcfc09352012-07-27 23:57:19 +00005205 if (stop_state == eStateExited)
5206 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005207
Sean Callananbf154da2012-08-08 17:35:10 +00005208 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005209 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005210 break;
5211 }
Sean Callanana46ec452012-07-11 21:31:24 +00005212 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005213
Sean Callanana46ec452012-07-11 21:31:24 +00005214 if (keep_going)
5215 continue;
5216 else
5217 break;
5218 }
5219 else
5220 {
5221 if (log)
5222 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005223 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005224 break;
5225 }
5226 }
5227 else
5228 {
5229 // If we didn't get an event that means we've timed out...
5230 // We will interrupt the process here. Depending on what we were asked to do we will
5231 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005232
Sean Callanana46ec452012-07-11 21:31:24 +00005233 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005234 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005235 {
Jim Ingham0161b492013-02-09 01:29:05 +00005236 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005237 {
5238 if (timeout_usec != 0)
5239 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005240 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005241 "running for %" PRIu32 " usec with all threads enabled.",
5242 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005243 }
5244 else
5245 {
5246 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005247 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005248 }
5249 }
Sean Callanana46ec452012-07-11 21:31:24 +00005250 else
5251 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005252 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005253 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005254 }
5255 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005256 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005257 "abandoning execution.",
5258 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005259 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005260
Jim Ingham0161b492013-02-09 01:29:05 +00005261 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5262 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5263 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5264 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5265 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005266
Jim Ingham0161b492013-02-09 01:29:05 +00005267 bool back_to_top = true;
5268 uint32_t try_halt_again = 0;
5269 bool do_halt = true;
5270 const uint32_t num_retries = 5;
5271 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005272 {
Jim Ingham0161b492013-02-09 01:29:05 +00005273 Error halt_error;
5274 if (do_halt)
5275 {
5276 if (log)
5277 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5278 halt_error = Halt();
5279 }
5280 if (halt_error.Success())
5281 {
5282 if (log)
5283 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005284
Jim Ingham0161b492013-02-09 01:29:05 +00005285 real_timeout = TimeValue::Now();
5286 real_timeout.OffsetWithMicroSeconds(500000);
5287
5288 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005289
Jim Ingham0161b492013-02-09 01:29:05 +00005290 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005291 {
Jim Ingham0161b492013-02-09 01:29:05 +00005292 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5293 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005294 {
Jim Ingham0161b492013-02-09 01:29:05 +00005295 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5296 if (stop_state == lldb::eStateStopped
5297 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5298 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005299 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005300
Jim Ingham0161b492013-02-09 01:29:05 +00005301 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005302 {
Jim Ingham0161b492013-02-09 01:29:05 +00005303 // Between the time we initiated the Halt and the time we delivered it, the process could have
5304 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005305
Jim Ingham0161b492013-02-09 01:29:05 +00005306 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5307 {
5308 if (log)
5309 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5310 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005311 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005312 back_to_top = false;
5313 break;
5314 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005315
Jim Ingham0161b492013-02-09 01:29:05 +00005316 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5317 {
5318 if (log)
5319 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5320 "Exiting wait loop.");
5321 try_halt_again++;
5322 do_halt = false;
5323 continue;
5324 }
Sean Callanana46ec452012-07-11 21:31:24 +00005325
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005326 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005327 {
5328 if (log)
5329 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005330 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005331 back_to_top = false;
5332 break;
5333 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005334
Jim Ingham0161b492013-02-09 01:29:05 +00005335 if (before_first_timeout)
5336 {
5337 // Set all the other threads to run, and return to the top of the loop, which will continue;
5338 before_first_timeout = false;
5339 thread_plan_sp->SetStopOthers (false);
5340 if (log)
5341 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005342
Jim Ingham0161b492013-02-09 01:29:05 +00005343 back_to_top = true;
5344 break;
5345 }
5346 else
5347 {
5348 // Running all threads failed, so return Interrupted.
5349 if (log)
5350 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005351 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005352 back_to_top = false;
5353 break;
5354 }
Sean Callanana46ec452012-07-11 21:31:24 +00005355 }
5356 }
5357 else
Jim Ingham0161b492013-02-09 01:29:05 +00005358 { if (log)
5359 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5360 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005361 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005362 back_to_top = false;
5363 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005364 }
5365 }
Jim Ingham0161b492013-02-09 01:29:05 +00005366 else
5367 {
5368 try_halt_again++;
5369 continue;
5370 }
Sean Callanana46ec452012-07-11 21:31:24 +00005371 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005372
Jim Ingham0161b492013-02-09 01:29:05 +00005373 if (!back_to_top || try_halt_again > num_retries)
5374 break;
5375 else
5376 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005377 }
Sean Callanana46ec452012-07-11 21:31:24 +00005378 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005379
Sean Callanana46ec452012-07-11 21:31:24 +00005380 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5381 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5382 {
5383 StopPrivateStateThread();
5384 Error error;
5385 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005386 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005387 {
5388 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5389 }
5390 m_public_state.SetValueNoLock(old_state);
5391
5392 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005393
Jim Ingham184e9812013-01-15 02:47:48 +00005394 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5395 // could happen:
5396 // 1) The execution successfully completed
5397 // 2) We hit a breakpoint, and ignore_breakpoints was true
5398 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005399 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5400 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005401
Jim Ingham8646d3c2014-05-05 02:47:44 +00005402 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005403 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005404 {
5405 thread_plan_sp->RestoreThreadState();
5406 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005407
Sean Callanana46ec452012-07-11 21:31:24 +00005408 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005409 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005410 {
5411 if (log)
5412 {
5413 StreamString s;
5414 if (event_sp)
5415 event_sp->Dump (&s);
5416 else
5417 {
5418 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5419 }
5420
5421 StreamString ts;
5422
5423 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005424
Sean Callanana46ec452012-07-11 21:31:24 +00005425 do
5426 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005427 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005428 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005429 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005430 break;
5431 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005432 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005433 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005434 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005435 break;
5436 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005437 else
Sean Callanana46ec452012-07-11 21:31:24 +00005438 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005439 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5440
5441 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005442 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005443 event_explanation = "<no event data>";
5444 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005445 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005446
Jim Inghamcfc09352012-07-27 23:57:19 +00005447 Process *process = event_data->GetProcessSP().get();
5448
5449 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005450 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005451 event_explanation = "<no process>";
5452 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005453 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005454
Jim Inghamcfc09352012-07-27 23:57:19 +00005455 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005456
Jim Inghamcfc09352012-07-27 23:57:19 +00005457 uint32_t num_threads = thread_list.GetSize();
5458 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005459
Jim Inghamcfc09352012-07-27 23:57:19 +00005460 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005461
Jim Inghamcfc09352012-07-27 23:57:19 +00005462 for (thread_index = 0;
5463 thread_index < num_threads;
5464 ++thread_index)
5465 {
5466 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005467
Jim Inghamcfc09352012-07-27 23:57:19 +00005468 if (!thread)
5469 {
5470 ts.Printf("<?> ");
5471 continue;
5472 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005473
Daniel Malead01b2952012-11-29 21:49:15 +00005474 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005475 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005476
Jim Inghamcfc09352012-07-27 23:57:19 +00005477 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005478 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005479 else
5480 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005481
Jim Inghamcfc09352012-07-27 23:57:19 +00005482 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5483 if (stop_info_sp)
5484 {
5485 const char *stop_desc = stop_info_sp->GetDescription();
5486 if (stop_desc)
5487 ts.PutCString (stop_desc);
5488 }
5489 ts.Printf(">");
5490 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005491
Jim Inghamcfc09352012-07-27 23:57:19 +00005492 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005493 }
Sean Callanana46ec452012-07-11 21:31:24 +00005494 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005495
Jim Inghamcfc09352012-07-27 23:57:19 +00005496 if (event_explanation)
5497 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005498 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005499 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5500 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005501
Jim Inghame4483cf2013-09-27 01:13:01 +00005502 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005503 {
5504 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005505 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5506 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005507 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5508 thread_plan_sp->SetPrivate (orig_plan_private);
5509 }
5510 else
5511 {
5512 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005513 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5514 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005515 }
5516 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005517 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005518 {
5519 if (log)
5520 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005521
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005522 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005523 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005524 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005525 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005526 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005527 }
5528 else
5529 {
Sean Callanana46ec452012-07-11 21:31:24 +00005530 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005531 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005532 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005533 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005534 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005535 }
5536 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5537 {
5538 if (log)
5539 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005540 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005541 }
5542 else
5543 {
5544 if (log)
5545 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005546 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005547 {
5548 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005549 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005550 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5551 thread_plan_sp->SetPrivate (orig_plan_private);
5552 }
5553 }
5554 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005555
Sean Callanana46ec452012-07-11 21:31:24 +00005556 // Thread we ran the function in may have gone away because we ran the target
5557 // Check that it's still there, and if it is put it back in the context. Also restore the
5558 // frame in the context if it is still present.
5559 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5560 if (thread)
5561 {
5562 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5563 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005564
Sean Callanana46ec452012-07-11 21:31:24 +00005565 // Also restore the current process'es selected frame & thread, since this function calling may
5566 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005567
Sean Callanana46ec452012-07-11 21:31:24 +00005568 if (selected_tid != LLDB_INVALID_THREAD_ID)
5569 {
5570 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5571 {
5572 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005573 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005574 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005575 if (old_frame_sp)
5576 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005577 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005578 }
5579 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005580
Sean Callanana46ec452012-07-11 21:31:24 +00005581 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005582
Sean Callanana46ec452012-07-11 21:31:24 +00005583 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005584 {
Sean Callanana46ec452012-07-11 21:31:24 +00005585 if (log)
5586 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5587 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005588 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005589
Jim Inghamf48169b2010-11-30 02:22:11 +00005590 return return_value;
5591}
5592
5593const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005594Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005595{
5596 const char *result_name;
5597
5598 switch (result)
5599 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005600 case eExpressionCompleted:
5601 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005602 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005603 case eExpressionDiscarded:
5604 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005605 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005606 case eExpressionInterrupted:
5607 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005608 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005609 case eExpressionHitBreakpoint:
5610 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005611 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005612 case eExpressionSetupError:
5613 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005614 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005615 case eExpressionParseError:
5616 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005617 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005618 case eExpressionResultUnavailable:
5619 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005620 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005621 case eExpressionTimedOut:
5622 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005623 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005624 case eExpressionStoppedForDebug:
5625 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005626 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005627 }
5628 return result_name;
5629}
5630
Greg Clayton7260f622011-04-18 08:33:37 +00005631void
5632Process::GetStatus (Stream &strm)
5633{
5634 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005635 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005636 {
5637 if (state == eStateExited)
5638 {
5639 int exit_status = GetExitStatus();
5640 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005641 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005642 GetID(),
5643 exit_status,
5644 exit_status,
5645 exit_description ? exit_description : "");
5646 }
5647 else
5648 {
5649 if (state == eStateConnected)
5650 strm.Printf ("Connected to remote target.\n");
5651 else
Daniel Malead01b2952012-11-29 21:49:15 +00005652 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005653 }
5654 }
5655 else
5656 {
Daniel Malead01b2952012-11-29 21:49:15 +00005657 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005658 }
5659}
5660
5661size_t
5662Process::GetThreadStatus (Stream &strm,
5663 bool only_threads_with_stop_reason,
5664 uint32_t start_frame,
5665 uint32_t num_frames,
5666 uint32_t num_frames_with_source)
5667{
5668 size_t num_thread_infos_dumped = 0;
5669
Jim Ingham4a65fb12014-03-07 11:20:03 +00005670 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5671 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5672 // ID's, and look them up one by one:
5673
5674 uint32_t num_threads;
5675 std::vector<uint32_t> thread_index_array;
5676 //Scope for thread list locker;
5677 {
5678 Mutex::Locker locker (GetThreadList().GetMutex());
5679 ThreadList &curr_thread_list = GetThreadList();
5680 num_threads = curr_thread_list.GetSize();
5681 uint32_t idx;
5682 thread_index_array.resize(num_threads);
5683 for (idx = 0; idx < num_threads; ++idx)
5684 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5685 }
5686
Greg Clayton7260f622011-04-18 08:33:37 +00005687 for (uint32_t i = 0; i < num_threads; i++)
5688 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005689 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5690 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005691 {
5692 if (only_threads_with_stop_reason)
5693 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005694 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005695 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005696 continue;
5697 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005698 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005699 start_frame,
5700 num_frames,
5701 num_frames_with_source);
5702 ++num_thread_infos_dumped;
5703 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005704 else
5705 {
5706 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5707 if (log)
5708 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5709
5710 }
Greg Clayton7260f622011-04-18 08:33:37 +00005711 }
5712 return num_thread_infos_dumped;
5713}
5714
Greg Claytona9f40ad2012-02-22 04:37:26 +00005715void
5716Process::AddInvalidMemoryRegion (const LoadRange &region)
5717{
5718 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5719}
5720
5721bool
5722Process::RemoveInvalidMemoryRange (const LoadRange &region)
5723{
5724 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5725}
5726
Jim Ingham372787f2012-04-07 00:00:41 +00005727void
5728Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5729{
5730 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5731}
5732
5733bool
5734Process::RunPreResumeActions ()
5735{
5736 bool result = true;
5737 while (!m_pre_resume_actions.empty())
5738 {
5739 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5740 m_pre_resume_actions.pop_back();
5741 bool this_result = action.callback (action.baton);
5742 if (result == true) result = this_result;
5743 }
5744 return result;
5745}
5746
5747void
5748Process::ClearPreResumeActions ()
5749{
5750 m_pre_resume_actions.clear();
5751}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005752
Greg Claytonfa559e52012-05-18 02:38:05 +00005753void
5754Process::Flush ()
5755{
5756 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005757 m_extended_thread_list.Flush();
5758 m_extended_thread_stop_id = 0;
5759 m_queue_list.Clear();
5760 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005761}
Greg Clayton90ba8112012-12-05 00:16:59 +00005762
5763void
5764Process::DidExec ()
5765{
5766 Target &target = GetTarget();
5767 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005768 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005769 m_dynamic_checkers_ap.reset();
5770 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005771 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005772 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005773 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005774 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005775 m_image_tokens.clear();
5776 m_allocated_memory_cache.Clear();
5777 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005778 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005779 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005780 DoDidExec();
5781 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005782 // Flush the process (threads and all stack frames) after running CompleteAttach()
5783 // in case the dynamic loader loaded things in new locations.
5784 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005785
5786 // After we figure out what was loaded/unloaded in CompleteAttach,
5787 // we need to let the target know so it can do any cleanup it needs to.
5788 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005789}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005790
Jim Ingham1460e4b2014-01-10 23:46:59 +00005791addr_t
5792Process::ResolveIndirectFunction(const Address *address, Error &error)
5793{
5794 if (address == nullptr)
5795 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005796 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005797 return LLDB_INVALID_ADDRESS;
5798 }
5799
5800 addr_t function_addr = LLDB_INVALID_ADDRESS;
5801
5802 addr_t addr = address->GetLoadAddress(&GetTarget());
5803 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5804 if (iter != m_resolved_indirect_addresses.end())
5805 {
5806 function_addr = (*iter).second;
5807 }
5808 else
5809 {
5810 if (!InferiorCall(this, address, function_addr))
5811 {
5812 Symbol *symbol = address->CalculateSymbolContextSymbol();
5813 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5814 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5815 function_addr = LLDB_INVALID_ADDRESS;
5816 }
5817 else
5818 {
5819 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5820 }
5821 }
5822 return function_addr;
5823}
5824
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005825void
5826Process::ModulesDidLoad (ModuleList &module_list)
5827{
5828 SystemRuntime *sys_runtime = GetSystemRuntime();
5829 if (sys_runtime)
5830 {
5831 sys_runtime->ModulesDidLoad (module_list);
5832 }
5833
5834 GetJITLoaders().ModulesDidLoad (module_list);
5835}