blob: ab82db3a0def9a56c5eb8b107365d93e10b72610 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000024#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000025#include "lldb/Expression/ClangUserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000026#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000029#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000030#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Interpreter/CommandInterpreter.h"
33#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000035#include "lldb/Target/DynamicLoader.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000036#include "lldb/Target/JITLoader.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000037#include "lldb/Target/MemoryHistory.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000038#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000039#include "lldb/Target/LanguageRuntime.h"
40#include "lldb/Target/CPPLanguageRuntime.h"
41#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000042#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000044#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000045#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/Target.h"
47#include "lldb/Target/TargetList.h"
48#include "lldb/Target/Thread.h"
49#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000050#include "lldb/Target/ThreadPlanBase.h"
Kuba Breckaafdf8422014-10-10 23:43:03 +000051#include "lldb/Target/InstrumentationRuntime.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000052#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053
54using namespace lldb;
55using namespace lldb_private;
56
Greg Clayton67cc0632012-08-22 17:17:09 +000057
58// Comment out line below to disable memory caching, overriding the process setting
59// target.process.disable-memory-cache
60#define ENABLE_MEMORY_CACHING
61
62#ifdef ENABLE_MEMORY_CACHING
63#define DISABLE_MEM_CACHE_DEFAULT false
64#else
65#define DISABLE_MEM_CACHE_DEFAULT true
66#endif
67
68class ProcessOptionValueProperties : public OptionValueProperties
69{
70public:
71 ProcessOptionValueProperties (const ConstString &name) :
72 OptionValueProperties (name)
73 {
74 }
75
76 // This constructor is used when creating ProcessOptionValueProperties when it
77 // is part of a new lldb_private::Process instance. It will copy all current
78 // global property values as needed
79 ProcessOptionValueProperties (ProcessProperties *global_properties) :
80 OptionValueProperties(*global_properties->GetValueProperties())
81 {
82 }
83
84 virtual const Property *
85 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
86 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000087 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000088 // try and grab the setting from the current process if there is one. Else we just
89 // use the one from this instance.
90 if (exe_ctx)
91 {
92 Process *process = exe_ctx->GetProcessPtr();
93 if (process)
94 {
95 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
96 if (this != instance_properties)
97 return instance_properties->ProtectedGetPropertyAtIndex (idx);
98 }
99 }
100 return ProtectedGetPropertyAtIndex (idx);
101 }
102};
103
104static PropertyDefinition
105g_properties[] =
106{
107 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Ingham8c3f2762012-11-29 00:41:12 +0000108 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
109 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000110 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
111 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Claytone1e835c2012-11-29 18:48:47 +0000112 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham29950772013-01-26 02:19:28 +0000113 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Jim Inghamacff8952013-05-02 00:27:30 +0000114 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Jason Molendaf0340c92014-09-03 22:30:54 +0000115 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Greg Clayton67cc0632012-08-22 17:17:09 +0000116 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
117};
118
119enum {
120 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000121 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000122 ePropertyIgnoreBreakpointsInExpressions,
123 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000124 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000125 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000126 ePropertyDetachKeepsStopped,
127 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09 +0000128};
129
130ProcessProperties::ProcessProperties (bool is_global) :
131 Properties ()
132{
133 if (is_global)
134 {
135 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
136 m_collection_sp->Initialize(g_properties);
137 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000138 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000139 true,
140 Thread::GetGlobalProperties()->GetValueProperties());
141 }
142 else
143 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
144}
145
146ProcessProperties::~ProcessProperties()
147{
148}
149
150bool
151ProcessProperties::GetDisableMemoryCache() const
152{
153 const uint32_t idx = ePropertyDisableMemCache;
154 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
155}
156
Jason Molendaf0340c92014-09-03 22:30:54 +0000157uint64_t
158ProcessProperties::GetMemoryCacheLineSize() const
159{
160 const uint32_t idx = ePropertyMemCacheLineSize;
161 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
162}
163
Greg Clayton67cc0632012-08-22 17:17:09 +0000164Args
165ProcessProperties::GetExtraStartupCommands () const
166{
167 Args args;
168 const uint32_t idx = ePropertyExtraStartCommand;
169 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
170 return args;
171}
172
173void
174ProcessProperties::SetExtraStartupCommands (const Args &args)
175{
176 const uint32_t idx = ePropertyExtraStartCommand;
177 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
178}
179
Greg Claytonc9d645d2012-10-18 22:40:37 +0000180FileSpec
181ProcessProperties::GetPythonOSPluginPath () const
182{
183 const uint32_t idx = ePropertyPythonOSPluginPath;
184 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
185}
186
187void
188ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
189{
190 const uint32_t idx = ePropertyPythonOSPluginPath;
191 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
192}
193
Jim Ingham184e9812013-01-15 02:47:48 +0000194
195bool
196ProcessProperties::GetIgnoreBreakpointsInExpressions () const
197{
198 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
199 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
200}
201
202void
203ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
204{
205 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
206 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
207}
208
209bool
210ProcessProperties::GetUnwindOnErrorInExpressions () const
211{
212 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
213 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
214}
215
216void
217ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
218{
219 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
220 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
221}
222
Jim Ingham29950772013-01-26 02:19:28 +0000223bool
224ProcessProperties::GetStopOnSharedLibraryEvents () const
225{
226 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
228}
229
230void
231ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
232{
233 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
234 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
235}
236
Jim Inghamacff8952013-05-02 00:27:30 +0000237bool
238ProcessProperties::GetDetachKeepsStopped () const
239{
240 const uint32_t idx = ePropertyDetachKeepsStopped;
241 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
242}
243
244void
245ProcessProperties::SetDetachKeepsStopped (bool stop)
246{
247 const uint32_t idx = ePropertyDetachKeepsStopped;
248 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
249}
250
Greg Clayton32e0a752011-03-30 18:16:51 +0000251void
Greg Clayton8b82f082011-04-12 05:54:46 +0000252ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000253{
254 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000255 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000256 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000257
258 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000259 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000260
261 if (m_executable)
262 {
263 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
264 s.PutCString (" file = ");
265 m_executable.Dump(&s);
266 s.EOL();
267 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000268 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000269 if (argc > 0)
270 {
271 for (uint32_t i=0; i<argc; i++)
272 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000273 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000274 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000275 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000276 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000277 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000278 }
279 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000280
281 const uint32_t envc = m_environment.GetArgumentCount();
282 if (envc > 0)
283 {
284 for (uint32_t i=0; i<envc; i++)
285 {
286 const char *env = m_environment.GetArgumentAtIndex(i);
287 if (i < 10)
288 s.Printf (" env[%u] = %s\n", i, env);
289 else
290 s.Printf ("env[%u] = %s\n", i, env);
291 }
292 }
293
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000294 if (m_arch.IsValid())
295 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
296
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000298 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 cstr = platform->GetUserName (m_uid);
300 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000301 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000302 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000303 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000304 cstr = platform->GetGroupName (m_gid);
305 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000306 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000307 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000308 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000309 cstr = platform->GetUserName (m_euid);
310 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000311 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000312 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000313 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000314 cstr = platform->GetGroupName (m_egid);
315 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000316 }
317}
318
319void
Greg Clayton8b82f082011-04-12 05:54:46 +0000320ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000321{
Greg Clayton8b82f082011-04-12 05:54:46 +0000322 const char *label;
323 if (show_args || verbose)
324 label = "ARGUMENTS";
325 else
326 label = "NAME";
327
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000328 if (verbose)
329 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000330 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000331 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
332 }
333 else
334 {
Jim Ingham368ac222014-08-15 17:05:27 +0000335 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
336 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000337 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000338}
339
340void
Greg Clayton8b82f082011-04-12 05:54:46 +0000341ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000342{
343 if (m_pid != LLDB_INVALID_PROCESS_ID)
344 {
345 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000346 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000347
Greg Clayton32e0a752011-03-30 18:16:51 +0000348
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000349 if (verbose)
350 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000351 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000352 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
353 s.Printf ("%-10s ", cstr);
354 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000355 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000356
Greg Clayton8b82f082011-04-12 05:54:46 +0000357 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000358 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
359 s.Printf ("%-10s ", cstr);
360 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000361 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000362
Greg Clayton8b82f082011-04-12 05:54:46 +0000363 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000364 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
365 s.Printf ("%-10s ", cstr);
366 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000367 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000368
Greg Clayton8b82f082011-04-12 05:54:46 +0000369 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000370 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
371 s.Printf ("%-10s ", cstr);
372 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000373 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000374 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
375 }
376 else
377 {
Jim Ingham368ac222014-08-15 17:05:27 +0000378 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000379 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000380 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000381 }
382
Greg Clayton8b82f082011-04-12 05:54:46 +0000383 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000384 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000385 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000386 if (argc > 0)
387 {
388 for (uint32_t i=0; i<argc; i++)
389 {
390 if (i > 0)
391 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000392 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000393 }
394 }
395 }
396 else
397 {
398 s.PutCString (GetName());
399 }
400
401 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000402 }
403}
404
Greg Clayton8b82f082011-04-12 05:54:46 +0000405Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000406ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000407{
408 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000409 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000410
411 switch (short_option)
412 {
413 case 's': // Stop at program entry point
414 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
415 break;
416
Greg Clayton8b82f082011-04-12 05:54:46 +0000417 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000418 {
419 FileAction action;
420 if (action.Open (STDIN_FILENO, option_arg, true, false))
421 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000422 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000423 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000424
425 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000426 {
427 FileAction action;
428 if (action.Open (STDOUT_FILENO, option_arg, false, true))
429 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000430 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000431 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000432
433 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000434 {
435 FileAction action;
436 if (action.Open (STDERR_FILENO, option_arg, false, true))
437 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000438 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000439 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000440
Greg Clayton8b82f082011-04-12 05:54:46 +0000441 case 'p': // Process plug-in name
442 launch_info.SetProcessPluginName (option_arg);
443 break;
444
445 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000446 {
447 FileAction action;
448 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
449 launch_info.AppendFileAction (action);
450 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
451 launch_info.AppendFileAction (action);
452 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
453 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000454 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000455 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000456
457 case 'w':
458 launch_info.SetWorkingDirectory (option_arg);
459 break;
460
461 case 't': // Open process in new terminal window
462 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
463 break;
464
465 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000466 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
467 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000468 break;
469
Todd Fiala51637922014-08-19 17:40:43 +0000470 case 'A': // Disable ASLR.
471 {
472 bool success;
473 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
474 if (success)
475 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
476 else
477 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000478 break;
Todd Fiala51637922014-08-19 17:40:43 +0000479 }
480
481 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000482 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000483 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000484 else
Zachary Turner10687b02014-10-20 17:46:43 +0000485 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000486 break;
487
Greg Clayton8b82f082011-04-12 05:54:46 +0000488 case 'v':
489 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
490 break;
491
492 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000493 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000495 }
496 return error;
497}
498
499OptionDefinition
500ProcessLaunchCommandOptions::g_option_table[] =
501{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000502{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
Todd Fiala51637922014-08-19 17:40:43 +0000503{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000504{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
505{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
506{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
507{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
508{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000509
Zachary Turnerd37221d2014-07-09 16:31:49 +0000510{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
511{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
512{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000513
Zachary Turnerd37221d2014-07-09 16:31:49 +0000514{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000515
Zachary Turnerd37221d2014-07-09 16:31:49 +0000516{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000517
Zachary Turnerd37221d2014-07-09 16:31:49 +0000518{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000519};
520
521
522
523bool
524ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000525{
526 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
527 return true;
528 const char *match_name = m_match_info.GetName();
529 if (!match_name)
530 return true;
531
532 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
533}
534
535bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000536ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000537{
538 if (!NameMatches (proc_info.GetName()))
539 return false;
540
541 if (m_match_info.ProcessIDIsValid() &&
542 m_match_info.GetProcessID() != proc_info.GetProcessID())
543 return false;
544
545 if (m_match_info.ParentProcessIDIsValid() &&
546 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
547 return false;
548
Greg Clayton8b82f082011-04-12 05:54:46 +0000549 if (m_match_info.UserIDIsValid () &&
550 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000551 return false;
552
Greg Clayton8b82f082011-04-12 05:54:46 +0000553 if (m_match_info.GroupIDIsValid () &&
554 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000555 return false;
556
557 if (m_match_info.EffectiveUserIDIsValid () &&
558 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
559 return false;
560
561 if (m_match_info.EffectiveGroupIDIsValid () &&
562 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
563 return false;
564
565 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000566 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000567 return false;
568 return true;
569}
570
571bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000572ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000573{
574 if (m_name_match_type != eNameMatchIgnore)
575 return false;
576
577 if (m_match_info.ProcessIDIsValid())
578 return false;
579
580 if (m_match_info.ParentProcessIDIsValid())
581 return false;
582
Greg Clayton8b82f082011-04-12 05:54:46 +0000583 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000584 return false;
585
Greg Clayton8b82f082011-04-12 05:54:46 +0000586 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000587 return false;
588
589 if (m_match_info.EffectiveUserIDIsValid ())
590 return false;
591
592 if (m_match_info.EffectiveGroupIDIsValid ())
593 return false;
594
595 if (m_match_info.GetArchitecture().IsValid())
596 return false;
597
598 if (m_match_all_users)
599 return false;
600
601 return true;
602
603}
604
605void
Greg Clayton8b82f082011-04-12 05:54:46 +0000606ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000607{
608 m_match_info.Clear();
609 m_name_match_type = eNameMatchIgnore;
610 m_match_all_users = false;
611}
Greg Clayton58be07b2011-01-07 06:08:19 +0000612
Greg Claytonc3776bf2012-02-09 06:16:32 +0000613ProcessSP
614Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000615{
Greg Clayton949e8222013-01-16 17:29:04 +0000616 static uint32_t g_process_unique_id = 0;
617
Greg Claytonc3776bf2012-02-09 06:16:32 +0000618 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619 ProcessCreateInstance create_callback = NULL;
620 if (plugin_name)
621 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000622 ConstString const_plugin_name(plugin_name);
623 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000624 if (create_callback)
625 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000626 process_sp = create_callback(target, listener, crash_file_path);
627 if (process_sp)
628 {
Greg Clayton949e8222013-01-16 17:29:04 +0000629 if (process_sp->CanDebug(target, true))
630 {
631 process_sp->m_process_unique_id = ++g_process_unique_id;
632 }
633 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000634 process_sp.reset();
635 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636 }
637 }
638 else
639 {
Greg Claytonc982c762010-07-09 20:39:50 +0000640 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000642 process_sp = create_callback(target, listener, crash_file_path);
643 if (process_sp)
644 {
Greg Clayton949e8222013-01-16 17:29:04 +0000645 if (process_sp->CanDebug(target, false))
646 {
647 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000648 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000649 }
650 else
651 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000652 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653 }
654 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000655 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656}
657
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000658ConstString &
659Process::GetStaticBroadcasterClass ()
660{
661 static ConstString class_name ("lldb.process");
662 return class_name;
663}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664
665//----------------------------------------------------------------------
666// Process constructor
667//----------------------------------------------------------------------
668Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000669 Process(target, listener, Host::GetUnixSignals ())
670{
671 // This constructor just delegates to the full Process constructor,
672 // defaulting to using the Host's UnixSignals.
673}
674
675Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000676 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000678 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 m_public_state (eStateUnloaded),
681 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000682 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
683 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 m_private_state_listener ("lldb.process.internal_state_listener"),
685 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000686 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000687 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000688 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000689 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000690 m_exit_status (-1),
691 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000692 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000693 m_thread_mutex (Mutex::eMutexTypeRecursive),
694 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000695 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000696 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000697 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000698 m_queue_list (this),
699 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000700 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000701 m_image_tokens (),
702 m_listener (listener),
703 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000704 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000705 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000706 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000707 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000708 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000709 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000710 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000711 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000712 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
713 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000714 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000715 m_memory_cache (*this),
716 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000717 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000718 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000719 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000720 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000721 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000722 m_stop_info_override_callback (NULL),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000723 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000724 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000725 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000726 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000727 m_destroy_in_process (false),
728 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000730 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000731
Greg Clayton5160ce52013-03-27 23:08:40 +0000732 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000734 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735
Todd Fiala4ceced32014-08-29 17:35:57 +0000736 if (!m_unix_signals_sp)
737 m_unix_signals_sp.reset (new UnixSignals ());
738
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000739 SetEventName (eBroadcastBitStateChanged, "state-changed");
740 SetEventName (eBroadcastBitInterrupt, "interrupt");
741 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
742 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000743 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000744
Greg Clayton35a4cc52012-10-29 20:52:08 +0000745 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
746 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
747 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
748
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749 listener.StartListeningForEvents (this,
750 eBroadcastBitStateChanged |
751 eBroadcastBitInterrupt |
752 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000753 eBroadcastBitSTDERR |
754 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755
756 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000757 eBroadcastBitStateChanged |
758 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759
760 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
761 eBroadcastInternalStateControlStop |
762 eBroadcastInternalStateControlPause |
763 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000764 // We need something valid here, even if just the default UnixSignalsSP.
765 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766}
767
768//----------------------------------------------------------------------
769// Destructor
770//----------------------------------------------------------------------
771Process::~Process()
772{
Greg Clayton5160ce52013-03-27 23:08:40 +0000773 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000775 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000776 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000777
778 // ThreadList::Clear() will try to acquire this process's mutex, so
779 // explicitly clear the thread list here to ensure that the mutex
780 // is not destroyed before the thread list.
781 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000782}
783
Greg Clayton67cc0632012-08-22 17:17:09 +0000784const ProcessPropertiesSP &
785Process::GetGlobalProperties()
786{
787 static ProcessPropertiesSP g_settings_sp;
788 if (!g_settings_sp)
789 g_settings_sp.reset (new ProcessProperties (true));
790 return g_settings_sp;
791}
792
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793void
794Process::Finalize()
795{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000796 switch (GetPrivateState())
797 {
798 case eStateConnected:
799 case eStateAttaching:
800 case eStateLaunching:
801 case eStateStopped:
802 case eStateRunning:
803 case eStateStepping:
804 case eStateCrashed:
805 case eStateSuspended:
806 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000807 {
808 // FIXME: This will have to be a process setting:
809 bool keep_stopped = false;
810 Detach(keep_stopped);
811 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000812 else
813 Destroy();
814 break;
815
816 case eStateInvalid:
817 case eStateUnloaded:
818 case eStateDetached:
819 case eStateExited:
820 break;
821 }
822
Greg Clayton1ed54f52011-10-01 00:45:15 +0000823 // Clear our broadcaster before we proceed with destroying
824 Broadcaster::Clear();
825
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 // Do any cleanup needed prior to being destructed... Subclasses
827 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000828
829 // We need to destroy the loader before the derived Process class gets destroyed
830 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000831 m_dynamic_checkers_ap.reset();
832 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000833 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000834 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000835 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000836 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000837 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000838 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000839 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000840 m_queue_list.Clear();
841 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000842 std::vector<Notifications> empty_notifications;
843 m_notifications.swap(empty_notifications);
844 m_image_tokens.clear();
845 m_memory_cache.Clear();
846 m_allocated_memory_cache.Clear();
847 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000848 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000849 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000850 m_stop_info_override_callback = NULL;
Greg Clayton35a4cc52012-10-29 20:52:08 +0000851//#ifdef LLDB_CONFIGURATION_DEBUG
852// StreamFile s(stdout, false);
853// EventSP event_sp;
854// while (m_private_state_listener.GetNextEvent(event_sp))
855// {
856// event_sp->Dump (&s);
857// s.EOL();
858// }
859//#endif
860 // We have to be very careful here as the m_private_state_listener might
861 // contain events that have ProcessSP values in them which can keep this
862 // process around forever. These events need to be cleared out.
863 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000864 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
865 m_public_run_lock.SetStopped();
866 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
867 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000868 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869}
870
871void
872Process::RegisterNotificationCallbacks (const Notifications& callbacks)
873{
874 m_notifications.push_back(callbacks);
875 if (callbacks.initialize != NULL)
876 callbacks.initialize (callbacks.baton, this);
877}
878
879bool
880Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
881{
882 std::vector<Notifications>::iterator pos, end = m_notifications.end();
883 for (pos = m_notifications.begin(); pos != end; ++pos)
884 {
885 if (pos->baton == callbacks.baton &&
886 pos->initialize == callbacks.initialize &&
887 pos->process_state_changed == callbacks.process_state_changed)
888 {
889 m_notifications.erase(pos);
890 return true;
891 }
892 }
893 return false;
894}
895
896void
897Process::SynchronouslyNotifyStateChanged (StateType state)
898{
899 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
900 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
901 {
902 if (notification_pos->process_state_changed)
903 notification_pos->process_state_changed (notification_pos->baton, this, state);
904 }
905}
906
907// FIXME: We need to do some work on events before the general Listener sees them.
908// For instance if we are continuing from a breakpoint, we need to ensure that we do
909// the little "insert real insn, step & stop" trick. But we can't do that when the
910// event is delivered by the broadcaster - since that is done on the thread that is
911// waiting for new events, so if we needed more than one event for our handling, we would
912// stall. So instead we do it when we fetch the event off of the queue.
913//
914
915StateType
916Process::GetNextEvent (EventSP &event_sp)
917{
918 StateType state = eStateInvalid;
919
920 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
921 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
922
923 return state;
924}
925
Todd Fialaa3b89e22014-08-12 14:33:19 +0000926bool
927Process::SyncIOHandler (uint64_t timeout_msec)
928{
929 bool timed_out = false;
930
931 // don't sync (potentially context switch) in case where there is no process IO
932 if (m_process_input_reader)
933 {
934 TimeValue timeout = TimeValue::Now();
935 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
936
937 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
938
939 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
940 if(log)
941 {
942 if(timed_out)
943 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
944 else
945 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
946 }
947
Shawn Best1ded74a2014-10-08 01:50:37 +0000948 // reset sync one-shot so it will be ready for next launch
Todd Fialaa3b89e22014-08-12 14:33:19 +0000949 m_iohandler_sync.SetValue(false, eBroadcastNever);
950 }
951
952 return !timed_out;
953}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954
955StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000956Process::WaitForProcessToStop (const TimeValue *timeout,
957 EventSP *event_sp_ptr,
958 bool wait_always,
959 Listener *hijack_listener,
960 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961{
Jim Ingham4b536182011-08-09 02:12:22 +0000962 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
963 // We have to actually check each event, and in the case of a stopped event check the restarted flag
964 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000965 if (event_sp_ptr)
966 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000967 StateType state = GetState();
968 // If we are exited or detached, we won't ever get back to any
969 // other valid state...
970 if (state == eStateDetached || state == eStateExited)
971 return state;
972
Daniel Malea9e9919f2013-10-09 16:56:28 +0000973 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
974 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000975 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
976 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000977
978 if (!wait_always &&
979 StateIsStoppedState(state, true) &&
980 StateIsStoppedState(GetPrivateState(), true)) {
981 if (log)
982 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
983 __FUNCTION__);
984 return state;
985 }
986
Jim Ingham4b536182011-08-09 02:12:22 +0000987 while (state != eStateInvalid)
988 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000989 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000990 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000991 if (event_sp_ptr && event_sp)
992 *event_sp_ptr = event_sp;
993
Greg Claytondc6224e2014-10-21 01:00:42 +0000994 bool pop_process_io_handler = hijack_listener != NULL;
995 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
996
Jim Ingham4b536182011-08-09 02:12:22 +0000997 switch (state)
998 {
999 case eStateCrashed:
1000 case eStateDetached:
1001 case eStateExited:
1002 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001003 // We need to toggle the run lock as this won't get done in
1004 // SetPublicState() if the process is hijacked.
1005 if (hijack_listener)
1006 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001007 return state;
1008 case eStateStopped:
1009 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1010 continue;
1011 else
Greg Clayton44d93782014-01-27 23:43:24 +00001012 {
1013 // We need to toggle the run lock as this won't get done in
1014 // SetPublicState() if the process is hijacked.
1015 if (hijack_listener)
1016 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001017 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001018 }
Jim Ingham4b536182011-08-09 02:12:22 +00001019 default:
1020 continue;
1021 }
1022 }
1023 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024}
1025
Greg Claytondc6224e2014-10-21 01:00:42 +00001026bool
1027Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1028 Stream *stream,
1029 bool &pop_process_io_handler)
1030{
1031 const bool handle_pop = pop_process_io_handler == true;
1032
1033 pop_process_io_handler = false;
1034 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1035
1036 if (!process_sp)
1037 return false;
1038
1039 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1040 if (event_state == eStateInvalid)
1041 return false;
1042
1043 switch (event_state)
1044 {
1045 case eStateInvalid:
1046 case eStateUnloaded:
1047 case eStateConnected:
1048 case eStateAttaching:
1049 case eStateLaunching:
1050 case eStateStepping:
1051 case eStateDetached:
1052 {
1053 if (stream)
1054 stream->Printf ("Process %" PRIu64 " %s\n",
1055 process_sp->GetID(),
1056 StateAsCString (event_state));
1057
1058 if (event_state == eStateDetached)
1059 pop_process_io_handler = true;
1060 }
1061 break;
1062
1063 case eStateRunning:
1064 // Don't be chatty when we run...
1065 break;
1066
1067 case eStateExited:
1068 if (stream)
1069 process_sp->GetStatus(*stream);
1070 pop_process_io_handler = true;
1071 break;
1072
1073 case eStateStopped:
1074 case eStateCrashed:
1075 case eStateSuspended:
1076 // Make sure the program hasn't been auto-restarted:
1077 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1078 {
1079 if (stream)
1080 {
1081 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1082 if (num_reasons > 0)
1083 {
1084 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1085 if (num_reasons == 1)
1086 {
1087 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1088 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1089 process_sp->GetID(),
1090 reason ? reason : "<UNKNOWN REASON>");
1091 }
1092 else
1093 {
1094 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1095 process_sp->GetID());
1096
1097
1098 for (size_t i = 0; i < num_reasons; i++)
1099 {
1100 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1101 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1102 }
1103 }
1104 }
1105 }
1106 }
1107 else
1108 {
1109 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1110 {
1111 ThreadList &thread_list = process_sp->GetThreadList();
1112 Mutex::Locker locker (thread_list.GetMutex());
1113
1114 ThreadSP curr_thread (thread_list.GetSelectedThread());
1115 ThreadSP thread;
1116 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1117 if (curr_thread)
1118 curr_thread_stop_reason = curr_thread->GetStopReason();
1119 if (!curr_thread ||
1120 !curr_thread->IsValid() ||
1121 curr_thread_stop_reason == eStopReasonInvalid ||
1122 curr_thread_stop_reason == eStopReasonNone)
1123 {
1124 // Prefer a thread that has just completed its plan over another thread as current thread.
1125 ThreadSP plan_thread;
1126 ThreadSP other_thread;
1127 const size_t num_threads = thread_list.GetSize();
1128 size_t i;
1129 for (i = 0; i < num_threads; ++i)
1130 {
1131 thread = thread_list.GetThreadAtIndex(i);
1132 StopReason thread_stop_reason = thread->GetStopReason();
1133 switch (thread_stop_reason)
1134 {
1135 case eStopReasonInvalid:
1136 case eStopReasonNone:
1137 break;
1138
1139 case eStopReasonTrace:
1140 case eStopReasonBreakpoint:
1141 case eStopReasonWatchpoint:
1142 case eStopReasonSignal:
1143 case eStopReasonException:
1144 case eStopReasonExec:
1145 case eStopReasonThreadExiting:
1146 case eStopReasonInstrumentation:
1147 if (!other_thread)
1148 other_thread = thread;
1149 break;
1150 case eStopReasonPlanComplete:
1151 if (!plan_thread)
1152 plan_thread = thread;
1153 break;
1154 }
1155 }
1156 if (plan_thread)
1157 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1158 else if (other_thread)
1159 thread_list.SetSelectedThreadByID (other_thread->GetID());
1160 else
1161 {
1162 if (curr_thread && curr_thread->IsValid())
1163 thread = curr_thread;
1164 else
1165 thread = thread_list.GetThreadAtIndex(0);
1166
1167 if (thread)
1168 thread_list.SetSelectedThreadByID (thread->GetID());
1169 }
1170 }
1171 }
1172 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1173 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1174 // have a hard time restarting the process.
1175 if (stream)
1176 {
1177 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1178 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1179 {
1180 const bool only_threads_with_stop_reason = true;
1181 const uint32_t start_frame = 0;
1182 const uint32_t num_frames = 1;
1183 const uint32_t num_frames_with_source = 1;
1184 process_sp->GetStatus(*stream);
1185 process_sp->GetThreadStatus (*stream,
1186 only_threads_with_stop_reason,
1187 start_frame,
1188 num_frames,
1189 num_frames_with_source);
1190 }
1191 else
1192 {
1193 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1194 if (target_idx != UINT32_MAX)
1195 stream->Printf ("Target %d: (", target_idx);
1196 else
1197 stream->Printf ("Target <unknown index>: (");
1198 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1199 stream->Printf (") stopped.\n");
1200 }
1201 }
1202
1203 // Pop the process IO handler
1204 pop_process_io_handler = true;
1205 }
1206 break;
1207 }
1208
1209 if (handle_pop && pop_process_io_handler)
1210 process_sp->PopProcessIOHandler();
1211
1212 return true;
1213}
1214
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215
1216StateType
1217Process::WaitForState
1218(
1219 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001220 const StateType *match_states,
1221 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001222)
1223{
1224 EventSP event_sp;
1225 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001226 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227 while (state != eStateInvalid)
1228 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001229 // If we are exited or detached, we won't ever get back to any
1230 // other valid state...
1231 if (state == eStateDetached || state == eStateExited)
1232 return state;
1233
Greg Clayton44d93782014-01-27 23:43:24 +00001234 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235
1236 for (i=0; i<num_match_states; ++i)
1237 {
1238 if (match_states[i] == state)
1239 return state;
1240 }
1241 }
1242 return state;
1243}
1244
Jim Ingham30f9b212010-10-11 23:53:14 +00001245bool
1246Process::HijackProcessEvents (Listener *listener)
1247{
1248 if (listener != NULL)
1249 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001250 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001251 }
1252 else
1253 return false;
1254}
1255
1256void
1257Process::RestoreProcessEvents ()
1258{
1259 RestoreBroadcaster();
1260}
1261
Jim Ingham0f16e732011-02-08 05:20:59 +00001262bool
1263Process::HijackPrivateProcessEvents (Listener *listener)
1264{
1265 if (listener != NULL)
1266 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001267 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001268 }
1269 else
1270 return false;
1271}
1272
1273void
1274Process::RestorePrivateProcessEvents ()
1275{
1276 m_private_state_broadcaster.RestoreBroadcaster();
1277}
1278
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001280Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281{
Greg Clayton5160ce52013-03-27 23:08:40 +00001282 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283
1284 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001285 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1286 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001287
Greg Clayton44d93782014-01-27 23:43:24 +00001288 Listener *listener = hijack_listener;
1289 if (listener == NULL)
1290 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001292 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001293 if (listener->WaitForEventForBroadcasterWithType (timeout,
1294 this,
1295 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1296 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001297 {
1298 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1299 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1300 else if (log)
1301 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1302 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001303
1304 if (log)
1305 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001306 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 StateAsCString(state));
1308 return state;
1309}
1310
1311Event *
1312Process::PeekAtStateChangedEvents ()
1313{
Greg Clayton5160ce52013-03-27 23:08:40 +00001314 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315
1316 if (log)
1317 log->Printf ("Process::%s...", __FUNCTION__);
1318
1319 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001320 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1321 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322 if (log)
1323 {
1324 if (event_ptr)
1325 {
1326 log->Printf ("Process::%s (event_ptr) => %s",
1327 __FUNCTION__,
1328 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1329 }
1330 else
1331 {
1332 log->Printf ("Process::%s no events found",
1333 __FUNCTION__);
1334 }
1335 }
1336 return event_ptr;
1337}
1338
1339StateType
1340Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1341{
Greg Clayton5160ce52013-03-27 23:08:40 +00001342 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343
1344 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001345 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1346 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347
1348 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001349 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1350 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001351 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001352 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001353 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1354 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355
1356 // This is a bit of a hack, but when we wait here we could very well return
1357 // to the command-line, and that could disable the log, which would render the
1358 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001359 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001360 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1361 __FUNCTION__, static_cast<const void *>(timeout),
1362 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001363 return state;
1364}
1365
1366bool
1367Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1368{
Greg Clayton5160ce52013-03-27 23:08:40 +00001369 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370
1371 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001372 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1373 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374
1375 if (control_only)
1376 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1377 else
1378 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1379}
1380
1381bool
1382Process::IsRunning () const
1383{
1384 return StateIsRunningState (m_public_state.GetValue());
1385}
1386
1387int
1388Process::GetExitStatus ()
1389{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001390 Mutex::Locker locker (m_exit_status_mutex);
1391
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392 if (m_public_state.GetValue() == eStateExited)
1393 return m_exit_status;
1394 return -1;
1395}
1396
Greg Clayton85851dd2010-12-04 00:10:17 +00001397
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398const char *
1399Process::GetExitDescription ()
1400{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001401 Mutex::Locker locker (m_exit_status_mutex);
1402
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001403 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1404 return m_exit_string.c_str();
1405 return NULL;
1406}
1407
Greg Clayton6779606a2011-01-22 23:43:18 +00001408bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409Process::SetExitStatus (int status, const char *cstr)
1410{
Greg Clayton5160ce52013-03-27 23:08:40 +00001411 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001412 if (log)
1413 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1414 status, status,
1415 cstr ? "\"" : "",
1416 cstr ? cstr : "NULL",
1417 cstr ? "\"" : "");
1418
Greg Clayton6779606a2011-01-22 23:43:18 +00001419 // We were already in the exited state
1420 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001421 {
Greg Clayton385d6032011-01-26 23:47:29 +00001422 if (log)
1423 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001424 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001425 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001426
Todd Fiala7b0917a2014-09-15 20:07:33 +00001427 // use a mutex to protect the status and string during updating
1428 {
1429 Mutex::Locker locker (m_exit_status_mutex);
1430
1431 m_exit_status = status;
1432 if (cstr)
1433 m_exit_string = cstr;
1434 else
1435 m_exit_string.clear();
1436 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437
Greg Clayton6779606a2011-01-22 23:43:18 +00001438 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001439
Greg Clayton6779606a2011-01-22 23:43:18 +00001440 SetPrivateState (eStateExited);
1441 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442}
1443
1444// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001445// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001446// found in the global target list (we want to be completely sure that the
1447// lldb_private::Process doesn't go away before we can deliver the signal.
1448bool
Greg Claytone4e45922011-11-16 05:37:56 +00001449Process::SetProcessExitStatus (void *callback_baton,
1450 lldb::pid_t pid,
1451 bool exited,
1452 int signo, // Zero for no signal
1453 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001454)
1455{
Greg Clayton5160ce52013-03-27 23:08:40 +00001456 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001457 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001458 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001459 callback_baton,
1460 pid,
1461 exited,
1462 signo,
1463 exit_status);
1464
1465 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001466 {
Greg Clayton66111032010-06-23 01:19:29 +00001467 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001468 if (target_sp)
1469 {
1470 ProcessSP process_sp (target_sp->GetProcessSP());
1471 if (process_sp)
1472 {
1473 const char *signal_cstr = NULL;
1474 if (signo)
1475 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1476
1477 process_sp->SetExitStatus (exit_status, signal_cstr);
1478 }
1479 }
1480 return true;
1481 }
1482 return false;
1483}
1484
1485
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001486void
1487Process::UpdateThreadListIfNeeded ()
1488{
1489 const uint32_t stop_id = GetStopID();
1490 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1491 {
Greg Clayton2637f822011-11-17 01:23:07 +00001492 const StateType state = GetPrivateState();
1493 if (StateIsStoppedState (state, true))
1494 {
1495 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001496 // m_thread_list does have its own mutex, but we need to
1497 // hold onto the mutex between the call to UpdateThreadList(...)
1498 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001499 ThreadList &old_thread_list = m_thread_list;
1500 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001501 ThreadList new_thread_list(this);
1502 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001503 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001504 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001505 {
Jim Ingham09437922013-03-01 20:04:25 +00001506 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1507 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1508 // shutting us down, causing a deadlock.
1509 if (!m_destroy_in_process)
1510 {
1511 OperatingSystem *os = GetOperatingSystem ();
1512 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001513 {
1514 // Clear any old backing threads where memory threads might have been
1515 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001516 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001517 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001518 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001519
1520 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001521 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1522 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1523 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 +00001524 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001525 else
1526 {
1527 // No OS plug-in, the new thread list is the same as the real thread list
1528 new_thread_list = real_thread_list;
1529 }
Jim Ingham09437922013-03-01 20:04:25 +00001530 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001531
1532 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001533 m_thread_list.Update (new_thread_list);
1534 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001535
Jason Molenda4ff13262013-11-20 00:31:38 +00001536 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1537 {
1538 // Clear any extended threads that we may have accumulated previously
1539 m_extended_thread_list.Clear();
1540 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001541
1542 m_queue_list.Clear();
1543 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001544 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001545 }
Greg Clayton2637f822011-11-17 01:23:07 +00001546 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001547 }
1548}
1549
Jason Molenda5e8dce42013-12-13 00:29:16 +00001550void
1551Process::UpdateQueueListIfNeeded ()
1552{
1553 if (m_system_runtime_ap.get())
1554 {
1555 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1556 {
1557 const StateType state = GetPrivateState();
1558 if (StateIsStoppedState (state, true))
1559 {
1560 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1561 m_queue_list_stop_id = GetLastNaturalStopID();
1562 }
1563 }
1564 }
1565}
1566
Greg Claytona4d87472013-01-18 23:41:08 +00001567ThreadSP
1568Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1569{
1570 OperatingSystem *os = GetOperatingSystem ();
1571 if (os)
1572 return os->CreateThread(tid, context);
1573 return ThreadSP();
1574}
1575
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001576uint32_t
1577Process::GetNextThreadIndexID (uint64_t thread_id)
1578{
1579 return AssignIndexIDToThread(thread_id);
1580}
1581
1582bool
1583Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1584{
1585 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1586 if (iterator == m_thread_id_to_index_id_map.end())
1587 {
1588 return false;
1589 }
1590 else
1591 {
1592 return true;
1593 }
1594}
1595
1596uint32_t
1597Process::AssignIndexIDToThread(uint64_t thread_id)
1598{
1599 uint32_t result = 0;
1600 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1601 if (iterator == m_thread_id_to_index_id_map.end())
1602 {
1603 result = ++m_thread_index_id;
1604 m_thread_id_to_index_id_map[thread_id] = result;
1605 }
1606 else
1607 {
1608 result = iterator->second;
1609 }
1610
1611 return result;
1612}
1613
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001614StateType
1615Process::GetState()
1616{
1617 // If any other threads access this we will need a mutex for it
1618 return m_public_state.GetValue ();
1619}
1620
Greg Claytondc6224e2014-10-21 01:00:42 +00001621bool
1622Process::StateChangedIsExternallyHijacked()
1623{
1624 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1625 {
1626 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1627 return true;
1628 }
1629 return false;
1630}
1631
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632void
Jim Ingham221d51c2013-05-08 00:35:16 +00001633Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634{
Greg Clayton5160ce52013-03-27 23:08:40 +00001635 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001636 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001637 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001638 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001639 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001640
1641 // On the transition from Run to Stopped, we unlock the writer end of the
1642 // run lock. The lock gets locked in Resume, which is the public API
1643 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001644 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001645 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001646 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001647 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001648 if (log)
1649 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001650 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001651 }
1652 else
1653 {
1654 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1655 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001656 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001657 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001658 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001659 {
1660 if (log)
1661 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001662 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001663 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001664 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001665 }
1666 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667}
1668
Jim Ingham3b8285d2012-04-19 01:40:33 +00001669Error
1670Process::Resume ()
1671{
Greg Clayton5160ce52013-03-27 23:08:40 +00001672 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001673 if (log)
1674 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001675 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001676 {
1677 Error error("Resume request failed - process still running.");
1678 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001679 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001680 return error;
1681 }
1682 return PrivateResume();
1683}
1684
Greg Claytondc6224e2014-10-21 01:00:42 +00001685Error
1686Process::ResumeSynchronous (Stream *stream)
1687{
1688 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1689 if (log)
1690 log->Printf("Process::ResumeSynchronous -- locking run lock");
1691 if (!m_public_run_lock.TrySetRunning())
1692 {
1693 Error error("Resume request failed - process still running.");
1694 if (log)
1695 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1696 return error;
1697 }
1698
1699 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1700 HijackProcessEvents(listener_sp.get());
1701
1702 Error error = PrivateResume();
1703
1704 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1705
1706 // Undo the hijacking of process events...
1707 RestoreProcessEvents();
1708
1709 if (error.Success() && !StateIsStoppedState(state, false))
1710 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1711
1712 return error;
1713}
1714
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715StateType
1716Process::GetPrivateState ()
1717{
1718 return m_private_state.GetValue();
1719}
1720
1721void
1722Process::SetPrivateState (StateType new_state)
1723{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001724 if (m_finalize_called)
1725 return;
1726
Greg Clayton5160ce52013-03-27 23:08:40 +00001727 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728 bool state_changed = false;
1729
1730 if (log)
1731 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1732
Andrew Kaylor29d65742013-05-10 17:19:04 +00001733 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734 Mutex::Locker locker(m_private_state.GetMutex());
1735
1736 const StateType old_state = m_private_state.GetValueNoLock ();
1737 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001738
Greg Claytonaa49c832013-05-03 22:25:56 +00001739 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1740 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1741 if (old_state_is_stopped != new_state_is_stopped)
1742 {
1743 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001744 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001745 else
Ed Maste64fad602013-07-29 20:58:06 +00001746 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001747 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001748
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001749 if (state_changed)
1750 {
1751 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001752 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001753 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001754 // Note, this currently assumes that all threads in the list
1755 // stop when the process stops. In the future we will want to
1756 // support a debugging model where some threads continue to run
1757 // while others are stopped. When that happens we will either need
1758 // a way for the thread list to identify which threads are stopping
1759 // or create a special thread list containing only threads which
1760 // actually stopped.
1761 //
1762 // The process plugin is responsible for managing the actual
1763 // behavior of the threads and should have stopped any threads
1764 // that are going to stop before we get here.
1765 m_thread_list.DidStop();
1766
Jim Ingham4b536182011-08-09 02:12:22 +00001767 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001768 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001770 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001771 }
1772 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001773 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1774 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1775 else
1776 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001777 }
1778 else
1779 {
1780 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001781 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001782 }
1783}
1784
Jim Ingham0faa43f2011-11-08 03:00:11 +00001785void
1786Process::SetRunningUserExpression (bool on)
1787{
1788 m_mod_id.SetRunningUserExpression (on);
1789}
1790
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001791addr_t
1792Process::GetImageInfoAddress()
1793{
1794 return LLDB_INVALID_ADDRESS;
1795}
1796
Greg Clayton8f343b02010-11-04 01:54:29 +00001797//----------------------------------------------------------------------
1798// LoadImage
1799//
1800// This function provides a default implementation that works for most
1801// unix variants. Any Process subclasses that need to do shared library
1802// loading differently should override LoadImage and UnloadImage and
1803// do what is needed.
1804//----------------------------------------------------------------------
1805uint32_t
1806Process::LoadImage (const FileSpec &image_spec, Error &error)
1807{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001808 char path[PATH_MAX];
1809 image_spec.GetPath(path, sizeof(path));
1810
Greg Clayton8f343b02010-11-04 01:54:29 +00001811 DynamicLoader *loader = GetDynamicLoader();
1812 if (loader)
1813 {
1814 error = loader->CanLoadImage();
1815 if (error.Fail())
1816 return LLDB_INVALID_IMAGE_TOKEN;
1817 }
1818
1819 if (error.Success())
1820 {
1821 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001822
1823 if (thread_sp)
1824 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001825 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001826
1827 if (frame_sp)
1828 {
1829 ExecutionContext exe_ctx;
1830 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001831 EvaluateExpressionOptions expr_options;
1832 expr_options.SetUnwindOnError(true);
1833 expr_options.SetIgnoreBreakpoints(true);
1834 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001835 expr_options.SetResultIsInternal(true);
1836
Greg Clayton8f343b02010-11-04 01:54:29 +00001837 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001838 expr.Printf(R"(
1839 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1840 the_result.image_ptr = dlopen ("%s", 2);
1841 if (the_result.image_ptr == (void *) 0x0)
1842 {
1843 the_result.error_str = dlerror();
1844 }
1845 else
1846 {
1847 the_result.error_str = (const char *) 0x0;
1848 }
1849 the_result;
1850 )",
1851 path);
1852 const char *prefix = R"(
1853 extern "C" void* dlopen (const char *path, int mode);
1854 extern "C" const char *dlerror (void);
1855 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001856 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001857 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001858 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001859 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001860 expr.GetData(),
1861 prefix,
1862 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001863 expr_error);
1864 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001865 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001866 error = result_valobj_sp->GetError();
1867 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001868 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001869 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001870 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1871 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001872 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001873 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1874 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1875 {
1876 uint32_t image_token = m_image_tokens.size();
1877 m_image_tokens.push_back (image_ptr);
1878 return image_token;
1879 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001880 else if (image_ptr == 0)
1881 {
Jim Ingham6971b862014-07-19 00:37:06 +00001882 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1883 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001884 {
Jim Ingham6971b862014-07-19 00:37:06 +00001885 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001886 {
Enrico Granata2206b482014-10-30 18:27:31 +00001887 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1888 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001889 if (error.Success() && num_chars > 0)
1890 {
1891 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001892 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1893 }
1894 else
1895 {
1896 error.Clear();
1897 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001898 }
1899 }
1900 }
1901 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001902 }
1903 }
1904 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001905 else
1906 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001907 }
1908 }
1909 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001910 if (!error.AsCString())
1911 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001912 return LLDB_INVALID_IMAGE_TOKEN;
1913}
1914
1915//----------------------------------------------------------------------
1916// UnloadImage
1917//
1918// This function provides a default implementation that works for most
1919// unix variants. Any Process subclasses that need to do shared library
1920// loading differently should override LoadImage and UnloadImage and
1921// do what is needed.
1922//----------------------------------------------------------------------
1923Error
1924Process::UnloadImage (uint32_t image_token)
1925{
1926 Error error;
1927 if (image_token < m_image_tokens.size())
1928 {
1929 const addr_t image_addr = m_image_tokens[image_token];
1930 if (image_addr == LLDB_INVALID_ADDRESS)
1931 {
1932 error.SetErrorString("image already unloaded");
1933 }
1934 else
1935 {
1936 DynamicLoader *loader = GetDynamicLoader();
1937 if (loader)
1938 error = loader->CanLoadImage();
1939
1940 if (error.Success())
1941 {
1942 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001943
1944 if (thread_sp)
1945 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001946 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001947
1948 if (frame_sp)
1949 {
1950 ExecutionContext exe_ctx;
1951 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001952 EvaluateExpressionOptions expr_options;
1953 expr_options.SetUnwindOnError(true);
1954 expr_options.SetIgnoreBreakpoints(true);
1955 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001956 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001957 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001958 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001959 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001960 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001961 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001962 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001963 expr.GetData(),
1964 prefix,
1965 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001966 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001967 if (result_valobj_sp->GetError().Success())
1968 {
1969 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001970 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001971 {
1972 if (scalar.UInt(1))
1973 {
1974 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1975 }
1976 else
1977 {
1978 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1979 }
1980 }
1981 }
1982 else
1983 {
1984 error = result_valobj_sp->GetError();
1985 }
1986 }
1987 }
1988 }
1989 }
1990 }
1991 else
1992 {
1993 error.SetErrorString("invalid image token");
1994 }
1995 return error;
1996}
1997
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001998const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001999Process::GetABI()
2000{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002001 if (!m_abi_sp)
2002 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2003 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002004}
2005
Jim Ingham22777012010-09-23 02:01:19 +00002006LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002007Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002008{
2009 LanguageRuntimeCollection::iterator pos;
2010 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002011 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002012 {
Jim Inghamab175242012-03-10 00:22:19 +00002013 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002014
Jim Inghamab175242012-03-10 00:22:19 +00002015 m_language_runtimes[language] = runtime_sp;
2016 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002017 }
2018 else
2019 return (*pos).second.get();
2020}
2021
2022CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002023Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002024{
Jim Inghamab175242012-03-10 00:22:19 +00002025 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002026 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2027 return static_cast<CPPLanguageRuntime *> (runtime);
2028 return NULL;
2029}
2030
2031ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002032Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002033{
Jim Inghamab175242012-03-10 00:22:19 +00002034 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002035 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2036 return static_cast<ObjCLanguageRuntime *> (runtime);
2037 return NULL;
2038}
2039
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002040bool
2041Process::IsPossibleDynamicValue (ValueObject& in_value)
2042{
2043 if (in_value.IsDynamic())
2044 return false;
2045 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2046
2047 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2048 {
2049 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2050 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2051 }
2052
2053 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2054 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2055 return true;
2056
2057 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2058 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2059}
2060
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061BreakpointSiteList &
2062Process::GetBreakpointSiteList()
2063{
2064 return m_breakpoint_site_list;
2065}
2066
2067const BreakpointSiteList &
2068Process::GetBreakpointSiteList() const
2069{
2070 return m_breakpoint_site_list;
2071}
2072
2073
2074void
2075Process::DisableAllBreakpointSites ()
2076{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002077 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2078// bp_site->SetEnabled(true);
2079 DisableBreakpointSite(bp_site);
2080 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081}
2082
2083Error
2084Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2085{
2086 Error error (DisableBreakpointSiteByID (break_id));
2087
2088 if (error.Success())
2089 m_breakpoint_site_list.Remove(break_id);
2090
2091 return error;
2092}
2093
2094Error
2095Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2096{
2097 Error error;
2098 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2099 if (bp_site_sp)
2100 {
2101 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002102 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103 }
2104 else
2105 {
Daniel Malead01b2952012-11-29 21:49:15 +00002106 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107 }
2108
2109 return error;
2110}
2111
2112Error
2113Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2114{
2115 Error error;
2116 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2117 if (bp_site_sp)
2118 {
2119 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002120 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121 }
2122 else
2123 {
Daniel Malead01b2952012-11-29 21:49:15 +00002124 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 }
2126 return error;
2127}
2128
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002129lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002130Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002131{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002132 addr_t load_addr = LLDB_INVALID_ADDRESS;
2133
2134 bool show_error = true;
2135 switch (GetState())
2136 {
2137 case eStateInvalid:
2138 case eStateUnloaded:
2139 case eStateConnected:
2140 case eStateAttaching:
2141 case eStateLaunching:
2142 case eStateDetached:
2143 case eStateExited:
2144 show_error = false;
2145 break;
2146
2147 case eStateStopped:
2148 case eStateRunning:
2149 case eStateStepping:
2150 case eStateCrashed:
2151 case eStateSuspended:
2152 show_error = IsAlive();
2153 break;
2154 }
2155
2156 // Reset the IsIndirect flag here, in case the location changes from
2157 // pointing to a indirect symbol to a regular symbol.
2158 owner->SetIsIndirect (false);
2159
2160 if (owner->ShouldResolveIndirectFunctions())
2161 {
2162 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2163 if (symbol && symbol->IsIndirect())
2164 {
2165 Error error;
2166 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2167 if (!error.Success() && show_error)
2168 {
Greg Clayton44d93782014-01-27 23:43:24 +00002169 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2170 symbol->GetAddress().GetLoadAddress(&m_target),
2171 owner->GetBreakpoint().GetID(),
2172 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002173 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002174 return LLDB_INVALID_BREAK_ID;
2175 }
2176 Address resolved_address(load_addr);
2177 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2178 owner->SetIsIndirect(true);
2179 }
2180 else
2181 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2182 }
2183 else
2184 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2185
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002186 if (load_addr != LLDB_INVALID_ADDRESS)
2187 {
2188 BreakpointSiteSP bp_site_sp;
2189
2190 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2191 // create a new breakpoint site and add it.
2192
2193 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2194
2195 if (bp_site_sp)
2196 {
2197 bp_site_sp->AddOwner (owner);
2198 owner->SetBreakpointSite (bp_site_sp);
2199 return bp_site_sp->GetID();
2200 }
2201 else
2202 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002203 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204 if (bp_site_sp)
2205 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002206 Error error = EnableBreakpointSite (bp_site_sp.get());
2207 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002208 {
2209 owner->SetBreakpointSite (bp_site_sp);
2210 return m_breakpoint_site_list.Add (bp_site_sp);
2211 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002212 else
2213 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002214 if (show_error)
2215 {
2216 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002217 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2218 load_addr,
2219 owner->GetBreakpoint().GetID(),
2220 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002221 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002222 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002223 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224 }
2225 }
2226 }
2227 // We failed to enable the breakpoint
2228 return LLDB_INVALID_BREAK_ID;
2229
2230}
2231
2232void
2233Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2234{
2235 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2236 if (num_owners == 0)
2237 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002238 // Don't try to disable the site if we don't have a live process anymore.
2239 if (IsAlive())
2240 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2242 }
2243}
2244
2245
2246size_t
2247Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2248{
2249 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002250 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251
Jim Ingham20c77192011-06-29 19:42:28 +00002252 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002253 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002254 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2255 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002256 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002257 addr_t intersect_addr;
2258 size_t intersect_size;
2259 size_t opcode_offset;
2260 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002261 {
2262 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2263 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002264 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002265 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002266 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002267 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002269 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270 }
2271 return bytes_removed;
2272}
2273
2274
Greg Claytonded470d2011-03-19 01:12:21 +00002275
2276size_t
2277Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2278{
2279 PlatformSP platform_sp (m_target.GetPlatform());
2280 if (platform_sp)
2281 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2282 return 0;
2283}
2284
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285Error
2286Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2287{
2288 Error error;
2289 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002290 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291 const addr_t bp_addr = bp_site->GetLoadAddress();
2292 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002293 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002294 if (bp_site->IsEnabled())
2295 {
2296 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002297 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 +00002298 return error;
2299 }
2300
2301 if (bp_addr == LLDB_INVALID_ADDRESS)
2302 {
2303 error.SetErrorString("BreakpointSite contains an invalid load address.");
2304 return error;
2305 }
2306 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2307 // trap for the breakpoint site
2308 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2309
2310 if (bp_opcode_size == 0)
2311 {
Daniel Malead01b2952012-11-29 21:49:15 +00002312 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 }
2314 else
2315 {
2316 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2317
2318 if (bp_opcode_bytes == NULL)
2319 {
2320 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2321 return error;
2322 }
2323
2324 // Save the original opcode by reading it
2325 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2326 {
2327 // Write a software breakpoint in place of the original opcode
2328 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2329 {
2330 uint8_t verify_bp_opcode_bytes[64];
2331 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2332 {
2333 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2334 {
2335 bp_site->SetEnabled(true);
2336 bp_site->SetType (BreakpointSite::eSoftware);
2337 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002338 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 bp_site->GetID(),
2340 (uint64_t)bp_addr);
2341 }
2342 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002343 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 }
2345 else
2346 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2347 }
2348 else
2349 error.SetErrorString("Unable to write breakpoint trap to memory.");
2350 }
2351 else
2352 error.SetErrorString("Unable to read memory at breakpoint address.");
2353 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002354 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002355 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 bp_site->GetID(),
2357 (uint64_t)bp_addr,
2358 error.AsCString());
2359 return error;
2360}
2361
2362Error
2363Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2364{
2365 Error error;
2366 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002367 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002368 addr_t bp_addr = bp_site->GetLoadAddress();
2369 lldb::user_id_t breakID = bp_site->GetID();
2370 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002371 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372
2373 if (bp_site->IsHardware())
2374 {
2375 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2376 }
2377 else if (bp_site->IsEnabled())
2378 {
2379 const size_t break_op_size = bp_site->GetByteSize();
2380 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2381 if (break_op_size > 0)
2382 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002383 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002384 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002385 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 bool break_op_found = false;
2387
2388 // Read the breakpoint opcode
2389 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2390 {
2391 bool verify = false;
2392 // Make sure we have the a breakpoint opcode exists at this address
2393 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2394 {
2395 break_op_found = true;
2396 // We found a valid breakpoint opcode at this address, now restore
2397 // the saved opcode.
2398 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2399 {
2400 verify = true;
2401 }
2402 else
2403 error.SetErrorString("Memory write failed when restoring original opcode.");
2404 }
2405 else
2406 {
2407 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2408 // Set verify to true and so we can check if the original opcode has already been restored
2409 verify = true;
2410 }
2411
2412 if (verify)
2413 {
Greg Claytonc982c762010-07-09 20:39:50 +00002414 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002415 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416 // Verify that our original opcode made it back to the inferior
2417 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2418 {
2419 // compare the memory we just read with the original opcode
2420 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2421 {
2422 // SUCCESS
2423 bp_site->SetEnabled(false);
2424 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002425 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 +00002426 return error;
2427 }
2428 else
2429 {
2430 if (break_op_found)
2431 error.SetErrorString("Failed to restore original opcode.");
2432 }
2433 }
2434 else
2435 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2436 }
2437 }
2438 else
2439 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2440 }
2441 }
2442 else
2443 {
2444 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002445 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 +00002446 return error;
2447 }
2448
2449 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002450 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 bp_site->GetID(),
2452 (uint64_t)bp_addr,
2453 error.AsCString());
2454 return error;
2455
2456}
2457
Greg Clayton58be07b2011-01-07 06:08:19 +00002458// Uncomment to verify memory caching works after making changes to caching code
2459//#define VERIFY_MEMORY_READS
2460
Sean Callanan64c0cf22012-06-07 22:26:42 +00002461size_t
2462Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2463{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002464 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002465 if (!GetDisableMemoryCache())
2466 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002467#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002468 // Memory caching is enabled, with debug verification
2469
2470 if (buf && size)
2471 {
2472 // Uncomment the line below to make sure memory caching is working.
2473 // I ran this through the test suite and got no assertions, so I am
2474 // pretty confident this is working well. If any changes are made to
2475 // memory caching, uncomment the line below and test your changes!
2476
2477 // Verify all memory reads by using the cache first, then redundantly
2478 // reading the same memory from the inferior and comparing to make sure
2479 // everything is exactly the same.
2480 std::string verify_buf (size, '\0');
2481 assert (verify_buf.size() == size);
2482 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2483 Error verify_error;
2484 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2485 assert (cache_bytes_read == verify_bytes_read);
2486 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2487 assert (verify_error.Success() == error.Success());
2488 return cache_bytes_read;
2489 }
2490 return 0;
2491#else // !defined(VERIFY_MEMORY_READS)
2492 // Memory caching is enabled, without debug verification
2493
2494 return m_memory_cache.Read (addr, buf, size, error);
2495#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002496 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002497 else
2498 {
2499 // Memory caching is disabled
2500
2501 return ReadMemoryFromInferior (addr, buf, size, error);
2502 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002503}
Greg Clayton58be07b2011-01-07 06:08:19 +00002504
Greg Clayton4c82d422012-05-18 23:20:01 +00002505size_t
2506Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2507{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002508 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002509 out_str.clear();
2510 addr_t curr_addr = addr;
2511 while (1)
2512 {
2513 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2514 if (length == 0)
2515 break;
2516 out_str.append(buf, length);
2517 // If we got "length - 1" bytes, we didn't get the whole C string, we
2518 // need to read some more characters
2519 if (length == sizeof(buf) - 1)
2520 curr_addr += length;
2521 else
2522 break;
2523 }
2524 return out_str.size();
2525}
2526
Greg Clayton58be07b2011-01-07 06:08:19 +00002527
2528size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002529Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2530 size_t type_width)
2531{
2532 size_t total_bytes_read = 0;
2533 if (dst && max_bytes && type_width && max_bytes >= type_width)
2534 {
2535 // Ensure a null terminator independent of the number of bytes that is read.
2536 memset (dst, 0, max_bytes);
2537 size_t bytes_left = max_bytes - type_width;
2538
2539 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2540 assert(sizeof(terminator) >= type_width &&
2541 "Attempting to validate a string with more than 4 bytes per character!");
2542
2543 addr_t curr_addr = addr;
2544 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2545 char *curr_dst = dst;
2546
2547 error.Clear();
2548 while (bytes_left > 0 && error.Success())
2549 {
2550 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2551 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2552 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2553
2554 if (bytes_read == 0)
2555 break;
2556
2557 // Search for a null terminator of correct size and alignment in bytes_read
2558 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2559 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2560 if (::strncmp(&dst[i], terminator, type_width) == 0)
2561 {
2562 error.Clear();
2563 return i;
2564 }
2565
2566 total_bytes_read += bytes_read;
2567 curr_dst += bytes_read;
2568 curr_addr += bytes_read;
2569 bytes_left -= bytes_read;
2570 }
2571 }
2572 else
2573 {
2574 if (max_bytes)
2575 error.SetErrorString("invalid arguments");
2576 }
2577 return total_bytes_read;
2578}
2579
2580// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2581// null terminators.
2582size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002583Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002584{
2585 size_t total_cstr_len = 0;
2586 if (dst && dst_max_len)
2587 {
Greg Claytone91b7952011-12-15 03:14:23 +00002588 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002589 // NULL out everything just to be safe
2590 memset (dst, 0, dst_max_len);
2591 Error error;
2592 addr_t curr_addr = addr;
2593 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2594 size_t bytes_left = dst_max_len - 1;
2595 char *curr_dst = dst;
2596
2597 while (bytes_left > 0)
2598 {
2599 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2600 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2601 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2602
2603 if (bytes_read == 0)
2604 {
Greg Claytone91b7952011-12-15 03:14:23 +00002605 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002606 dst[total_cstr_len] = '\0';
2607 break;
2608 }
2609 const size_t len = strlen(curr_dst);
2610
2611 total_cstr_len += len;
2612
2613 if (len < bytes_to_read)
2614 break;
2615
2616 curr_dst += bytes_read;
2617 curr_addr += bytes_read;
2618 bytes_left -= bytes_read;
2619 }
2620 }
Greg Claytone91b7952011-12-15 03:14:23 +00002621 else
2622 {
2623 if (dst == NULL)
2624 result_error.SetErrorString("invalid arguments");
2625 else
2626 result_error.Clear();
2627 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002628 return total_cstr_len;
2629}
2630
2631size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002632Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2633{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634 if (buf == NULL || size == 0)
2635 return 0;
2636
2637 size_t bytes_read = 0;
2638 uint8_t *bytes = (uint8_t *)buf;
2639
2640 while (bytes_read < size)
2641 {
2642 const size_t curr_size = size - bytes_read;
2643 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2644 bytes + bytes_read,
2645 curr_size,
2646 error);
2647 bytes_read += curr_bytes_read;
2648 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2649 break;
2650 }
2651
2652 // Replace any software breakpoint opcodes that fall into this range back
2653 // into "buf" before we return
2654 if (bytes_read > 0)
2655 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2656 return bytes_read;
2657}
2658
Greg Clayton58a4c462010-12-16 20:01:20 +00002659uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002660Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002661{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002662 Scalar scalar;
2663 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2664 return scalar.ULongLong(fail_value);
2665 return fail_value;
2666}
2667
2668addr_t
2669Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2670{
2671 Scalar scalar;
2672 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2673 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2674 return LLDB_INVALID_ADDRESS;
2675}
2676
2677
2678bool
2679Process::WritePointerToMemory (lldb::addr_t vm_addr,
2680 lldb::addr_t ptr_value,
2681 Error &error)
2682{
2683 Scalar scalar;
2684 const uint32_t addr_byte_size = GetAddressByteSize();
2685 if (addr_byte_size <= 4)
2686 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002687 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002688 scalar = ptr_value;
2689 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002690}
2691
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002692size_t
2693Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2694{
2695 size_t bytes_written = 0;
2696 const uint8_t *bytes = (const uint8_t *)buf;
2697
2698 while (bytes_written < size)
2699 {
2700 const size_t curr_size = size - bytes_written;
2701 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2702 bytes + bytes_written,
2703 curr_size,
2704 error);
2705 bytes_written += curr_bytes_written;
2706 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2707 break;
2708 }
2709 return bytes_written;
2710}
2711
2712size_t
2713Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2714{
Greg Clayton58be07b2011-01-07 06:08:19 +00002715#if defined (ENABLE_MEMORY_CACHING)
2716 m_memory_cache.Flush (addr, size);
2717#endif
2718
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719 if (buf == NULL || size == 0)
2720 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002721
Jim Ingham4b536182011-08-09 02:12:22 +00002722 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002723
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724 // We need to write any data that would go where any current software traps
2725 // (enabled software breakpoints) any software traps (breakpoints) that we
2726 // may have placed in our tasks memory.
2727
Greg Claytond8cf1a12013-06-12 00:46:38 +00002728 BreakpointSiteList bp_sites_in_range;
2729
2730 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002732 // No breakpoint sites overlap
2733 if (bp_sites_in_range.IsEmpty())
2734 return WriteMemoryPrivate (addr, buf, size, error);
2735 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002737 const uint8_t *ubuf = (const uint8_t *)buf;
2738 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739
Greg Claytond8cf1a12013-06-12 00:46:38 +00002740 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2741
2742 if (error.Success())
2743 {
2744 addr_t intersect_addr;
2745 size_t intersect_size;
2746 size_t opcode_offset;
2747 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2748 assert(intersects);
2749 assert(addr <= intersect_addr && intersect_addr < addr + size);
2750 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2751 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2752
2753 // Check for bytes before this breakpoint
2754 const addr_t curr_addr = addr + bytes_written;
2755 if (intersect_addr > curr_addr)
2756 {
2757 // There are some bytes before this breakpoint that we need to
2758 // just write to memory
2759 size_t curr_size = intersect_addr - curr_addr;
2760 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2761 ubuf + bytes_written,
2762 curr_size,
2763 error);
2764 bytes_written += curr_bytes_written;
2765 if (curr_bytes_written != curr_size)
2766 {
2767 // We weren't able to write all of the requested bytes, we
2768 // are done looping and will return the number of bytes that
2769 // we have written so far.
2770 if (error.Success())
2771 error.SetErrorToGenericError();
2772 }
2773 }
2774 // Now write any bytes that would cover up any software breakpoints
2775 // directly into the breakpoint opcode buffer
2776 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2777 bytes_written += intersect_size;
2778 }
2779 });
2780
2781 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002782 WriteMemoryPrivate (addr + bytes_written,
2783 ubuf + bytes_written,
2784 size - bytes_written,
2785 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002786 }
2787 }
2788 else
2789 {
2790 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002791 }
2792
2793 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002794 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002796
2797size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002798Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002799{
2800 if (byte_size == UINT32_MAX)
2801 byte_size = scalar.GetByteSize();
2802 if (byte_size > 0)
2803 {
2804 uint8_t buf[32];
2805 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2806 if (mem_size > 0)
2807 return WriteMemory(addr, buf, mem_size, error);
2808 else
2809 error.SetErrorString ("failed to get scalar as memory data");
2810 }
2811 else
2812 {
2813 error.SetErrorString ("invalid scalar value");
2814 }
2815 return 0;
2816}
2817
2818size_t
2819Process::ReadScalarIntegerFromMemory (addr_t addr,
2820 uint32_t byte_size,
2821 bool is_signed,
2822 Scalar &scalar,
2823 Error &error)
2824{
Greg Clayton7060f892013-05-01 23:41:30 +00002825 uint64_t uval = 0;
2826 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002827 {
Greg Clayton7060f892013-05-01 23:41:30 +00002828 error.SetErrorString ("byte size is zero");
2829 }
2830 else if (byte_size & (byte_size - 1))
2831 {
2832 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2833 }
2834 else if (byte_size <= sizeof(uval))
2835 {
2836 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002837 if (bytes_read == byte_size)
2838 {
2839 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002840 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002841 if (byte_size <= 4)
2842 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002843 else
Greg Clayton7060f892013-05-01 23:41:30 +00002844 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002845 if (is_signed)
2846 scalar.SignExtend(byte_size * 8);
2847 return bytes_read;
2848 }
2849 }
2850 else
2851 {
2852 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2853 }
2854 return 0;
2855}
2856
Greg Claytond495c532011-05-17 03:37:42 +00002857#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002858addr_t
2859Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2860{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002861 if (GetPrivateState() != eStateStopped)
2862 return LLDB_INVALID_ADDRESS;
2863
Greg Claytond495c532011-05-17 03:37:42 +00002864#if defined (USE_ALLOCATE_MEMORY_CACHE)
2865 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2866#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002867 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002868 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002869 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002870 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 +00002871 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002872 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002873 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002874 m_mod_id.GetStopID(),
2875 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002876 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002877#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878}
2879
Sean Callanan90539452011-09-20 23:01:51 +00002880bool
2881Process::CanJIT ()
2882{
Sean Callanana7b443a2012-02-14 22:50:38 +00002883 if (m_can_jit == eCanJITDontKnow)
2884 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002885 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002886 Error err;
2887
2888 uint64_t allocated_memory = AllocateMemory(8,
2889 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2890 err);
2891
2892 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002893 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002894 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002895 if (log)
2896 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2897 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002898 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002899 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002900 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002901 if (log)
2902 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2903 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002904
2905 DeallocateMemory (allocated_memory);
2906 }
2907
Sean Callanan90539452011-09-20 23:01:51 +00002908 return m_can_jit == eCanJITYes;
2909}
2910
2911void
2912Process::SetCanJIT (bool can_jit)
2913{
2914 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2915}
2916
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002917Error
2918Process::DeallocateMemory (addr_t ptr)
2919{
Greg Claytond495c532011-05-17 03:37:42 +00002920 Error error;
2921#if defined (USE_ALLOCATE_MEMORY_CACHE)
2922 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2923 {
Daniel Malead01b2952012-11-29 21:49:15 +00002924 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002925 }
2926#else
2927 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002928
Greg Clayton5160ce52013-03-27 23:08:40 +00002929 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002930 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002931 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 +00002932 ptr,
2933 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002934 m_mod_id.GetStopID(),
2935 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002936#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002937 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002938}
2939
Han Ming Ongc811d382012-11-17 00:33:14 +00002940
Greg Claytonc9660542012-02-05 02:38:54 +00002941ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002942Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002943 lldb::addr_t header_addr,
2944 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002945{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002946 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002947 if (module_sp)
2948 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002949 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002950 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002951 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002952 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002953 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002954 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002955}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002956
2957Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002958Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002959{
2960 Error error;
2961 error.SetErrorString("watchpoints are not supported");
2962 return error;
2963}
2964
2965Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002966Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002967{
2968 Error error;
2969 error.SetErrorString("watchpoints are not supported");
2970 return error;
2971}
2972
2973StateType
2974Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2975{
2976 StateType state;
2977 // Now wait for the process to launch and return control to us, and then
2978 // call DidLaunch:
2979 while (1)
2980 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002981 event_sp.reset();
2982 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2983
Greg Clayton2637f822011-11-17 01:23:07 +00002984 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002985 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002986
2987 // If state is invalid, then we timed out
2988 if (state == eStateInvalid)
2989 break;
2990
2991 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992 HandlePrivateEvent (event_sp);
2993 }
2994 return state;
2995}
2996
2997Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002998Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999{
3000 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003002 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003003 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003004 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003005 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003006 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003007 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008
Greg Claytonaa149cb2011-08-11 02:48:45 +00003009 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003010 if (exe_module)
3011 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003012 char local_exec_file_path[PATH_MAX];
3013 char platform_exec_file_path[PATH_MAX];
3014 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3015 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 if (exe_module->GetFileSpec().Exists())
3017 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003018 // Install anything that might need to be installed prior to launching.
3019 // For host systems, this will do nothing, but if we are connected to a
3020 // remote platform it will install any needed binaries
3021 error = GetTarget().Install(&launch_info);
3022 if (error.Fail())
3023 return error;
3024
Greg Clayton71337622011-02-24 22:24:29 +00003025 if (PrivateStateThreadIsValid ())
3026 PausePrivateStateThread ();
3027
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003028 error = WillLaunch (exe_module);
3029 if (error.Success())
3030 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003031 const bool restarted = false;
3032 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003033 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034
Ed Maste64fad602013-07-29 20:58:06 +00003035 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003036 {
3037 // Now launch using these arguments.
3038 error = DoLaunch (exe_module, launch_info);
3039 }
3040 else
3041 {
3042 // This shouldn't happen
3043 error.SetErrorString("failed to acquire process run lock");
3044 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045
3046 if (error.Fail())
3047 {
3048 if (GetID() != LLDB_INVALID_PROCESS_ID)
3049 {
3050 SetID (LLDB_INVALID_PROCESS_ID);
3051 const char *error_string = error.AsCString();
3052 if (error_string == NULL)
3053 error_string = "launch failed";
3054 SetExitStatus (-1, error_string);
3055 }
3056 }
3057 else
3058 {
3059 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003060 TimeValue timeout_time;
3061 timeout_time = TimeValue::Now();
3062 timeout_time.OffsetWithSeconds(10);
3063 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003064
Greg Clayton1a38ea72011-06-22 01:42:17 +00003065 if (state == eStateInvalid || event_sp.get() == NULL)
3066 {
3067 // We were able to launch the process, but we failed to
3068 // catch the initial stop.
3069 SetExitStatus (0, "failed to catch stop after launch");
3070 Destroy();
3071 }
3072 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075 DidLaunch ();
3076
Greg Claytonc859e2d2012-02-13 23:10:39 +00003077 DynamicLoader *dyld = GetDynamicLoader ();
3078 if (dyld)
3079 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003080
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003081 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003082
Jason Molendaeef51062013-11-05 03:57:19 +00003083 SystemRuntime *system_runtime = GetSystemRuntime ();
3084 if (system_runtime)
3085 system_runtime->DidLaunch();
3086
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003087 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Todd Fialaf72fa672014-10-07 16:05:21 +00003088
3089 // Note, the stop event was consumed above, but not handled. This was done
3090 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3091 // Directly set the state. This is done to prevent a stop message with a bunch
3092 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3093 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003094
3095 if (PrivateStateThreadIsValid ())
3096 ResumePrivateStateThread ();
3097 else
3098 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003099
3100 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101 }
3102 else if (state == eStateExited)
3103 {
3104 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3105 // not likely to work, and return an invalid pid.
3106 HandlePrivateEvent (event_sp);
3107 }
3108 }
3109 }
3110 }
3111 else
3112 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003113 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003114 }
3115 }
3116 return error;
3117}
3118
Greg Claytonc3776bf2012-02-09 06:16:32 +00003119
3120Error
3121Process::LoadCore ()
3122{
3123 Error error = DoLoadCore();
3124 if (error.Success())
3125 {
3126 if (PrivateStateThreadIsValid ())
3127 ResumePrivateStateThread ();
3128 else
3129 StartPrivateStateThread ();
3130
Greg Claytonc859e2d2012-02-13 23:10:39 +00003131 DynamicLoader *dyld = GetDynamicLoader ();
3132 if (dyld)
3133 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003134
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003135 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003136
Jason Molendaeef51062013-11-05 03:57:19 +00003137 SystemRuntime *system_runtime = GetSystemRuntime ();
3138 if (system_runtime)
3139 system_runtime->DidAttach();
3140
Greg Claytonc859e2d2012-02-13 23:10:39 +00003141 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003142 // We successfully loaded a core file, now pretend we stopped so we can
3143 // show all of the threads in the core file and explore the crashed
3144 // state.
3145 SetPrivateState (eStateStopped);
3146
3147 }
3148 return error;
3149}
3150
Greg Claytonc859e2d2012-02-13 23:10:39 +00003151DynamicLoader *
3152Process::GetDynamicLoader ()
3153{
3154 if (m_dyld_ap.get() == NULL)
3155 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3156 return m_dyld_ap.get();
3157}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003158
Todd Fialaaf245d12014-06-30 21:05:18 +00003159const lldb::DataBufferSP
3160Process::GetAuxvData()
3161{
3162 return DataBufferSP ();
3163}
3164
Andrew MacPherson17220c12014-03-05 10:12:43 +00003165JITLoaderList &
3166Process::GetJITLoaders ()
3167{
3168 if (!m_jit_loaders_ap)
3169 {
3170 m_jit_loaders_ap.reset(new JITLoaderList());
3171 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3172 }
3173 return *m_jit_loaders_ap;
3174}
3175
Jason Molendaeef51062013-11-05 03:57:19 +00003176SystemRuntime *
3177Process::GetSystemRuntime ()
3178{
3179 if (m_system_runtime_ap.get() == NULL)
3180 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3181 return m_system_runtime_ap.get();
3182}
3183
Todd Fiala76e0fc92014-08-27 22:58:26 +00003184Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3185 NextEventAction (process),
3186 m_exec_count (exec_count)
3187{
3188 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3189 if (log)
3190 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3191}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003192
Jim Inghambb3a2832011-01-29 01:49:25 +00003193Process::NextEventAction::EventActionResult
3194Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003196 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3197
Jim Inghambb3a2832011-01-29 01:49:25 +00003198 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003199 if (log)
3200 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3201
3202 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003203 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003204 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003205 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003206 return eEventActionRetry;
3207
3208 case eStateStopped:
3209 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003210 {
3211 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003212 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003213 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003214 // We don't want these events to be reported, so go set the ShouldReportStop here:
3215 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3216
Greg Claytonc9ed4782011-11-12 02:10:56 +00003217 if (m_exec_count > 0)
3218 {
3219 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003220
3221 if (log)
3222 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3223
Jim Ingham221d51c2013-05-08 00:35:16 +00003224 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003225 return eEventActionRetry;
3226 }
3227 else
3228 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003229 if (log)
3230 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3231
Greg Claytonc9ed4782011-11-12 02:10:56 +00003232 m_process->CompleteAttach ();
3233 return eEventActionSuccess;
3234 }
3235 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003236 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003237
Greg Clayton513c26c2011-01-29 07:10:55 +00003238 default:
3239 case eStateExited:
3240 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003241 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003242 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003243
3244 m_exit_string.assign ("No valid Process");
3245 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003246}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003247
Jim Inghambb3a2832011-01-29 01:49:25 +00003248Process::NextEventAction::EventActionResult
3249Process::AttachCompletionHandler::HandleBeingInterrupted()
3250{
3251 return eEventActionSuccess;
3252}
3253
3254const char *
3255Process::AttachCompletionHandler::GetExitString ()
3256{
3257 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258}
3259
Greg Clayton8012cad2014-11-17 19:39:20 +00003260Listener &
3261ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3262{
3263 if (m_listener_sp)
3264 return *m_listener_sp;
3265 else
3266 return debugger.GetListener();
3267}
3268
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003269Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003270Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003271{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003273 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003274 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003275 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003276 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003277 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003278 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003279
Greg Clayton144f3a92011-11-15 03:53:30 +00003280 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003281 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003282 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003283 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003284 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003285
Greg Clayton144f3a92011-11-15 03:53:30 +00003286 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003287 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003288 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3289
3290 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003292 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3293 if (error.Success())
3294 {
Ed Maste64fad602013-07-29 20:58:06 +00003295 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003296 {
3297 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003298 const bool restarted = false;
3299 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003300 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003301 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003302 }
3303 else
3304 {
3305 // This shouldn't happen
3306 error.SetErrorString("failed to acquire process run lock");
3307 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003308
Greg Clayton144f3a92011-11-15 03:53:30 +00003309 if (error.Fail())
3310 {
3311 if (GetID() != LLDB_INVALID_PROCESS_ID)
3312 {
3313 SetID (LLDB_INVALID_PROCESS_ID);
3314 if (error.AsCString() == NULL)
3315 error.SetErrorString("attach failed");
3316
3317 SetExitStatus(-1, error.AsCString());
3318 }
3319 }
3320 else
3321 {
3322 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3323 StartPrivateStateThread();
3324 }
3325 return error;
3326 }
Greg Claytone996fd32011-03-08 22:40:15 +00003327 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003328 else
Greg Claytone996fd32011-03-08 22:40:15 +00003329 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003330 ProcessInstanceInfoList process_infos;
3331 PlatformSP platform_sp (m_target.GetPlatform ());
3332
3333 if (platform_sp)
3334 {
3335 ProcessInstanceInfoMatch match_info;
3336 match_info.GetProcessInfo() = attach_info;
3337 match_info.SetNameMatchType (eNameMatchEquals);
3338 platform_sp->FindProcesses (match_info, process_infos);
3339 const uint32_t num_matches = process_infos.GetSize();
3340 if (num_matches == 1)
3341 {
3342 attach_pid = process_infos.GetProcessIDAtIndex(0);
3343 // Fall through and attach using the above process ID
3344 }
3345 else
3346 {
3347 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3348 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003349 {
3350 StreamString s;
3351 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3352 for (size_t i = 0; i < num_matches; i++)
3353 {
3354 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3355 }
3356 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3357 process_name,
3358 s.GetData());
3359 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003360 else
3361 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3362 }
3363 }
3364 else
3365 {
3366 error.SetErrorString ("invalid platform, can't find processes by name");
3367 return error;
3368 }
Greg Claytone996fd32011-03-08 22:40:15 +00003369 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 }
3371 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003372 {
3373 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003374 }
3375 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003376
3377 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003378 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003379 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003380 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003381 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003382
Ed Maste64fad602013-07-29 20:58:06 +00003383 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003384 {
3385 // Now attach using these arguments.
3386 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003387 const bool restarted = false;
3388 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003389 error = DoAttachToProcessWithID (attach_pid, attach_info);
3390 }
3391 else
3392 {
3393 // This shouldn't happen
3394 error.SetErrorString("failed to acquire process run lock");
3395 }
3396
Greg Clayton144f3a92011-11-15 03:53:30 +00003397 if (error.Success())
3398 {
3399
3400 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3401 StartPrivateStateThread();
3402 }
3403 else
Greg Claytone996fd32011-03-08 22:40:15 +00003404 {
3405 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003406 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003407
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003408 const char *error_string = error.AsCString();
3409 if (error_string == NULL)
3410 error_string = "attach failed";
3411
3412 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003413 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003414 }
3415 }
3416 return error;
3417}
3418
Greg Clayton93d3c8332011-02-16 04:46:07 +00003419void
3420Process::CompleteAttach ()
3421{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003422 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3423 if (log)
3424 log->Printf ("Process::%s()", __FUNCTION__);
3425
Greg Clayton93d3c8332011-02-16 04:46:07 +00003426 // Let the process subclass figure out at much as it can about the process
3427 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003428 ArchSpec process_arch;
3429 DidAttach(process_arch);
3430
3431 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003432 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003433 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003434 if (log)
3435 {
3436 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3437 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3438 __FUNCTION__,
3439 triple_str ? triple_str : "<null>");
3440 }
3441 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003442
Jim Ingham4299fdb2011-09-15 01:10:17 +00003443 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3444 // the same as the one we've already set, switch architectures.
3445 PlatformSP platform_sp (m_target.GetPlatform ());
3446 assert (platform_sp.get());
3447 if (platform_sp)
3448 {
Greg Clayton70512312012-05-08 01:45:38 +00003449 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003450 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003451 {
3452 ArchSpec platform_arch;
3453 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3454 if (platform_sp)
3455 {
3456 m_target.SetPlatform (platform_sp);
3457 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003458 if (log)
3459 log->Printf ("Process::%s switching platform to %s and architecture to %s based on info from attach", __FUNCTION__, platform_sp->GetName().AsCString (""), platform_arch.GetTriple().getTriple().c_str ());
Greg Clayton70512312012-05-08 01:45:38 +00003460 }
3461 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003462 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003463 {
3464 ProcessInstanceInfo process_info;
3465 platform_sp->GetProcessInfo (GetID(), process_info);
3466 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003467 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003468 {
Greg Clayton70512312012-05-08 01:45:38 +00003469 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003470 if (log)
3471 log->Printf ("Process::%s switching architecture to %s based on info the platform retrieved for pid %" PRIu64, __FUNCTION__, process_arch.GetTriple().getTriple().c_str (), GetID ());
3472 }
Greg Clayton70512312012-05-08 01:45:38 +00003473 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003474 }
3475
3476 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003477 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003478 DynamicLoader *dyld = GetDynamicLoader ();
3479 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003480 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003481 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003482 if (log)
3483 {
3484 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3485 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3486 __FUNCTION__,
3487 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3488 dyld->GetPluginName().AsCString ("<unnamed>"));
3489 }
3490 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003491
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003492 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003493
Jason Molendaeef51062013-11-05 03:57:19 +00003494 SystemRuntime *system_runtime = GetSystemRuntime ();
3495 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003496 {
Jason Molendaeef51062013-11-05 03:57:19 +00003497 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003498 if (log)
3499 {
3500 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3501 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3502 __FUNCTION__,
3503 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3504 system_runtime->GetPluginName().AsCString("<unnamed>"));
3505 }
3506 }
Jason Molendaeef51062013-11-05 03:57:19 +00003507
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003508 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003509 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003510 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003511 Mutex::Locker modules_locker(target_modules.GetMutex());
3512 size_t num_modules = target_modules.GetSize();
3513 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003514
Andy Gibbsa297a972013-06-19 19:04:53 +00003515 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003516 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003517 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003518 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003519 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003520 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003521 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003522 break;
3523 }
3524 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003525 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003526 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003527 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003528 if (log)
3529 {
3530 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3531 log->Printf ("Process::%s after looping through modules, target executable is %s",
3532 __FUNCTION__,
3533 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3534 }
3535 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003536
3537 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003538}
3539
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003541Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003542{
Greg Claytonb766a732011-02-04 01:58:07 +00003543 m_abi_sp.reset();
3544 m_process_input_reader.reset();
3545
3546 // Find the process and its architecture. Make sure it matches the architecture
3547 // of the current Target, and if not adjust it.
3548
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003549 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003550 if (error.Success())
3551 {
Greg Clayton71337622011-02-24 22:24:29 +00003552 if (GetID() != LLDB_INVALID_PROCESS_ID)
3553 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003554 EventSP event_sp;
3555 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3556
3557 if (state == eStateStopped || state == eStateCrashed)
3558 {
3559 // If we attached and actually have a process on the other end, then
3560 // this ended up being the equivalent of an attach.
3561 CompleteAttach ();
3562
3563 // This delays passing the stopped event to listeners till
3564 // CompleteAttach gets a chance to complete...
3565 HandlePrivateEvent (event_sp);
3566
3567 }
Greg Clayton71337622011-02-24 22:24:29 +00003568 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003569
3570 if (PrivateStateThreadIsValid ())
3571 ResumePrivateStateThread ();
3572 else
3573 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003574 }
3575 return error;
3576}
3577
3578
3579Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003580Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003581{
Greg Clayton5160ce52013-03-27 23:08:40 +00003582 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003583 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003584 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003585 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003586 StateAsCString(m_public_state.GetValue()),
3587 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588
3589 Error error (WillResume());
3590 // Tell the process it is about to resume before the thread list
3591 if (error.Success())
3592 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003593 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003594 // can let all of our threads know that they are about to be
3595 // resumed. Threads will each be called with
3596 // Thread::WillResume(StateType) where StateType contains the state
3597 // that they are supposed to have when the process is resumed
3598 // (suspended/running/stepping). Threads should also check
3599 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003600 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003601 if (m_thread_list.WillResume())
3602 {
Jim Ingham372787f2012-04-07 00:00:41 +00003603 // Last thing, do the PreResumeActions.
3604 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003605 {
Jim Ingham0161b492013-02-09 01:29:05 +00003606 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003607 }
3608 else
3609 {
3610 m_mod_id.BumpResumeID();
3611 error = DoResume();
3612 if (error.Success())
3613 {
3614 DidResume();
3615 m_thread_list.DidResume();
3616 if (log)
3617 log->Printf ("Process thinks the process has resumed.");
3618 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003619 }
3620 }
3621 else
3622 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003623 // Somebody wanted to run without running. So generate a continue & a stopped event,
3624 // and let the world handle them.
3625 if (log)
3626 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3627
3628 SetPrivateState(eStateRunning);
3629 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003630 }
3631 }
Jim Ingham444586b2011-01-24 06:34:17 +00003632 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003633 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003634 return error;
3635}
3636
3637Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003638Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003639{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003640 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3641 // in case it was already set and some thread plan logic calls halt on its
3642 // own.
3643 m_clear_thread_plans_on_stop |= clear_thread_plans;
3644
Jim Inghamaacc3182012-06-06 00:29:30 +00003645 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3646 // we could just straightaway get another event. It just narrows the window...
3647 m_currently_handling_event.WaitForValueEqualTo(false);
3648
3649
Jim Inghambb3a2832011-01-29 01:49:25 +00003650 // Pause our private state thread so we can ensure no one else eats
3651 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003652 Listener halt_listener ("lldb.process.halt_listener");
3653 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003654
Jim Inghambb3a2832011-01-29 01:49:25 +00003655 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003656 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003657
Greg Clayton06357c92014-07-30 17:38:47 +00003658 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003659 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003660 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003661
Greg Clayton513c26c2011-01-29 07:10:55 +00003662 bool caused_stop = false;
3663
3664 // Ask the process subclass to actually halt our process
3665 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003667 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003668 if (m_public_state.GetValue() == eStateAttaching)
3669 {
Greg Clayton06357c92014-07-30 17:38:47 +00003670 // Don't hijack and eat the eStateExited as the code that was doing
3671 // the attach will be waiting for this event...
3672 RestorePrivateProcessEvents();
3673 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003674 SetExitStatus(SIGKILL, "Cancelled async attach.");
3675 Destroy ();
3676 }
3677 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003678 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003679 // If "caused_stop" is true, then DoHalt stopped the process. If
3680 // "caused_stop" is false, the process was already stopped.
3681 // If the DoHalt caused the process to stop, then we want to catch
3682 // this event and set the interrupted bool to true before we pass
3683 // this along so clients know that the process was interrupted by
3684 // a halt command.
3685 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003686 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003687 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003688 TimeValue timeout_time;
3689 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003690 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003691 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3692 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003693
Jim Ingham0f16e732011-02-08 05:20:59 +00003694 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003695 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003696 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003697 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003698 }
3699 else
3700 {
Greg Clayton2637f822011-11-17 01:23:07 +00003701 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003702 {
3703 // We caused the process to interrupt itself, so mark this
3704 // as such in the stop event so clients can tell an interrupted
3705 // process from a natural stop
3706 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3707 }
3708 else
3709 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003710 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003711 if (log)
3712 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3713 error.SetErrorString ("Did not get stopped event after halt.");
3714 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003715 }
3716 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003717 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003718 }
3719 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003721 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003722 if (!restored_process_events)
3723 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003724
3725 // Post any event we might have consumed. If all goes well, we will have
3726 // stopped the process, intercepted the event and set the interrupted
3727 // bool in the event. Post it to the private event queue and that will end up
3728 // correctly setting the state.
3729 if (event_sp)
3730 m_private_state_broadcaster.BroadcastEvent(event_sp);
3731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732 return error;
3733}
3734
3735Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003736Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3737{
3738 Error error;
3739 if (m_public_state.GetValue() == eStateRunning)
3740 {
3741 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3742 if (log)
3743 log->Printf("Process::Destroy() About to halt.");
3744 error = Halt();
3745 if (error.Success())
3746 {
3747 // Consume the halt event.
3748 TimeValue timeout (TimeValue::Now());
3749 timeout.OffsetWithSeconds(1);
3750 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3751
3752 // If the process exited while we were waiting for it to stop, put the exited event into
3753 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3754 // they don't have a process anymore...
3755
3756 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3757 {
3758 if (log)
3759 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3760 return error;
3761 }
3762 else
3763 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3764
3765 if (state != eStateStopped)
3766 {
3767 if (log)
3768 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3769 // If we really couldn't stop the process then we should just error out here, but if the
3770 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3771 StateType private_state = m_private_state.GetValue();
3772 if (private_state != eStateStopped)
3773 {
3774 return error;
3775 }
3776 }
3777 }
3778 else
3779 {
3780 if (log)
3781 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3782 }
3783 }
3784 return error;
3785}
3786
3787Error
Jim Inghamacff8952013-05-02 00:27:30 +00003788Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003790 EventSP exit_event_sp;
3791 Error error;
3792 m_destroy_in_process = true;
3793
3794 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003795
3796 if (error.Success())
3797 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003798 if (DetachRequiresHalt())
3799 {
3800 error = HaltForDestroyOrDetach (exit_event_sp);
3801 if (!error.Success())
3802 {
3803 m_destroy_in_process = false;
3804 return error;
3805 }
3806 else if (exit_event_sp)
3807 {
3808 // We shouldn't need to do anything else here. There's no process left to detach from...
3809 StopPrivateStateThread();
3810 m_destroy_in_process = false;
3811 return error;
3812 }
3813 }
3814
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003815 m_thread_list.DiscardThreadPlans();
3816 DisableAllBreakpointSites();
3817
Jim Inghamacff8952013-05-02 00:27:30 +00003818 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003819 if (error.Success())
3820 {
3821 DidDetach();
3822 StopPrivateStateThread();
3823 }
Jim Inghamacff8952013-05-02 00:27:30 +00003824 else
3825 {
3826 return error;
3827 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003829 m_destroy_in_process = false;
3830
3831 // If we exited when we were waiting for a process to stop, then
3832 // forward the event here so we don't lose the event
3833 if (exit_event_sp)
3834 {
3835 // Directly broadcast our exited event because we shut down our
3836 // private state thread above
3837 BroadcastEvent(exit_event_sp);
3838 }
3839
3840 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3841 // the last events through the event system, in which case we might strand the write lock. Unlock
3842 // it here so when we do to tear down the process we don't get an error destroying the lock.
3843
Ed Maste64fad602013-07-29 20:58:06 +00003844 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003845 return error;
3846}
3847
3848Error
3849Process::Destroy ()
3850{
Jim Ingham09437922013-03-01 20:04:25 +00003851
3852 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3853 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3854 // failed and the process stays around for some reason it won't be in a confused state.
3855
3856 m_destroy_in_process = true;
3857
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003858 Error error (WillDestroy());
3859 if (error.Success())
3860 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003861 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003862 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003863 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003864 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003865 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003866
Jim Inghamaacc3182012-06-06 00:29:30 +00003867 if (m_public_state.GetValue() != eStateRunning)
3868 {
3869 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3870 // kill it, we don't want it hitting a breakpoint...
3871 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3872 // we're not going to have much luck doing this now.
3873 m_thread_list.DiscardThreadPlans();
3874 DisableAllBreakpointSites();
3875 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003876
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877 error = DoDestroy();
3878 if (error.Success())
3879 {
3880 DidDestroy();
3881 StopPrivateStateThread();
3882 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003883 m_stdio_communication.StopReadThread();
3884 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003885
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003886 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003887 {
3888 m_process_input_reader->SetIsDone(true);
3889 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003890 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003891 }
3892
Greg Clayton85fb1b92012-09-11 02:33:37 +00003893 // If we exited when we were waiting for a process to stop, then
3894 // forward the event here so we don't lose the event
3895 if (exit_event_sp)
3896 {
3897 // Directly broadcast our exited event because we shut down our
3898 // private state thread above
3899 BroadcastEvent(exit_event_sp);
3900 }
3901
Jim Inghamb1e2e842012-04-12 18:49:31 +00003902 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3903 // the last events through the event system, in which case we might strand the write lock. Unlock
3904 // 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 +00003905 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003906 }
Jim Ingham09437922013-03-01 20:04:25 +00003907
3908 m_destroy_in_process = false;
3909
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003910 return error;
3911}
3912
3913Error
3914Process::Signal (int signal)
3915{
3916 Error error (WillSignal());
3917 if (error.Success())
3918 {
3919 error = DoSignal(signal);
3920 if (error.Success())
3921 DidSignal();
3922 }
3923 return error;
3924}
3925
Greg Clayton514487e2011-02-15 21:59:32 +00003926lldb::ByteOrder
3927Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003928{
Greg Clayton514487e2011-02-15 21:59:32 +00003929 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930}
3931
3932uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003933Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003934{
Greg Clayton514487e2011-02-15 21:59:32 +00003935 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003936}
3937
Greg Clayton514487e2011-02-15 21:59:32 +00003938
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003939bool
3940Process::ShouldBroadcastEvent (Event *event_ptr)
3941{
3942 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3943 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003944 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003945
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003946 switch (state)
3947 {
Greg Claytonb766a732011-02-04 01:58:07 +00003948 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003949 case eStateAttaching:
3950 case eStateLaunching:
3951 case eStateDetached:
3952 case eStateExited:
3953 case eStateUnloaded:
3954 // These events indicate changes in the state of the debugging session, always report them.
3955 return_value = true;
3956 break;
3957 case eStateInvalid:
3958 // We stopped for no apparent reason, don't report it.
3959 return_value = false;
3960 break;
3961 case eStateRunning:
3962 case eStateStepping:
3963 // If we've started the target running, we handle the cases where we
3964 // are already running and where there is a transition from stopped to
3965 // running differently.
3966 // running -> running: Automatically suppress extra running events
3967 // stopped -> running: Report except when there is one or more no votes
3968 // and no yes votes.
3969 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003970 if (m_force_next_event_delivery)
3971 return_value = true;
3972 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003973 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003974 switch (m_last_broadcast_state)
3975 {
3976 case eStateRunning:
3977 case eStateStepping:
3978 // We always suppress multiple runnings with no PUBLIC stop in between.
3979 return_value = false;
3980 break;
3981 default:
3982 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003983 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003984 // events. If I run the lldb/test/thread/a.out file and
3985 // break at main.cpp:58, run and hit the breakpoints on
3986 // multiple threads, then somehow during the stepping over
3987 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988
Jim Ingham1460e4b2014-01-10 23:46:59 +00003989 // This is a transition from stop to run.
3990 switch (m_thread_list.ShouldReportRun (event_ptr))
3991 {
3992 case eVoteYes:
3993 case eVoteNoOpinion:
3994 return_value = true;
3995 break;
3996 case eVoteNo:
3997 return_value = false;
3998 break;
3999 }
4000 break;
4001 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004002 }
4003 break;
4004 case eStateStopped:
4005 case eStateCrashed:
4006 case eStateSuspended:
4007 {
4008 // We've stopped. First see if we're going to restart the target.
4009 // If we are going to stop, then we always broadcast the event.
4010 // 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 +00004011 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004012
Jim Inghamcb4ca112012-05-16 01:32:14 +00004013 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004014 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004015 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004016 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004017 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004018 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004019 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004020 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4021 // so they can properly set their state.
4022 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004023 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004024 }
4025 else
4026 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004027 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4028 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004029
Jim Ingham0161b492013-02-09 01:29:05 +00004030 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4031 // Asking the thread list is also not likely to go well, since we are running again.
4032 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004033
Jim Ingham0161b492013-02-09 01:29:05 +00004034 if (!was_restarted)
4035 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004036
Jim Ingham221d51c2013-05-08 00:35:16 +00004037 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038 {
Jim Ingham0161b492013-02-09 01:29:05 +00004039 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4040 if (log)
4041 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004042 should_resume, StateAsCString(state),
4043 was_restarted, stop_vote);
4044
Jim Ingham0161b492013-02-09 01:29:05 +00004045 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004046 {
4047 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004048 return_value = true;
4049 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051 case eVoteNo:
4052 return_value = false;
4053 break;
4054 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004055
Jim Inghamcb95f342012-09-05 21:13:56 +00004056 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004057 {
4058 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004059 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4060 static_cast<void*>(event_ptr),
4061 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004062 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004063 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004064 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004065
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004066 }
4067 else
4068 {
4069 return_value = true;
4070 SynchronouslyNotifyStateChanged (state);
4071 }
4072 }
4073 }
Jim Ingham0161b492013-02-09 01:29:05 +00004074 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004075 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004076
Jim Ingham1460e4b2014-01-10 23:46:59 +00004077 // Forcing the next event delivery is a one shot deal. So reset it here.
4078 m_force_next_event_delivery = false;
4079
Jim Ingham0161b492013-02-09 01:29:05 +00004080 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4081 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4082 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4083 // because the PublicState reflects the last event pulled off the queue, and there may be several
4084 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4085 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004086
Jim Ingham0161b492013-02-09 01:29:05 +00004087 if (return_value)
4088 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004089
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004090 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004091 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004092 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004093 StateAsCString(m_last_broadcast_state),
4094 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004095 return return_value;
4096}
4097
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098
4099bool
Jim Ingham372787f2012-04-07 00:00:41 +00004100Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004101{
Greg Clayton5160ce52013-03-27 23:08:40 +00004102 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004103
Greg Clayton8b82f082011-04-12 05:54:46 +00004104 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004105 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004106 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4107
Jim Ingham372787f2012-04-07 00:00:41 +00004108 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004109 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110
4111 // Create a thread that watches our internal state and controls which
4112 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004113 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004114
Zachary Turner39de3112014-09-09 20:54:56 +00004115 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004116 {
Zachary Turner39de3112014-09-09 20:54:56 +00004117 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4118 if (already_running)
4119 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4120 else
4121 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004122 }
Jim Ingham372787f2012-04-07 00:00:41 +00004123 else
Todd Fiala17096d72014-07-16 19:03:16 +00004124 {
4125 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004126 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004127 else
Zachary Turner39de3112014-09-09 20:54:56 +00004128 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004129 }
4130
Jim Ingham076b3042012-04-10 01:21:57 +00004131 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00004132 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004133 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004134 {
4135 ResumePrivateStateThread();
4136 return true;
4137 }
4138 else
4139 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004140}
4141
4142void
4143Process::PausePrivateStateThread ()
4144{
4145 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4146}
4147
4148void
4149Process::ResumePrivateStateThread ()
4150{
4151 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4152}
4153
4154void
4155Process::StopPrivateStateThread ()
4156{
Greg Clayton8b82f082011-04-12 05:54:46 +00004157 if (PrivateStateThreadIsValid ())
4158 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004159 else
4160 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004161 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004162 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004163 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165}
4166
4167void
4168Process::ControlPrivateStateThread (uint32_t signal)
4169{
Greg Clayton5160ce52013-03-27 23:08:40 +00004170 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004171
4172 assert (signal == eBroadcastInternalStateControlStop ||
4173 signal == eBroadcastInternalStateControlPause ||
4174 signal == eBroadcastInternalStateControlResume);
4175
4176 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004177 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004178
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004179 // Signal the private state thread. First we should copy this is case the
4180 // thread starts exiting since the private state thread will NULL this out
4181 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004182 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004183 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004184 {
4185 TimeValue timeout_time;
4186 bool timed_out;
4187
4188 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4189
4190 timeout_time = TimeValue::Now();
4191 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004192 if (log)
4193 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004194 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4195 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4196
4197 if (signal == eBroadcastInternalStateControlStop)
4198 {
4199 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004200 {
Zachary Turner39de3112014-09-09 20:54:56 +00004201 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004202 if (log)
4203 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4204 }
4205 else
4206 {
4207 if (log)
4208 log->Printf ("The control event killed the private state thread without having to cancel.");
4209 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004210
4211 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004212 private_state_thread.Join(&result);
4213 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004214 }
4215 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004216 else
4217 {
4218 if (log)
4219 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4220 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004221}
4222
4223void
Jim Inghamcfc09352012-07-27 23:57:19 +00004224Process::SendAsyncInterrupt ()
4225{
4226 if (PrivateStateThreadIsValid())
4227 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4228 else
4229 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4230}
4231
4232void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004233Process::HandlePrivateEvent (EventSP &event_sp)
4234{
Greg Clayton5160ce52013-03-27 23:08:40 +00004235 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004236 m_resume_requested = false;
4237
Jim Inghamaacc3182012-06-06 00:29:30 +00004238 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004239
Greg Clayton414f5d32011-01-25 02:58:48 +00004240 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004241
4242 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004243 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004244 {
Jim Ingham754ab982011-01-29 04:05:41 +00004245 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004246 if (log)
4247 log->Printf ("Ran next event action, result was %d.", action_result);
4248
Jim Inghambb3a2832011-01-29 01:49:25 +00004249 switch (action_result)
4250 {
4251 case NextEventAction::eEventActionSuccess:
4252 SetNextEventAction(NULL);
4253 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004254
Jim Inghambb3a2832011-01-29 01:49:25 +00004255 case NextEventAction::eEventActionRetry:
4256 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004257
Jim Inghambb3a2832011-01-29 01:49:25 +00004258 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004259 // Handle Exiting Here. If we already got an exited event,
4260 // we should just propagate it. Otherwise, swallow this event,
4261 // and set our state to exit so the next event will kill us.
4262 if (new_state != eStateExited)
4263 {
4264 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004265 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004266 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004267 SetNextEventAction(NULL);
4268 return;
4269 }
4270 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004271 break;
4272 }
4273 }
4274
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004275 // See if we should broadcast this state to external clients?
4276 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004277
4278 if (should_broadcast)
4279 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004280 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004281 if (log)
4282 {
Daniel Malead01b2952012-11-29 21:49:15 +00004283 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004284 __FUNCTION__,
4285 GetID(),
4286 StateAsCString(new_state),
4287 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004288 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004289 }
Jim Ingham9575d842011-03-11 03:53:59 +00004290 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004291 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004292 {
4293 // Only push the input handler if we aren't fowarding events,
4294 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004295 // Or don't push it if we are launching since it will come up stopped.
4296 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004297 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004298 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004299 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004300 else if (StateIsStoppedState(new_state, false))
4301 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004302 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004303 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4304 {
4305 // If the lldb_private::Debugger is handling the events, we don't
4306 // want to pop the process IOHandler here, we want to do it when
4307 // we receive the stopped event so we can carefully control when
4308 // the process IOHandler is popped because when we stop we want to
4309 // display some text stating how and why we stopped, then maybe some
4310 // process/thread/frame info, and then we want the "(lldb) " prompt
4311 // to show up. If we pop the process IOHandler here, then we will
4312 // cause the command interpreter to become the top IOHandler after
4313 // the process pops off and it will update its prompt right away...
4314 // See the Debugger.cpp file where it calls the function as
4315 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4316 // Otherwise we end up getting overlapping "(lldb) " prompts and
4317 // garbled output.
4318 //
4319 // If we aren't handling the events in the debugger (which is indicated
4320 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4321 // are hijacked, then we always pop the process IO handler manually.
4322 // Hijacking happens when the internal process state thread is running
4323 // thread plans, or when commands want to run in synchronous mode
4324 // and they call "process->WaitForProcessToStop()". An example of something
4325 // that will hijack the events is a simple expression:
4326 //
4327 // (lldb) expr (int)puts("hello")
4328 //
4329 // This will cause the internal process state thread to resume and halt
4330 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4331 // events) and we do need the IO handler to be pushed and popped
4332 // correctly.
4333
4334 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4335 PopProcessIOHandler ();
4336 }
4337 }
Jim Ingham9575d842011-03-11 03:53:59 +00004338
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004339 BroadcastEvent (event_sp);
4340 }
4341 else
4342 {
4343 if (log)
4344 {
Daniel Malead01b2952012-11-29 21:49:15 +00004345 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004346 __FUNCTION__,
4347 GetID(),
4348 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004349 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004350 }
4351 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004352 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353}
4354
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004355thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004356Process::PrivateStateThread (void *arg)
4357{
4358 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004359 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004360 return result;
4361}
4362
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004363thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004364Process::RunPrivateStateThread ()
4365{
Jim Ingham076b3042012-04-10 01:21:57 +00004366 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004367 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004368
Greg Clayton5160ce52013-03-27 23:08:40 +00004369 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004370 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004371 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4372 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004373
4374 bool exit_now = false;
4375 while (!exit_now)
4376 {
4377 EventSP event_sp;
4378 WaitForEventsPrivate (NULL, event_sp, control_only);
4379 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4380 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004381 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004382 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4383 __FUNCTION__, static_cast<void*>(this), GetID(),
4384 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004386 switch (event_sp->GetType())
4387 {
4388 case eBroadcastInternalStateControlStop:
4389 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004390 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391
4392 case eBroadcastInternalStateControlPause:
4393 control_only = true;
4394 break;
4395
4396 case eBroadcastInternalStateControlResume:
4397 control_only = false;
4398 break;
4399 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004401 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004402 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004403 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004404 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4405 {
4406 if (m_public_state.GetValue() == eStateAttaching)
4407 {
4408 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004409 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4410 __FUNCTION__, static_cast<void*>(this),
4411 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004412 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4413 }
4414 else
4415 {
4416 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004417 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4418 __FUNCTION__, static_cast<void*>(this),
4419 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004420 Halt();
4421 }
4422 continue;
4423 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004424
4425 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4426
4427 if (internal_state != eStateInvalid)
4428 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004429 if (m_clear_thread_plans_on_stop &&
4430 StateIsStoppedState(internal_state, true))
4431 {
4432 m_clear_thread_plans_on_stop = false;
4433 m_thread_list.DiscardThreadPlans();
4434 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004435 HandlePrivateEvent (event_sp);
4436 }
4437
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004438 if (internal_state == eStateInvalid ||
4439 internal_state == eStateExited ||
4440 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004441 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004442 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004443 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4444 __FUNCTION__, static_cast<void*>(this), GetID(),
4445 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004446
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004447 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004448 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004449 }
4450
Caroline Tice20ad3c42010-10-29 21:48:37 +00004451 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004452 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004453 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4454 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004455
Ed Maste64fad602013-07-29 20:58:06 +00004456 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004457 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004458 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004459 return NULL;
4460}
4461
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004462//------------------------------------------------------------------
4463// Process Event Data
4464//------------------------------------------------------------------
4465
4466Process::ProcessEventData::ProcessEventData () :
4467 EventData (),
4468 m_process_sp (),
4469 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004470 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004471 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004472 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004473{
4474}
4475
4476Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4477 EventData (),
4478 m_process_sp (process_sp),
4479 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004480 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004481 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004482 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004483{
4484}
4485
4486Process::ProcessEventData::~ProcessEventData()
4487{
4488}
4489
4490const ConstString &
4491Process::ProcessEventData::GetFlavorString ()
4492{
4493 static ConstString g_flavor ("Process::ProcessEventData");
4494 return g_flavor;
4495}
4496
4497const ConstString &
4498Process::ProcessEventData::GetFlavor () const
4499{
4500 return ProcessEventData::GetFlavorString ();
4501}
4502
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004503void
4504Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4505{
4506 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004507 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4508 // the public event queue, then other times when we're pretending that this is where we stopped at the
4509 // end of expression evaluation. m_update_state is used to distinguish these
4510 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004511 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004512 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004513 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004514
Jim Ingham221d51c2013-05-08 00:35:16 +00004515 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004516
4517 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4518 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4519 // end up restarting the process.
4520 if (m_interrupted)
4521 return;
4522
4523 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004524 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004525 {
4526 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004527 uint32_t num_threads = curr_thread_list.GetSize();
4528 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004529
Jim Ingham4b536182011-08-09 02:12:22 +00004530 // The actions might change one of the thread's stop_info's opinions about whether we should
4531 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004532
4533 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4534 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4535 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4536 // 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
4537 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004538 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004539 for (idx = 0; idx < num_threads; ++idx)
4540 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4541
Jim Inghamc7078c22012-12-13 22:24:15 +00004542 // Use this to track whether we should continue from here. We will only continue the target running if
4543 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4544 // then it doesn't matter what the other threads say...
4545
4546 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004547
Jim Ingham0ad7e052013-04-25 02:04:59 +00004548 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4549 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4550 // thing to do is, and it's better to let the user decide than continue behind their backs.
4551
4552 bool does_anybody_have_an_opinion = false;
4553
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004554 for (idx = 0; idx < num_threads; ++idx)
4555 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004556 curr_thread_list = m_process_sp->GetThreadList();
4557 if (curr_thread_list.GetSize() != num_threads)
4558 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004559 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004560 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004561 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 +00004562 break;
4563 }
4564
4565 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4566
4567 if (thread_sp->GetIndexID() != thread_index_array[idx])
4568 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004569 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004570 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004571 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004572 idx,
4573 thread_index_array[idx],
4574 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004575 break;
4576 }
4577
Jim Inghamb15bfc72010-10-20 00:39:53 +00004578 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004579 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004580 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004581 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004582 bool this_thread_wants_to_stop;
4583 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004584 {
Jim Ingham0161b492013-02-09 01:29:05 +00004585 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4586 }
4587 else
4588 {
4589 stop_info_sp->PerformAction(event_ptr);
4590 // The stop action might restart the target. If it does, then we want to mark that in the
4591 // event so that whoever is receiving it will know to wait for the running event and reflect
4592 // that state appropriately.
4593 // We also need to stop processing actions, since they aren't expecting the target to be running.
4594
4595 // FIXME: we might have run.
4596 if (stop_info_sp->HasTargetRunSinceMe())
4597 {
4598 SetRestarted (true);
4599 break;
4600 }
4601
4602 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004603 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004604
Jim Inghamc7078c22012-12-13 22:24:15 +00004605 if (still_should_stop == false)
4606 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004607 }
4608 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004609
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004610
Jim Inghama8ca6e22013-05-03 23:04:37 +00004611 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004612 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004613 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004614 {
4615 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004616 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004617 // Use the public resume method here, since this is just
4618 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004619 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004620 }
4621 else
4622 {
4623 // If we didn't restart, run the Stop Hooks here:
4624 // They might also restart the target, so watch for that.
4625 m_process_sp->GetTarget().RunStopHooks();
4626 if (m_process_sp->GetPrivateState() == eStateRunning)
4627 SetRestarted(true);
4628 }
Jim Ingham9575d842011-03-11 03:53:59 +00004629 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004630 }
4631}
4632
4633void
4634Process::ProcessEventData::Dump (Stream *s) const
4635{
4636 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004637 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4638 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004639
Greg Clayton8b82f082011-04-12 05:54:46 +00004640 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004641}
4642
4643const Process::ProcessEventData *
4644Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4645{
4646 if (event_ptr)
4647 {
4648 const EventData *event_data = event_ptr->GetData();
4649 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4650 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4651 }
4652 return NULL;
4653}
4654
4655ProcessSP
4656Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4657{
4658 ProcessSP process_sp;
4659 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4660 if (data)
4661 process_sp = data->GetProcessSP();
4662 return process_sp;
4663}
4664
4665StateType
4666Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4667{
4668 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4669 if (data == NULL)
4670 return eStateInvalid;
4671 else
4672 return data->GetState();
4673}
4674
4675bool
4676Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4677{
4678 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4679 if (data == NULL)
4680 return false;
4681 else
4682 return data->GetRestarted();
4683}
4684
4685void
4686Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4687{
4688 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4689 if (data != NULL)
4690 data->SetRestarted(new_value);
4691}
4692
Jim Ingham0161b492013-02-09 01:29:05 +00004693size_t
4694Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4695{
4696 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4697 if (data != NULL)
4698 return data->GetNumRestartedReasons();
4699 else
4700 return 0;
4701}
4702
4703const char *
4704Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4705{
4706 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4707 if (data != NULL)
4708 return data->GetRestartedReasonAtIndex(idx);
4709 else
4710 return NULL;
4711}
4712
4713void
4714Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4715{
4716 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4717 if (data != NULL)
4718 data->AddRestartedReason(reason);
4719}
4720
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004721bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004722Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4723{
4724 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4725 if (data == NULL)
4726 return false;
4727 else
4728 return data->GetInterrupted ();
4729}
4730
4731void
4732Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4733{
4734 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4735 if (data != NULL)
4736 data->SetInterrupted(new_value);
4737}
4738
4739bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004740Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4741{
4742 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4743 if (data)
4744 {
4745 data->SetUpdateStateOnRemoval();
4746 return true;
4747 }
4748 return false;
4749}
4750
Greg Claytond9e416c2012-02-18 05:35:26 +00004751lldb::TargetSP
4752Process::CalculateTarget ()
4753{
4754 return m_target.shared_from_this();
4755}
4756
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004757void
Greg Clayton0603aa92010-10-04 01:05:56 +00004758Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004759{
Greg Claytonc14ee322011-09-22 04:58:26 +00004760 exe_ctx.SetTargetPtr (&m_target);
4761 exe_ctx.SetProcessPtr (this);
4762 exe_ctx.SetThreadPtr(NULL);
4763 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004764}
4765
Greg Claytone996fd32011-03-08 22:40:15 +00004766//uint32_t
4767//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4768//{
4769// return 0;
4770//}
4771//
4772//ArchSpec
4773//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4774//{
4775// return Host::GetArchSpecForExistingProcess (pid);
4776//}
4777//
4778//ArchSpec
4779//Process::GetArchSpecForExistingProcess (const char *process_name)
4780//{
4781// return Host::GetArchSpecForExistingProcess (process_name);
4782//}
4783//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004784void
4785Process::AppendSTDOUT (const char * s, size_t len)
4786{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004787 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004788 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004789 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004790}
4791
4792void
Greg Clayton93e86192011-11-13 04:45:22 +00004793Process::AppendSTDERR (const char * s, size_t len)
4794{
4795 Mutex::Locker locker (m_stdio_communication_mutex);
4796 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004797 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004798}
4799
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004800void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004801Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004802{
4803 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004804 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004805 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4806}
4807
4808size_t
4809Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4810{
4811 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004812 if (m_profile_data.empty())
4813 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004814
4815 std::string &one_profile_data = m_profile_data.front();
4816 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004817 if (bytes_available > 0)
4818 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004819 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004820 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004821 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4822 static_cast<void*>(buf),
4823 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004824 if (bytes_available > buf_size)
4825 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004826 memcpy(buf, one_profile_data.c_str(), buf_size);
4827 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004828 bytes_available = buf_size;
4829 }
4830 else
4831 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004832 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004833 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004834 }
4835 }
4836 return bytes_available;
4837}
4838
4839
Greg Clayton93e86192011-11-13 04:45:22 +00004840//------------------------------------------------------------------
4841// Process STDIO
4842//------------------------------------------------------------------
4843
4844size_t
4845Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4846{
4847 Mutex::Locker locker(m_stdio_communication_mutex);
4848 size_t bytes_available = m_stdout_data.size();
4849 if (bytes_available > 0)
4850 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004851 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004852 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004853 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4854 static_cast<void*>(buf),
4855 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004856 if (bytes_available > buf_size)
4857 {
4858 memcpy(buf, m_stdout_data.c_str(), buf_size);
4859 m_stdout_data.erase(0, buf_size);
4860 bytes_available = buf_size;
4861 }
4862 else
4863 {
4864 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4865 m_stdout_data.clear();
4866 }
4867 }
4868 return bytes_available;
4869}
4870
4871
4872size_t
4873Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4874{
4875 Mutex::Locker locker(m_stdio_communication_mutex);
4876 size_t bytes_available = m_stderr_data.size();
4877 if (bytes_available > 0)
4878 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004879 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004880 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004881 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4882 static_cast<void*>(buf),
4883 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004884 if (bytes_available > buf_size)
4885 {
4886 memcpy(buf, m_stderr_data.c_str(), buf_size);
4887 m_stderr_data.erase(0, buf_size);
4888 bytes_available = buf_size;
4889 }
4890 else
4891 {
4892 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4893 m_stderr_data.clear();
4894 }
4895 }
4896 return bytes_available;
4897}
4898
4899void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004900Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4901{
4902 Process *process = (Process *) baton;
4903 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4904}
4905
Greg Clayton44d93782014-01-27 23:43:24 +00004906class IOHandlerProcessSTDIO :
4907 public IOHandler
4908{
4909public:
4910 IOHandlerProcessSTDIO (Process *process,
4911 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00004912 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00004913 m_process (process),
4914 m_read_file (),
4915 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004916 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004917 {
4918 m_read_file.SetDescriptor(GetInputFD(), false);
4919 }
4920
4921 virtual
4922 ~IOHandlerProcessSTDIO ()
4923 {
4924
4925 }
4926
4927 bool
4928 OpenPipes ()
4929 {
Greg Clayton100eb932014-07-02 21:10:39 +00004930 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004931 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004932 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004933 }
4934
4935 void
4936 ClosePipes()
4937 {
Greg Clayton100eb932014-07-02 21:10:39 +00004938 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004939 }
4940
4941 // Each IOHandler gets to run until it is done. It should read data
4942 // from the "in" and place output into "out" and "err and return
4943 // when done.
4944 virtual void
4945 Run ()
4946 {
4947 if (m_read_file.IsValid() && m_write_file.IsValid())
4948 {
4949 SetIsDone(false);
4950 if (OpenPipes())
4951 {
4952 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004953 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004954 TerminalState terminal_state;
4955 terminal_state.Save (read_fd, false);
4956 Terminal terminal(read_fd);
4957 terminal.SetCanonical(false);
4958 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004959// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004960#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004961 while (!GetIsDone())
4962 {
4963 fd_set read_fdset;
4964 FD_ZERO (&read_fdset);
4965 FD_SET (read_fd, &read_fdset);
4966 FD_SET (pipe_read_fd, &read_fdset);
4967 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4968 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4969 if (num_set_fds < 0)
4970 {
4971 const int select_errno = errno;
4972
4973 if (select_errno != EINTR)
4974 SetIsDone(true);
4975 }
4976 else if (num_set_fds > 0)
4977 {
4978 char ch = 0;
4979 size_t n;
4980 if (FD_ISSET (read_fd, &read_fdset))
4981 {
4982 n = 1;
4983 if (m_read_file.Read(&ch, n).Success() && n == 1)
4984 {
4985 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4986 SetIsDone(true);
4987 }
4988 else
4989 SetIsDone(true);
4990 }
4991 if (FD_ISSET (pipe_read_fd, &read_fdset))
4992 {
4993 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004994 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004995 {
Greg Clayton100eb932014-07-02 21:10:39 +00004996 switch (ch)
4997 {
4998 case 'q':
4999 SetIsDone(true);
5000 break;
5001 case 'i':
5002 if (StateIsRunningState(m_process->GetState()))
5003 m_process->Halt();
5004 break;
5005 }
Greg Clayton19e11352014-02-26 22:47:33 +00005006 }
Greg Clayton44d93782014-01-27 23:43:24 +00005007 }
5008 }
5009 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00005010#endif
Greg Clayton44d93782014-01-27 23:43:24 +00005011 terminal_state.Restore();
5012
5013 }
5014 else
5015 SetIsDone(true);
5016 }
5017 else
5018 SetIsDone(true);
5019 }
5020
5021 // Hide any characters that have been displayed so far so async
5022 // output can be displayed. Refresh() will be called after the
5023 // output has been displayed.
5024 virtual void
5025 Hide ()
5026 {
5027
5028 }
5029 // Called when the async output has been received in order to update
5030 // the input reader (refresh the prompt and redisplay any current
5031 // line(s) that are being edited
5032 virtual void
5033 Refresh ()
5034 {
5035
5036 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005037
Greg Clayton44d93782014-01-27 23:43:24 +00005038 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00005039 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00005040 {
Greg Clayton19e11352014-02-26 22:47:33 +00005041 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00005042 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00005043 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005044
Greg Claytonf0066ad2014-05-02 00:45:31 +00005045 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00005046 Interrupt ()
5047 {
Greg Clayton19e11352014-02-26 22:47:33 +00005048 // Do only things that are safe to do in an interrupt context (like in
5049 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5050 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5051 // that was written to the pipe and then call m_process->Halt() from a
5052 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005053 if (m_active)
5054 {
5055 char ch = 'i'; // Send 'i' for interrupt
5056 return m_pipe.Write (&ch, 1) == 1;
5057 }
5058 else
5059 {
5060 // This IOHandler might be pushed on the stack, but not being run currently
5061 // so do the right thing if we aren't actively watching for STDIN by sending
5062 // the interrupt to the process. Otherwise the write to the pipe above would
5063 // do nothing. This can happen when the command interpreter is running and
5064 // gets a "expression ...". It will be on the IOHandler thread and sending
5065 // the input is complete to the delegate which will cause the expression to
5066 // run, which will push the process IO handler, but not run it.
5067
5068 if (StateIsRunningState(m_process->GetState()))
5069 {
5070 m_process->SendAsyncInterrupt();
5071 return true;
5072 }
5073 }
5074 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005075 }
Greg Clayton44d93782014-01-27 23:43:24 +00005076
5077 virtual void
5078 GotEOF()
5079 {
5080
5081 }
5082
5083protected:
5084 Process *m_process;
5085 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5086 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005087 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005088};
5089
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005090void
Greg Clayton44d93782014-01-27 23:43:24 +00005091Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005092{
5093 // First set up the Read Thread for reading/handling process I/O
5094
Greg Clayton44d93782014-01-27 23:43:24 +00005095 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005096
5097 if (conn_ap.get())
5098 {
5099 m_stdio_communication.SetConnection (conn_ap.release());
5100 if (m_stdio_communication.IsConnected())
5101 {
5102 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5103 m_stdio_communication.StartReadThread();
5104
5105 // Now read thread is set up, set up input reader.
5106
5107 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005108 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005109 }
5110 }
5111}
5112
Greg Claytonb4874f12014-02-28 18:22:24 +00005113bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005114Process::ProcessIOHandlerIsActive ()
5115{
5116 IOHandlerSP io_handler_sp (m_process_input_reader);
5117 if (io_handler_sp)
5118 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5119 return false;
5120}
5121bool
Greg Clayton44d93782014-01-27 23:43:24 +00005122Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005123{
Greg Clayton44d93782014-01-27 23:43:24 +00005124 IOHandlerSP io_handler_sp (m_process_input_reader);
5125 if (io_handler_sp)
5126 {
5127 io_handler_sp->SetIsDone(false);
5128 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005129 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005130 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005131 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005132}
5133
Greg Claytonb4874f12014-02-28 18:22:24 +00005134bool
Greg Clayton44d93782014-01-27 23:43:24 +00005135Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005136{
Greg Clayton44d93782014-01-27 23:43:24 +00005137 IOHandlerSP io_handler_sp (m_process_input_reader);
5138 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005139 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5140 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005141}
5142
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005143// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005144void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005145Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005146{
Greg Clayton6920b522012-08-22 18:39:03 +00005147 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005148}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005149
Greg Clayton99d0faf2010-11-18 23:32:35 +00005150void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005151Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005152{
Greg Clayton6920b522012-08-22 18:39:03 +00005153 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005154}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005155
Jim Ingham1624a2d2014-05-05 02:26:40 +00005156ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005157Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005158 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005159 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005160 Stream &errors)
5161{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005162 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005163
Jim Ingham77787032011-01-20 02:03:18 +00005164 if (thread_plan_sp.get() == NULL)
5165 {
5166 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005167 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005168 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005169
Jim Ingham7d7931d2013-03-28 00:05:34 +00005170 if (!thread_plan_sp->ValidatePlan(NULL))
5171 {
5172 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005173 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005174 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005175
Greg Claytonc14ee322011-09-22 04:58:26 +00005176 if (exe_ctx.GetProcessPtr() != this)
5177 {
5178 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005179 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005180 }
5181
5182 Thread *thread = exe_ctx.GetThreadPtr();
5183 if (thread == NULL)
5184 {
5185 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005186 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005187 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005188
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005189 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5190 // For that to be true the plan can't be private - since private plans suppress themselves in the
5191 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005192
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005193 bool orig_plan_private = thread_plan_sp->GetPrivate();
5194 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005195
Jim Ingham444586b2011-01-24 06:34:17 +00005196 if (m_private_state.GetValue() != eStateStopped)
5197 {
5198 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005199 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005200 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005201
Jim Ingham66243842011-08-13 00:56:10 +00005202 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005203 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005204 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005205 if (!selected_frame_sp)
5206 {
5207 thread->SetSelectedFrame(0);
5208 selected_frame_sp = thread->GetSelectedFrame();
5209 if (!selected_frame_sp)
5210 {
5211 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005212 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005213 }
5214 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005215
Jim Ingham11b0e052013-02-19 23:22:45 +00005216 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005217
5218 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5219 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005220
Greg Claytonc14ee322011-09-22 04:58:26 +00005221 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005222
Jim Ingham66243842011-08-13 00:56:10 +00005223 uint32_t selected_tid;
5224 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005225 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005226 {
5227 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005228 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005229 }
5230 else
5231 {
5232 selected_tid = LLDB_INVALID_THREAD_ID;
5233 }
5234
Zachary Turner39de3112014-09-09 20:54:56 +00005235 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005236 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005237 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005238
Greg Clayton5160ce52013-03-27 23:08:40 +00005239 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005240 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005241 {
Jim Ingham076b3042012-04-10 01:21:57 +00005242 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5243 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005244 // 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 +00005245 // we are fielding public events here.
5246 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005247 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 +00005248
Jim Ingham372787f2012-04-07 00:00:41 +00005249 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005250
5251 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5252 // returning control here.
5253 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5254 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5255 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5256 // do just what we want.
5257 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5258 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5259 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5260 old_state = m_public_state.GetValue();
5261 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005262
Jim Ingham076b3042012-04-10 01:21:57 +00005263 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005264 StartPrivateStateThread(true);
5265 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005266
Jim Ingham372787f2012-04-07 00:00:41 +00005267 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005268
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005269 if (options.GetDebug())
5270 {
5271 // In this case, we aren't actually going to run, we just want to stop right away.
5272 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5273 // FIXME: To make this prettier we should invent some stop reason for this, but that
5274 // is only cosmetic, and this functionality is only of use to lldb developers who can
5275 // live with not pretty...
5276 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005277 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005278 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005279
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005280 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005281
Sean Callanana46ec452012-07-11 21:31:24 +00005282 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005283
Jim Ingham77787032011-01-20 02:03:18 +00005284 {
Sean Callanana46ec452012-07-11 21:31:24 +00005285 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5286 // restored on exit to the function.
5287 //
5288 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5289 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005290
Sean Callanana46ec452012-07-11 21:31:24 +00005291 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005292
Jim Inghamf48169b2010-11-30 02:22:11 +00005293 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005294 {
5295 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005296 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005297 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005298 thread->GetIndexID(),
5299 thread->GetID(),
5300 s.GetData());
5301 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005302
Sean Callanana46ec452012-07-11 21:31:24 +00005303 bool got_event;
5304 lldb::EventSP event_sp;
5305 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005306
Sean Callanana46ec452012-07-11 21:31:24 +00005307 TimeValue* timeout_ptr = NULL;
5308 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005309
Jim Ingham0161b492013-02-09 01:29:05 +00005310 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 +00005311 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005312 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005313 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005314
Jim Ingham0161b492013-02-09 01:29:05 +00005315 // This is just for accounting:
5316 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005317
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005318 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005319 uint32_t one_thread_timeout_usec;
5320 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005321
5322 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5323 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5324 // first timeout already.
5325
5326 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005327 {
5328 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005329 one_thread_timeout_usec = 0;
5330 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005331 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005332 else
Jim Ingham0161b492013-02-09 01:29:05 +00005333 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005334 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005335
Jim Ingham914f4e72014-03-28 21:58:28 +00005336 // If the overall wait is forever, then we only need to set the one thread timeout:
5337 if (timeout_usec == 0)
5338 {
Ed Maste801335c2014-03-31 19:28:14 +00005339 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005340 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005341 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005342 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005343 }
Jim Ingham0161b492013-02-09 01:29:05 +00005344 else
5345 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005346 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5347 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5348 uint64_t computed_one_thread_timeout;
5349 if (option_one_thread_timeout != 0)
5350 {
5351 if (timeout_usec < option_one_thread_timeout)
5352 {
5353 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005354 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005355 }
5356 computed_one_thread_timeout = option_one_thread_timeout;
5357 }
5358 else
5359 {
5360 computed_one_thread_timeout = timeout_usec / 2;
5361 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5362 computed_one_thread_timeout = default_one_thread_timeout_usec;
5363 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005364 one_thread_timeout_usec = computed_one_thread_timeout;
5365 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5366
Jim Ingham0161b492013-02-09 01:29:05 +00005367 }
Jim Ingham0161b492013-02-09 01:29:05 +00005368 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005369
5370 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005371 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 +00005372 options.GetStopOthers(),
5373 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005374 before_first_timeout,
5375 one_thread_timeout_usec,
5376 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005377
Jim Ingham1460e4b2014-01-10 23:46:59 +00005378 // This isn't going to work if there are unfetched events on the queue.
5379 // Are there cases where we might want to run the remaining events here, and then try to
5380 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005381
Jim Ingham1460e4b2014-01-10 23:46:59 +00005382 Event *other_events = listener.PeekAtNextEvent();
5383 if (other_events != NULL)
5384 {
5385 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005386 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005387 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005388
Jim Ingham1460e4b2014-01-10 23:46:59 +00005389 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5390 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5391 // event coalescing to cause us to lose OUR running event...
5392 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005393
Jim Ingham8559a352012-11-26 23:52:18 +00005394 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5395 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005396
5397#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5398 // It's pretty much impossible to write test cases for things like:
5399 // One thread timeout expires, I go to halt, but the process already stopped
5400 // on the function call stop breakpoint. Turning on this define will make us not
5401 // fetch the first event till after the halt. So if you run a quick function, it will have
5402 // completed, and the completion event will be waiting, when you interrupt for halt.
5403 // The expression evaluation should still succeed.
5404 bool miss_first_event = true;
5405#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005406 TimeValue one_thread_timeout;
5407 TimeValue final_timeout;
5408
Jim Ingham35878c42014-04-08 21:33:21 +00005409
Sean Callanana46ec452012-07-11 21:31:24 +00005410 while (1)
5411 {
5412 // We usually want to resume the process if we get to the top of the loop.
5413 // The only exception is if we get two running events with no intervening
5414 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005415 if (log)
5416 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5417 do_resume,
5418 handle_running_event,
5419 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005420
Jim Ingham184e9812013-01-15 02:47:48 +00005421 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005422 {
5423 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005424
Jim Ingham184e9812013-01-15 02:47:48 +00005425 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005426 {
Jim Ingham0161b492013-02-09 01:29:05 +00005427 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005428 Error resume_error = PrivateResume ();
5429 if (!resume_error.Success())
5430 {
Jim Ingham0161b492013-02-09 01:29:05 +00005431 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5432 num_resumes,
5433 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005434 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005435 break;
5436 }
Sean Callanana46ec452012-07-11 21:31:24 +00005437 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005438
Jim Ingham0161b492013-02-09 01:29:05 +00005439 TimeValue resume_timeout = TimeValue::Now();
5440 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005441
Jim Ingham0161b492013-02-09 01:29:05 +00005442 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005443 if (!got_event)
5444 {
5445 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005446 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5447 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005448
Jim Ingham0161b492013-02-09 01:29:05 +00005449 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005450 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005451 break;
5452 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005453
Sean Callanana46ec452012-07-11 21:31:24 +00005454 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005455
Sean Callanana46ec452012-07-11 21:31:24 +00005456 if (stop_state != eStateRunning)
5457 {
Jim Ingham0161b492013-02-09 01:29:05 +00005458 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005459
Jim Ingham0161b492013-02-09 01:29:05 +00005460 if (stop_state == eStateStopped)
5461 {
5462 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5463 if (log)
5464 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5465 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5466 num_resumes,
5467 StateAsCString(stop_state),
5468 restarted,
5469 do_resume,
5470 handle_running_event);
5471 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005472
Jim Ingham0161b492013-02-09 01:29:05 +00005473 if (restarted)
5474 {
5475 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5476 // event here. But if I do, the best thing is to Halt and then get out of here.
5477 Halt();
5478 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005479
Jim Ingham35e1bda2012-10-16 21:41:58 +00005480 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5481 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005482 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005483 break;
5484 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005485
Sean Callanana46ec452012-07-11 21:31:24 +00005486 if (log)
5487 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5488 // We need to call the function synchronously, so spin waiting for it to return.
5489 // If we get interrupted while executing, we're going to lose our context, and
5490 // won't be able to gather the result at this point.
5491 // We set the timeout AFTER the resume, since the resume takes some time and we
5492 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005493 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005494 else
5495 {
Sean Callanana46ec452012-07-11 21:31:24 +00005496 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005497 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005498 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005499
Jim Ingham0161b492013-02-09 01:29:05 +00005500 if (before_first_timeout)
5501 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005502 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005503 {
5504 one_thread_timeout = TimeValue::Now();
5505 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005506 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005507 }
Jim Ingham0161b492013-02-09 01:29:05 +00005508 else
5509 {
5510 if (timeout_usec == 0)
5511 timeout_ptr = NULL;
5512 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005513 {
5514 final_timeout = TimeValue::Now();
5515 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005516 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005517 }
Jim Ingham0161b492013-02-09 01:29:05 +00005518 }
5519 }
5520 else
5521 {
5522 if (timeout_usec == 0)
5523 timeout_ptr = NULL;
5524 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005525 {
5526 final_timeout = TimeValue::Now();
5527 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005528 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005529 }
Jim Ingham0161b492013-02-09 01:29:05 +00005530 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005531
Jim Ingham0161b492013-02-09 01:29:05 +00005532 do_resume = true;
5533 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005534
Sean Callanana46ec452012-07-11 21:31:24 +00005535 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005536 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005537
Jim Ingham0f16e732011-02-08 05:20:59 +00005538 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005539 {
Sean Callanana46ec452012-07-11 21:31:24 +00005540 if (timeout_ptr)
5541 {
Matt Kopec676a4872013-02-21 23:55:31 +00005542 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005543 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5544 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005545 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005546 else
Sean Callanana46ec452012-07-11 21:31:24 +00005547 {
5548 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5549 }
5550 }
Jim Ingham35878c42014-04-08 21:33:21 +00005551
5552#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5553 // See comment above...
5554 if (miss_first_event)
5555 {
5556 usleep(1000);
5557 miss_first_event = false;
5558 got_event = false;
5559 }
5560 else
5561#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005562 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005563
Sean Callanana46ec452012-07-11 21:31:24 +00005564 if (got_event)
5565 {
5566 if (event_sp.get())
5567 {
5568 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005569 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005570 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005571 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005572 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005573 errors.Printf ("Execution halted by user interrupt.");
5574 if (log)
5575 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005576 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005577 }
5578 else
5579 {
5580 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5581 if (log)
5582 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005583
Jim Inghamcfc09352012-07-27 23:57:19 +00005584 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005585 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005586 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005587 {
Jim Ingham0161b492013-02-09 01:29:05 +00005588 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005589 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5590 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005591 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005592 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005593 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005594 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005595 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005596 }
5597 else
5598 {
Jim Ingham0161b492013-02-09 01:29:05 +00005599 // If we were restarted, we just need to go back up to fetch another event.
5600 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005601 {
5602 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005603 {
5604 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5605 }
5606 keep_going = true;
5607 do_resume = false;
5608 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005609
Jim Inghamcfc09352012-07-27 23:57:19 +00005610 }
5611 else
5612 {
Jim Ingham0161b492013-02-09 01:29:05 +00005613 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5614 StopReason stop_reason = eStopReasonInvalid;
5615 if (stop_info_sp)
5616 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005617
Jim Ingham0161b492013-02-09 01:29:05 +00005618 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5619 // it is OUR plan that is complete?
5620 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005621 {
5622 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005623 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5624 // Now mark this plan as private so it doesn't get reported as the stop reason
5625 // after this point.
5626 if (thread_plan_sp)
5627 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005628 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005629 }
5630 else
5631 {
Jim Ingham0161b492013-02-09 01:29:05 +00005632 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005633 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005634 {
5635 if (log)
5636 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005637 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005638 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005639 {
5640 event_to_broadcast_sp = event_sp;
5641 }
Jim Ingham0161b492013-02-09 01:29:05 +00005642 }
Jim Ingham184e9812013-01-15 02:47:48 +00005643 else
Jim Ingham0161b492013-02-09 01:29:05 +00005644 {
5645 if (log)
5646 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005647 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005648 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005649 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005650 }
Jim Ingham184e9812013-01-15 02:47:48 +00005651 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005652 }
Sean Callanana46ec452012-07-11 21:31:24 +00005653 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005654 }
5655 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005656
Jim Inghamcfc09352012-07-27 23:57:19 +00005657 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005658 // This shouldn't really happen, but sometimes we do get two running events without an
5659 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005660 do_resume = false;
5661 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005662 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005663 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005664
Jim Inghamcfc09352012-07-27 23:57:19 +00005665 default:
5666 if (log)
5667 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005668
Jim Inghamcfc09352012-07-27 23:57:19 +00005669 if (stop_state == eStateExited)
5670 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005671
Sean Callananbf154da2012-08-08 17:35:10 +00005672 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005673 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005674 break;
5675 }
Sean Callanana46ec452012-07-11 21:31:24 +00005676 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005677
Sean Callanana46ec452012-07-11 21:31:24 +00005678 if (keep_going)
5679 continue;
5680 else
5681 break;
5682 }
5683 else
5684 {
5685 if (log)
5686 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005687 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005688 break;
5689 }
5690 }
5691 else
5692 {
5693 // If we didn't get an event that means we've timed out...
5694 // We will interrupt the process here. Depending on what we were asked to do we will
5695 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005696
Sean Callanana46ec452012-07-11 21:31:24 +00005697 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005698 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005699 {
Jim Ingham0161b492013-02-09 01:29:05 +00005700 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005701 {
5702 if (timeout_usec != 0)
5703 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005704 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005705 "running for %" PRIu32 " usec with all threads enabled.",
5706 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005707 }
5708 else
5709 {
5710 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005711 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005712 }
5713 }
Sean Callanana46ec452012-07-11 21:31:24 +00005714 else
5715 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005716 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005717 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005718 }
5719 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005720 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005721 "abandoning execution.",
5722 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005723 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005724
Jim Ingham0161b492013-02-09 01:29:05 +00005725 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5726 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5727 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5728 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5729 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005730
Jim Ingham0161b492013-02-09 01:29:05 +00005731 bool back_to_top = true;
5732 uint32_t try_halt_again = 0;
5733 bool do_halt = true;
5734 const uint32_t num_retries = 5;
5735 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005736 {
Jim Ingham0161b492013-02-09 01:29:05 +00005737 Error halt_error;
5738 if (do_halt)
5739 {
5740 if (log)
5741 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5742 halt_error = Halt();
5743 }
5744 if (halt_error.Success())
5745 {
5746 if (log)
5747 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005748
Jim Ingham0161b492013-02-09 01:29:05 +00005749 real_timeout = TimeValue::Now();
5750 real_timeout.OffsetWithMicroSeconds(500000);
5751
5752 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005753
Jim Ingham0161b492013-02-09 01:29:05 +00005754 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005755 {
Jim Ingham0161b492013-02-09 01:29:05 +00005756 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5757 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005758 {
Jim Ingham0161b492013-02-09 01:29:05 +00005759 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5760 if (stop_state == lldb::eStateStopped
5761 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5762 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005763 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005764
Jim Ingham0161b492013-02-09 01:29:05 +00005765 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005766 {
Jim Ingham0161b492013-02-09 01:29:05 +00005767 // Between the time we initiated the Halt and the time we delivered it, the process could have
5768 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005769
Jim Ingham0161b492013-02-09 01:29:05 +00005770 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5771 {
5772 if (log)
5773 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5774 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005775 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005776 back_to_top = false;
5777 break;
5778 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005779
Jim Ingham0161b492013-02-09 01:29:05 +00005780 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5781 {
5782 if (log)
5783 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5784 "Exiting wait loop.");
5785 try_halt_again++;
5786 do_halt = false;
5787 continue;
5788 }
Sean Callanana46ec452012-07-11 21:31:24 +00005789
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005790 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005791 {
5792 if (log)
5793 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005794 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005795 back_to_top = false;
5796 break;
5797 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005798
Jim Ingham0161b492013-02-09 01:29:05 +00005799 if (before_first_timeout)
5800 {
5801 // Set all the other threads to run, and return to the top of the loop, which will continue;
5802 before_first_timeout = false;
5803 thread_plan_sp->SetStopOthers (false);
5804 if (log)
5805 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005806
Jim Ingham0161b492013-02-09 01:29:05 +00005807 back_to_top = true;
5808 break;
5809 }
5810 else
5811 {
5812 // Running all threads failed, so return Interrupted.
5813 if (log)
5814 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005815 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005816 back_to_top = false;
5817 break;
5818 }
Sean Callanana46ec452012-07-11 21:31:24 +00005819 }
5820 }
5821 else
Jim Ingham0161b492013-02-09 01:29:05 +00005822 { if (log)
5823 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5824 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005825 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005826 back_to_top = false;
5827 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005828 }
5829 }
Jim Ingham0161b492013-02-09 01:29:05 +00005830 else
5831 {
5832 try_halt_again++;
5833 continue;
5834 }
Sean Callanana46ec452012-07-11 21:31:24 +00005835 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005836
Jim Ingham0161b492013-02-09 01:29:05 +00005837 if (!back_to_top || try_halt_again > num_retries)
5838 break;
5839 else
5840 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005841 }
Sean Callanana46ec452012-07-11 21:31:24 +00005842 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005843
Sean Callanana46ec452012-07-11 21:31:24 +00005844 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
Zachary Turneracee96a2014-09-23 18:32:09 +00005845 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005846 {
5847 StopPrivateStateThread();
5848 Error error;
5849 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005850 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005851 {
5852 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5853 }
Jason Molenda76513fd2014-10-15 23:39:31 +00005854 if (old_state != eStateInvalid)
5855 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00005856 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005857
Jim Ingham184e9812013-01-15 02:47:48 +00005858 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5859 // could happen:
5860 // 1) The execution successfully completed
5861 // 2) We hit a breakpoint, and ignore_breakpoints was true
5862 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005863 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5864 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005865
Jim Ingham8646d3c2014-05-05 02:47:44 +00005866 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005867 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005868 {
5869 thread_plan_sp->RestoreThreadState();
5870 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005871
Sean Callanana46ec452012-07-11 21:31:24 +00005872 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005873 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005874 {
5875 if (log)
5876 {
5877 StreamString s;
5878 if (event_sp)
5879 event_sp->Dump (&s);
5880 else
5881 {
5882 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5883 }
5884
5885 StreamString ts;
5886
5887 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005888
Sean Callanana46ec452012-07-11 21:31:24 +00005889 do
5890 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005891 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005892 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005893 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005894 break;
5895 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005896 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005897 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005898 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005899 break;
5900 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005901 else
Sean Callanana46ec452012-07-11 21:31:24 +00005902 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005903 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5904
5905 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005906 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005907 event_explanation = "<no event data>";
5908 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005909 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005910
Jim Inghamcfc09352012-07-27 23:57:19 +00005911 Process *process = event_data->GetProcessSP().get();
5912
5913 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005914 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005915 event_explanation = "<no process>";
5916 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005917 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005918
Jim Inghamcfc09352012-07-27 23:57:19 +00005919 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005920
Jim Inghamcfc09352012-07-27 23:57:19 +00005921 uint32_t num_threads = thread_list.GetSize();
5922 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005923
Jim Inghamcfc09352012-07-27 23:57:19 +00005924 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005925
Jim Inghamcfc09352012-07-27 23:57:19 +00005926 for (thread_index = 0;
5927 thread_index < num_threads;
5928 ++thread_index)
5929 {
5930 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005931
Jim Inghamcfc09352012-07-27 23:57:19 +00005932 if (!thread)
5933 {
5934 ts.Printf("<?> ");
5935 continue;
5936 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005937
Daniel Malead01b2952012-11-29 21:49:15 +00005938 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005939 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005940
Jim Inghamcfc09352012-07-27 23:57:19 +00005941 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005942 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005943 else
5944 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005945
Jim Inghamcfc09352012-07-27 23:57:19 +00005946 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5947 if (stop_info_sp)
5948 {
5949 const char *stop_desc = stop_info_sp->GetDescription();
5950 if (stop_desc)
5951 ts.PutCString (stop_desc);
5952 }
5953 ts.Printf(">");
5954 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005955
Jim Inghamcfc09352012-07-27 23:57:19 +00005956 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005957 }
Sean Callanana46ec452012-07-11 21:31:24 +00005958 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005959
Jim Inghamcfc09352012-07-27 23:57:19 +00005960 if (event_explanation)
5961 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005962 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005963 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5964 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005965
Jim Inghame4483cf2013-09-27 01:13:01 +00005966 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005967 {
5968 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005969 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5970 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005971 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5972 thread_plan_sp->SetPrivate (orig_plan_private);
5973 }
5974 else
5975 {
5976 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005977 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5978 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005979 }
5980 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005981 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005982 {
5983 if (log)
5984 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005985
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005986 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005987 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005988 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005989 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005990 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005991 }
5992 else
5993 {
Sean Callanana46ec452012-07-11 21:31:24 +00005994 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005995 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005996 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005997 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005998 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005999 }
6000 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6001 {
6002 if (log)
6003 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006004 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006005 }
6006 else
6007 {
6008 if (log)
6009 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006010 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006011 {
6012 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006013 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006014 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6015 thread_plan_sp->SetPrivate (orig_plan_private);
6016 }
6017 }
6018 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006019
Sean Callanana46ec452012-07-11 21:31:24 +00006020 // Thread we ran the function in may have gone away because we ran the target
6021 // Check that it's still there, and if it is put it back in the context. Also restore the
6022 // frame in the context if it is still present.
6023 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6024 if (thread)
6025 {
6026 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6027 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006028
Sean Callanana46ec452012-07-11 21:31:24 +00006029 // Also restore the current process'es selected frame & thread, since this function calling may
6030 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006031
Sean Callanana46ec452012-07-11 21:31:24 +00006032 if (selected_tid != LLDB_INVALID_THREAD_ID)
6033 {
6034 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6035 {
6036 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006037 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006038 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006039 if (old_frame_sp)
6040 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006041 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006042 }
6043 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006044
Sean Callanana46ec452012-07-11 21:31:24 +00006045 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006046
Sean Callanana46ec452012-07-11 21:31:24 +00006047 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006048 {
Sean Callanana46ec452012-07-11 21:31:24 +00006049 if (log)
6050 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6051 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006052 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006053
Jim Inghamf48169b2010-11-30 02:22:11 +00006054 return return_value;
6055}
6056
6057const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006058Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006059{
6060 const char *result_name;
6061
6062 switch (result)
6063 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006064 case eExpressionCompleted:
6065 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006066 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006067 case eExpressionDiscarded:
6068 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006069 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006070 case eExpressionInterrupted:
6071 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006072 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006073 case eExpressionHitBreakpoint:
6074 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006075 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006076 case eExpressionSetupError:
6077 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006078 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006079 case eExpressionParseError:
6080 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006081 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006082 case eExpressionResultUnavailable:
6083 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006084 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006085 case eExpressionTimedOut:
6086 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006087 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006088 case eExpressionStoppedForDebug:
6089 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006090 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006091 }
6092 return result_name;
6093}
6094
Greg Clayton7260f622011-04-18 08:33:37 +00006095void
6096Process::GetStatus (Stream &strm)
6097{
6098 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006099 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006100 {
6101 if (state == eStateExited)
6102 {
6103 int exit_status = GetExitStatus();
6104 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006105 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006106 GetID(),
6107 exit_status,
6108 exit_status,
6109 exit_description ? exit_description : "");
6110 }
6111 else
6112 {
6113 if (state == eStateConnected)
6114 strm.Printf ("Connected to remote target.\n");
6115 else
Daniel Malead01b2952012-11-29 21:49:15 +00006116 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006117 }
6118 }
6119 else
6120 {
Daniel Malead01b2952012-11-29 21:49:15 +00006121 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006122 }
6123}
6124
6125size_t
6126Process::GetThreadStatus (Stream &strm,
6127 bool only_threads_with_stop_reason,
6128 uint32_t start_frame,
6129 uint32_t num_frames,
6130 uint32_t num_frames_with_source)
6131{
6132 size_t num_thread_infos_dumped = 0;
6133
Jim Ingham4a65fb12014-03-07 11:20:03 +00006134 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6135 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6136 // ID's, and look them up one by one:
6137
6138 uint32_t num_threads;
6139 std::vector<uint32_t> thread_index_array;
6140 //Scope for thread list locker;
6141 {
6142 Mutex::Locker locker (GetThreadList().GetMutex());
6143 ThreadList &curr_thread_list = GetThreadList();
6144 num_threads = curr_thread_list.GetSize();
6145 uint32_t idx;
6146 thread_index_array.resize(num_threads);
6147 for (idx = 0; idx < num_threads; ++idx)
6148 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
6149 }
6150
Greg Clayton7260f622011-04-18 08:33:37 +00006151 for (uint32_t i = 0; i < num_threads; i++)
6152 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006153 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
6154 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006155 {
6156 if (only_threads_with_stop_reason)
6157 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006158 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006159 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006160 continue;
6161 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006162 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006163 start_frame,
6164 num_frames,
6165 num_frames_with_source);
6166 ++num_thread_infos_dumped;
6167 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006168 else
6169 {
6170 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6171 if (log)
6172 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6173
6174 }
Greg Clayton7260f622011-04-18 08:33:37 +00006175 }
6176 return num_thread_infos_dumped;
6177}
6178
Greg Claytona9f40ad2012-02-22 04:37:26 +00006179void
6180Process::AddInvalidMemoryRegion (const LoadRange &region)
6181{
6182 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6183}
6184
6185bool
6186Process::RemoveInvalidMemoryRange (const LoadRange &region)
6187{
6188 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6189}
6190
Jim Ingham372787f2012-04-07 00:00:41 +00006191void
6192Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6193{
6194 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6195}
6196
6197bool
6198Process::RunPreResumeActions ()
6199{
6200 bool result = true;
6201 while (!m_pre_resume_actions.empty())
6202 {
6203 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6204 m_pre_resume_actions.pop_back();
6205 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006206 if (result == true)
6207 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006208 }
6209 return result;
6210}
6211
6212void
6213Process::ClearPreResumeActions ()
6214{
6215 m_pre_resume_actions.clear();
6216}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006217
Greg Claytonfa559e52012-05-18 02:38:05 +00006218void
6219Process::Flush ()
6220{
6221 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006222 m_extended_thread_list.Flush();
6223 m_extended_thread_stop_id = 0;
6224 m_queue_list.Clear();
6225 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006226}
Greg Clayton90ba8112012-12-05 00:16:59 +00006227
6228void
6229Process::DidExec ()
6230{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006231 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6232 if (log)
6233 log->Printf ("Process::%s()", __FUNCTION__);
6234
Greg Clayton90ba8112012-12-05 00:16:59 +00006235 Target &target = GetTarget();
6236 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006237 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006238 m_dynamic_checkers_ap.reset();
6239 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006240 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006241 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006242 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006243 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006244 m_image_tokens.clear();
6245 m_allocated_memory_cache.Clear();
6246 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006247 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006248 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006249 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006250 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006251 DoDidExec();
6252 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006253 // Flush the process (threads and all stack frames) after running CompleteAttach()
6254 // in case the dynamic loader loaded things in new locations.
6255 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006256
6257 // After we figure out what was loaded/unloaded in CompleteAttach,
6258 // we need to let the target know so it can do any cleanup it needs to.
6259 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006260}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006261
Jim Ingham1460e4b2014-01-10 23:46:59 +00006262addr_t
6263Process::ResolveIndirectFunction(const Address *address, Error &error)
6264{
6265 if (address == nullptr)
6266 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006267 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006268 return LLDB_INVALID_ADDRESS;
6269 }
6270
6271 addr_t function_addr = LLDB_INVALID_ADDRESS;
6272
6273 addr_t addr = address->GetLoadAddress(&GetTarget());
6274 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6275 if (iter != m_resolved_indirect_addresses.end())
6276 {
6277 function_addr = (*iter).second;
6278 }
6279 else
6280 {
6281 if (!InferiorCall(this, address, function_addr))
6282 {
6283 Symbol *symbol = address->CalculateSymbolContextSymbol();
6284 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6285 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6286 function_addr = LLDB_INVALID_ADDRESS;
6287 }
6288 else
6289 {
6290 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6291 }
6292 }
6293 return function_addr;
6294}
6295
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006296void
6297Process::ModulesDidLoad (ModuleList &module_list)
6298{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006299 SystemRuntime *sys_runtime = GetSystemRuntime();
6300 if (sys_runtime)
6301 {
6302 sys_runtime->ModulesDidLoad (module_list);
6303 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006304
Kuba Breckaafdf8422014-10-10 23:43:03 +00006305 GetJITLoaders().ModulesDidLoad (module_list);
6306
6307 // Give runtimes a chance to be created.
6308 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6309
6310 // Tell runtimes about new modules.
6311 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6312 {
6313 InstrumentationRuntimeSP runtime = pos->second;
6314 runtime->ModulesDidLoad(module_list);
6315 }
6316
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006317}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006318
6319ThreadCollectionSP
6320Process::GetHistoryThreads(lldb::addr_t addr)
6321{
6322 ThreadCollectionSP threads;
6323
6324 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6325
6326 if (! memory_history.get()) {
6327 return threads;
6328 }
6329
6330 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6331
6332 return threads;
6333}
Kuba Brecka63927542014-10-11 01:59:32 +00006334
6335InstrumentationRuntimeSP
6336Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6337{
6338 InstrumentationRuntimeCollection::iterator pos;
6339 pos = m_instrumentation_runtimes.find (type);
6340 if (pos == m_instrumentation_runtimes.end())
6341 {
6342 return InstrumentationRuntimeSP();
6343 }
6344 else
6345 return (*pos).second;
6346}