blob: f5650112f4dd33a0778f51e7c35eb0e36efb517a [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),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000722 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000723 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000724 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000725 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000726 m_destroy_in_process (false),
727 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000729 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000730
Greg Clayton5160ce52013-03-27 23:08:40 +0000731 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000733 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734
Todd Fiala4ceced32014-08-29 17:35:57 +0000735 if (!m_unix_signals_sp)
736 m_unix_signals_sp.reset (new UnixSignals ());
737
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000738 SetEventName (eBroadcastBitStateChanged, "state-changed");
739 SetEventName (eBroadcastBitInterrupt, "interrupt");
740 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
741 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000742 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000743
Greg Clayton35a4cc52012-10-29 20:52:08 +0000744 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
745 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
746 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
747
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748 listener.StartListeningForEvents (this,
749 eBroadcastBitStateChanged |
750 eBroadcastBitInterrupt |
751 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000752 eBroadcastBitSTDERR |
753 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754
755 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000756 eBroadcastBitStateChanged |
757 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758
759 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
760 eBroadcastInternalStateControlStop |
761 eBroadcastInternalStateControlPause |
762 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000763 // We need something valid here, even if just the default UnixSignalsSP.
764 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765}
766
767//----------------------------------------------------------------------
768// Destructor
769//----------------------------------------------------------------------
770Process::~Process()
771{
Greg Clayton5160ce52013-03-27 23:08:40 +0000772 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000773 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000774 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000776
777 // ThreadList::Clear() will try to acquire this process's mutex, so
778 // explicitly clear the thread list here to ensure that the mutex
779 // is not destroyed before the thread list.
780 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781}
782
Greg Clayton67cc0632012-08-22 17:17:09 +0000783const ProcessPropertiesSP &
784Process::GetGlobalProperties()
785{
786 static ProcessPropertiesSP g_settings_sp;
787 if (!g_settings_sp)
788 g_settings_sp.reset (new ProcessProperties (true));
789 return g_settings_sp;
790}
791
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792void
793Process::Finalize()
794{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000795 switch (GetPrivateState())
796 {
797 case eStateConnected:
798 case eStateAttaching:
799 case eStateLaunching:
800 case eStateStopped:
801 case eStateRunning:
802 case eStateStepping:
803 case eStateCrashed:
804 case eStateSuspended:
805 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000806 {
807 // FIXME: This will have to be a process setting:
808 bool keep_stopped = false;
809 Detach(keep_stopped);
810 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000811 else
812 Destroy();
813 break;
814
815 case eStateInvalid:
816 case eStateUnloaded:
817 case eStateDetached:
818 case eStateExited:
819 break;
820 }
821
Greg Clayton1ed54f52011-10-01 00:45:15 +0000822 // Clear our broadcaster before we proceed with destroying
823 Broadcaster::Clear();
824
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825 // Do any cleanup needed prior to being destructed... Subclasses
826 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000827
828 // We need to destroy the loader before the derived Process class gets destroyed
829 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000830 m_dynamic_checkers_ap.reset();
831 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000832 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000833 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000834 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000835 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000836 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000837 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000838 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000839 m_queue_list.Clear();
840 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000841 std::vector<Notifications> empty_notifications;
842 m_notifications.swap(empty_notifications);
843 m_image_tokens.clear();
844 m_memory_cache.Clear();
845 m_allocated_memory_cache.Clear();
846 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000847 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000848 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000849//#ifdef LLDB_CONFIGURATION_DEBUG
850// StreamFile s(stdout, false);
851// EventSP event_sp;
852// while (m_private_state_listener.GetNextEvent(event_sp))
853// {
854// event_sp->Dump (&s);
855// s.EOL();
856// }
857//#endif
858 // We have to be very careful here as the m_private_state_listener might
859 // contain events that have ProcessSP values in them which can keep this
860 // process around forever. These events need to be cleared out.
861 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000862 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
863 m_public_run_lock.SetStopped();
864 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
865 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000866 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867}
868
869void
870Process::RegisterNotificationCallbacks (const Notifications& callbacks)
871{
872 m_notifications.push_back(callbacks);
873 if (callbacks.initialize != NULL)
874 callbacks.initialize (callbacks.baton, this);
875}
876
877bool
878Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
879{
880 std::vector<Notifications>::iterator pos, end = m_notifications.end();
881 for (pos = m_notifications.begin(); pos != end; ++pos)
882 {
883 if (pos->baton == callbacks.baton &&
884 pos->initialize == callbacks.initialize &&
885 pos->process_state_changed == callbacks.process_state_changed)
886 {
887 m_notifications.erase(pos);
888 return true;
889 }
890 }
891 return false;
892}
893
894void
895Process::SynchronouslyNotifyStateChanged (StateType state)
896{
897 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
898 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
899 {
900 if (notification_pos->process_state_changed)
901 notification_pos->process_state_changed (notification_pos->baton, this, state);
902 }
903}
904
905// FIXME: We need to do some work on events before the general Listener sees them.
906// For instance if we are continuing from a breakpoint, we need to ensure that we do
907// the little "insert real insn, step & stop" trick. But we can't do that when the
908// event is delivered by the broadcaster - since that is done on the thread that is
909// waiting for new events, so if we needed more than one event for our handling, we would
910// stall. So instead we do it when we fetch the event off of the queue.
911//
912
913StateType
914Process::GetNextEvent (EventSP &event_sp)
915{
916 StateType state = eStateInvalid;
917
918 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
919 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
920
921 return state;
922}
923
Todd Fialaa3b89e22014-08-12 14:33:19 +0000924bool
925Process::SyncIOHandler (uint64_t timeout_msec)
926{
927 bool timed_out = false;
928
929 // don't sync (potentially context switch) in case where there is no process IO
930 if (m_process_input_reader)
931 {
932 TimeValue timeout = TimeValue::Now();
933 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
934
935 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
936
937 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
938 if(log)
939 {
940 if(timed_out)
941 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
942 else
943 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
944 }
945
Shawn Best1ded74a2014-10-08 01:50:37 +0000946 // reset sync one-shot so it will be ready for next launch
Todd Fialaa3b89e22014-08-12 14:33:19 +0000947 m_iohandler_sync.SetValue(false, eBroadcastNever);
948 }
949
950 return !timed_out;
951}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952
953StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000954Process::WaitForProcessToStop (const TimeValue *timeout,
955 EventSP *event_sp_ptr,
956 bool wait_always,
957 Listener *hijack_listener,
958 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959{
Jim Ingham4b536182011-08-09 02:12:22 +0000960 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
961 // We have to actually check each event, and in the case of a stopped event check the restarted flag
962 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000963 if (event_sp_ptr)
964 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000965 StateType state = GetState();
966 // If we are exited or detached, we won't ever get back to any
967 // other valid state...
968 if (state == eStateDetached || state == eStateExited)
969 return state;
970
Daniel Malea9e9919f2013-10-09 16:56:28 +0000971 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
972 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000973 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
974 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000975
976 if (!wait_always &&
977 StateIsStoppedState(state, true) &&
978 StateIsStoppedState(GetPrivateState(), true)) {
979 if (log)
980 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
981 __FUNCTION__);
982 return state;
983 }
984
Jim Ingham4b536182011-08-09 02:12:22 +0000985 while (state != eStateInvalid)
986 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000987 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000988 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000989 if (event_sp_ptr && event_sp)
990 *event_sp_ptr = event_sp;
991
Greg Claytondc6224e2014-10-21 01:00:42 +0000992 bool pop_process_io_handler = hijack_listener != NULL;
993 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
994
Jim Ingham4b536182011-08-09 02:12:22 +0000995 switch (state)
996 {
997 case eStateCrashed:
998 case eStateDetached:
999 case eStateExited:
1000 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001001 // We need to toggle the run lock as this won't get done in
1002 // SetPublicState() if the process is hijacked.
1003 if (hijack_listener)
1004 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001005 return state;
1006 case eStateStopped:
1007 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1008 continue;
1009 else
Greg Clayton44d93782014-01-27 23:43:24 +00001010 {
1011 // We need to toggle the run lock as this won't get done in
1012 // SetPublicState() if the process is hijacked.
1013 if (hijack_listener)
1014 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001015 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001016 }
Jim Ingham4b536182011-08-09 02:12:22 +00001017 default:
1018 continue;
1019 }
1020 }
1021 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022}
1023
Greg Claytondc6224e2014-10-21 01:00:42 +00001024bool
1025Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1026 Stream *stream,
1027 bool &pop_process_io_handler)
1028{
1029 const bool handle_pop = pop_process_io_handler == true;
1030
1031 pop_process_io_handler = false;
1032 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1033
1034 if (!process_sp)
1035 return false;
1036
1037 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1038 if (event_state == eStateInvalid)
1039 return false;
1040
1041 switch (event_state)
1042 {
1043 case eStateInvalid:
1044 case eStateUnloaded:
1045 case eStateConnected:
1046 case eStateAttaching:
1047 case eStateLaunching:
1048 case eStateStepping:
1049 case eStateDetached:
1050 {
1051 if (stream)
1052 stream->Printf ("Process %" PRIu64 " %s\n",
1053 process_sp->GetID(),
1054 StateAsCString (event_state));
1055
1056 if (event_state == eStateDetached)
1057 pop_process_io_handler = true;
1058 }
1059 break;
1060
1061 case eStateRunning:
1062 // Don't be chatty when we run...
1063 break;
1064
1065 case eStateExited:
1066 if (stream)
1067 process_sp->GetStatus(*stream);
1068 pop_process_io_handler = true;
1069 break;
1070
1071 case eStateStopped:
1072 case eStateCrashed:
1073 case eStateSuspended:
1074 // Make sure the program hasn't been auto-restarted:
1075 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1076 {
1077 if (stream)
1078 {
1079 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1080 if (num_reasons > 0)
1081 {
1082 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1083 if (num_reasons == 1)
1084 {
1085 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1086 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1087 process_sp->GetID(),
1088 reason ? reason : "<UNKNOWN REASON>");
1089 }
1090 else
1091 {
1092 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1093 process_sp->GetID());
1094
1095
1096 for (size_t i = 0; i < num_reasons; i++)
1097 {
1098 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1099 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1100 }
1101 }
1102 }
1103 }
1104 }
1105 else
1106 {
1107 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1108 {
1109 ThreadList &thread_list = process_sp->GetThreadList();
1110 Mutex::Locker locker (thread_list.GetMutex());
1111
1112 ThreadSP curr_thread (thread_list.GetSelectedThread());
1113 ThreadSP thread;
1114 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1115 if (curr_thread)
1116 curr_thread_stop_reason = curr_thread->GetStopReason();
1117 if (!curr_thread ||
1118 !curr_thread->IsValid() ||
1119 curr_thread_stop_reason == eStopReasonInvalid ||
1120 curr_thread_stop_reason == eStopReasonNone)
1121 {
1122 // Prefer a thread that has just completed its plan over another thread as current thread.
1123 ThreadSP plan_thread;
1124 ThreadSP other_thread;
1125 const size_t num_threads = thread_list.GetSize();
1126 size_t i;
1127 for (i = 0; i < num_threads; ++i)
1128 {
1129 thread = thread_list.GetThreadAtIndex(i);
1130 StopReason thread_stop_reason = thread->GetStopReason();
1131 switch (thread_stop_reason)
1132 {
1133 case eStopReasonInvalid:
1134 case eStopReasonNone:
1135 break;
1136
1137 case eStopReasonTrace:
1138 case eStopReasonBreakpoint:
1139 case eStopReasonWatchpoint:
1140 case eStopReasonSignal:
1141 case eStopReasonException:
1142 case eStopReasonExec:
1143 case eStopReasonThreadExiting:
1144 case eStopReasonInstrumentation:
1145 if (!other_thread)
1146 other_thread = thread;
1147 break;
1148 case eStopReasonPlanComplete:
1149 if (!plan_thread)
1150 plan_thread = thread;
1151 break;
1152 }
1153 }
1154 if (plan_thread)
1155 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1156 else if (other_thread)
1157 thread_list.SetSelectedThreadByID (other_thread->GetID());
1158 else
1159 {
1160 if (curr_thread && curr_thread->IsValid())
1161 thread = curr_thread;
1162 else
1163 thread = thread_list.GetThreadAtIndex(0);
1164
1165 if (thread)
1166 thread_list.SetSelectedThreadByID (thread->GetID());
1167 }
1168 }
1169 }
1170 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1171 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1172 // have a hard time restarting the process.
1173 if (stream)
1174 {
1175 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1176 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1177 {
1178 const bool only_threads_with_stop_reason = true;
1179 const uint32_t start_frame = 0;
1180 const uint32_t num_frames = 1;
1181 const uint32_t num_frames_with_source = 1;
1182 process_sp->GetStatus(*stream);
1183 process_sp->GetThreadStatus (*stream,
1184 only_threads_with_stop_reason,
1185 start_frame,
1186 num_frames,
1187 num_frames_with_source);
1188 }
1189 else
1190 {
1191 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1192 if (target_idx != UINT32_MAX)
1193 stream->Printf ("Target %d: (", target_idx);
1194 else
1195 stream->Printf ("Target <unknown index>: (");
1196 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1197 stream->Printf (") stopped.\n");
1198 }
1199 }
1200
1201 // Pop the process IO handler
1202 pop_process_io_handler = true;
1203 }
1204 break;
1205 }
1206
1207 if (handle_pop && pop_process_io_handler)
1208 process_sp->PopProcessIOHandler();
1209
1210 return true;
1211}
1212
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001213
1214StateType
1215Process::WaitForState
1216(
1217 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001218 const StateType *match_states,
1219 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001220)
1221{
1222 EventSP event_sp;
1223 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001224 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001225 while (state != eStateInvalid)
1226 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001227 // If we are exited or detached, we won't ever get back to any
1228 // other valid state...
1229 if (state == eStateDetached || state == eStateExited)
1230 return state;
1231
Greg Clayton44d93782014-01-27 23:43:24 +00001232 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001233
1234 for (i=0; i<num_match_states; ++i)
1235 {
1236 if (match_states[i] == state)
1237 return state;
1238 }
1239 }
1240 return state;
1241}
1242
Jim Ingham30f9b212010-10-11 23:53:14 +00001243bool
1244Process::HijackProcessEvents (Listener *listener)
1245{
1246 if (listener != NULL)
1247 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001248 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001249 }
1250 else
1251 return false;
1252}
1253
1254void
1255Process::RestoreProcessEvents ()
1256{
1257 RestoreBroadcaster();
1258}
1259
Jim Ingham0f16e732011-02-08 05:20:59 +00001260bool
1261Process::HijackPrivateProcessEvents (Listener *listener)
1262{
1263 if (listener != NULL)
1264 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001265 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001266 }
1267 else
1268 return false;
1269}
1270
1271void
1272Process::RestorePrivateProcessEvents ()
1273{
1274 m_private_state_broadcaster.RestoreBroadcaster();
1275}
1276
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001277StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001278Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279{
Greg Clayton5160ce52013-03-27 23:08:40 +00001280 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281
1282 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001283 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1284 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001285
Greg Clayton44d93782014-01-27 23:43:24 +00001286 Listener *listener = hijack_listener;
1287 if (listener == NULL)
1288 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001289
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001290 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001291 if (listener->WaitForEventForBroadcasterWithType (timeout,
1292 this,
1293 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1294 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001295 {
1296 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1297 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1298 else if (log)
1299 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1300 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301
1302 if (log)
1303 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001304 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 StateAsCString(state));
1306 return state;
1307}
1308
1309Event *
1310Process::PeekAtStateChangedEvents ()
1311{
Greg Clayton5160ce52013-03-27 23:08:40 +00001312 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313
1314 if (log)
1315 log->Printf ("Process::%s...", __FUNCTION__);
1316
1317 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001318 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1319 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 if (log)
1321 {
1322 if (event_ptr)
1323 {
1324 log->Printf ("Process::%s (event_ptr) => %s",
1325 __FUNCTION__,
1326 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1327 }
1328 else
1329 {
1330 log->Printf ("Process::%s no events found",
1331 __FUNCTION__);
1332 }
1333 }
1334 return event_ptr;
1335}
1336
1337StateType
1338Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1339{
Greg Clayton5160ce52013-03-27 23:08:40 +00001340 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341
1342 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001343 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1344 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001345
1346 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001347 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1348 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001349 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001350 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001351 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1352 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353
1354 // This is a bit of a hack, but when we wait here we could very well return
1355 // to the command-line, and that could disable the log, which would render the
1356 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001358 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1359 __FUNCTION__, static_cast<const void *>(timeout),
1360 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361 return state;
1362}
1363
1364bool
1365Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1366{
Greg Clayton5160ce52013-03-27 23:08:40 +00001367 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368
1369 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001370 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1371 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372
1373 if (control_only)
1374 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1375 else
1376 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1377}
1378
1379bool
1380Process::IsRunning () const
1381{
1382 return StateIsRunningState (m_public_state.GetValue());
1383}
1384
1385int
1386Process::GetExitStatus ()
1387{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001388 Mutex::Locker locker (m_exit_status_mutex);
1389
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390 if (m_public_state.GetValue() == eStateExited)
1391 return m_exit_status;
1392 return -1;
1393}
1394
Greg Clayton85851dd2010-12-04 00:10:17 +00001395
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001396const char *
1397Process::GetExitDescription ()
1398{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001399 Mutex::Locker locker (m_exit_status_mutex);
1400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1402 return m_exit_string.c_str();
1403 return NULL;
1404}
1405
Greg Clayton6779606a2011-01-22 23:43:18 +00001406bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001407Process::SetExitStatus (int status, const char *cstr)
1408{
Greg Clayton5160ce52013-03-27 23:08:40 +00001409 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001410 if (log)
1411 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1412 status, status,
1413 cstr ? "\"" : "",
1414 cstr ? cstr : "NULL",
1415 cstr ? "\"" : "");
1416
Greg Clayton6779606a2011-01-22 23:43:18 +00001417 // We were already in the exited state
1418 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001419 {
Greg Clayton385d6032011-01-26 23:47:29 +00001420 if (log)
1421 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001422 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001423 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001424
Todd Fiala7b0917a2014-09-15 20:07:33 +00001425 // use a mutex to protect the status and string during updating
1426 {
1427 Mutex::Locker locker (m_exit_status_mutex);
1428
1429 m_exit_status = status;
1430 if (cstr)
1431 m_exit_string = cstr;
1432 else
1433 m_exit_string.clear();
1434 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001435
Greg Clayton6779606a2011-01-22 23:43:18 +00001436 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001437
Greg Clayton6779606a2011-01-22 23:43:18 +00001438 SetPrivateState (eStateExited);
1439 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001440}
1441
1442// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001443// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444// found in the global target list (we want to be completely sure that the
1445// lldb_private::Process doesn't go away before we can deliver the signal.
1446bool
Greg Claytone4e45922011-11-16 05:37:56 +00001447Process::SetProcessExitStatus (void *callback_baton,
1448 lldb::pid_t pid,
1449 bool exited,
1450 int signo, // Zero for no signal
1451 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001452)
1453{
Greg Clayton5160ce52013-03-27 23:08:40 +00001454 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001455 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001456 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001457 callback_baton,
1458 pid,
1459 exited,
1460 signo,
1461 exit_status);
1462
1463 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464 {
Greg Clayton66111032010-06-23 01:19:29 +00001465 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001466 if (target_sp)
1467 {
1468 ProcessSP process_sp (target_sp->GetProcessSP());
1469 if (process_sp)
1470 {
1471 const char *signal_cstr = NULL;
1472 if (signo)
1473 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1474
1475 process_sp->SetExitStatus (exit_status, signal_cstr);
1476 }
1477 }
1478 return true;
1479 }
1480 return false;
1481}
1482
1483
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001484void
1485Process::UpdateThreadListIfNeeded ()
1486{
1487 const uint32_t stop_id = GetStopID();
1488 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1489 {
Greg Clayton2637f822011-11-17 01:23:07 +00001490 const StateType state = GetPrivateState();
1491 if (StateIsStoppedState (state, true))
1492 {
1493 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001494 // m_thread_list does have its own mutex, but we need to
1495 // hold onto the mutex between the call to UpdateThreadList(...)
1496 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001497 ThreadList &old_thread_list = m_thread_list;
1498 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001499 ThreadList new_thread_list(this);
1500 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001501 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001502 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001503 {
Jim Ingham09437922013-03-01 20:04:25 +00001504 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1505 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1506 // shutting us down, causing a deadlock.
1507 if (!m_destroy_in_process)
1508 {
1509 OperatingSystem *os = GetOperatingSystem ();
1510 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001511 {
1512 // Clear any old backing threads where memory threads might have been
1513 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001514 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001515 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001516 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001517
1518 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001519 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1520 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1521 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 +00001522 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001523 else
1524 {
1525 // No OS plug-in, the new thread list is the same as the real thread list
1526 new_thread_list = real_thread_list;
1527 }
Jim Ingham09437922013-03-01 20:04:25 +00001528 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001529
1530 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001531 m_thread_list.Update (new_thread_list);
1532 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001533
Jason Molenda4ff13262013-11-20 00:31:38 +00001534 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1535 {
1536 // Clear any extended threads that we may have accumulated previously
1537 m_extended_thread_list.Clear();
1538 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001539
1540 m_queue_list.Clear();
1541 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001542 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001543 }
Greg Clayton2637f822011-11-17 01:23:07 +00001544 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001545 }
1546}
1547
Jason Molenda5e8dce42013-12-13 00:29:16 +00001548void
1549Process::UpdateQueueListIfNeeded ()
1550{
1551 if (m_system_runtime_ap.get())
1552 {
1553 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1554 {
1555 const StateType state = GetPrivateState();
1556 if (StateIsStoppedState (state, true))
1557 {
1558 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1559 m_queue_list_stop_id = GetLastNaturalStopID();
1560 }
1561 }
1562 }
1563}
1564
Greg Claytona4d87472013-01-18 23:41:08 +00001565ThreadSP
1566Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1567{
1568 OperatingSystem *os = GetOperatingSystem ();
1569 if (os)
1570 return os->CreateThread(tid, context);
1571 return ThreadSP();
1572}
1573
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001574uint32_t
1575Process::GetNextThreadIndexID (uint64_t thread_id)
1576{
1577 return AssignIndexIDToThread(thread_id);
1578}
1579
1580bool
1581Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1582{
1583 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1584 if (iterator == m_thread_id_to_index_id_map.end())
1585 {
1586 return false;
1587 }
1588 else
1589 {
1590 return true;
1591 }
1592}
1593
1594uint32_t
1595Process::AssignIndexIDToThread(uint64_t thread_id)
1596{
1597 uint32_t result = 0;
1598 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1599 if (iterator == m_thread_id_to_index_id_map.end())
1600 {
1601 result = ++m_thread_index_id;
1602 m_thread_id_to_index_id_map[thread_id] = result;
1603 }
1604 else
1605 {
1606 result = iterator->second;
1607 }
1608
1609 return result;
1610}
1611
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001612StateType
1613Process::GetState()
1614{
1615 // If any other threads access this we will need a mutex for it
1616 return m_public_state.GetValue ();
1617}
1618
Greg Claytondc6224e2014-10-21 01:00:42 +00001619bool
1620Process::StateChangedIsExternallyHijacked()
1621{
1622 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1623 {
1624 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1625 return true;
1626 }
1627 return false;
1628}
1629
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001630void
Jim Ingham221d51c2013-05-08 00:35:16 +00001631Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632{
Greg Clayton5160ce52013-03-27 23:08:40 +00001633 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001635 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001636 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001638
1639 // On the transition from Run to Stopped, we unlock the writer end of the
1640 // run lock. The lock gets locked in Resume, which is the public API
1641 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001642 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001643 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001644 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001645 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001646 if (log)
1647 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001648 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001649 }
1650 else
1651 {
1652 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1653 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001654 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001655 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001656 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001657 {
1658 if (log)
1659 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001660 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001661 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001662 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001663 }
1664 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665}
1666
Jim Ingham3b8285d2012-04-19 01:40:33 +00001667Error
1668Process::Resume ()
1669{
Greg Clayton5160ce52013-03-27 23:08:40 +00001670 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001671 if (log)
1672 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001673 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001674 {
1675 Error error("Resume request failed - process still running.");
1676 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001677 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001678 return error;
1679 }
1680 return PrivateResume();
1681}
1682
Greg Claytondc6224e2014-10-21 01:00:42 +00001683Error
1684Process::ResumeSynchronous (Stream *stream)
1685{
1686 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1687 if (log)
1688 log->Printf("Process::ResumeSynchronous -- locking run lock");
1689 if (!m_public_run_lock.TrySetRunning())
1690 {
1691 Error error("Resume request failed - process still running.");
1692 if (log)
1693 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1694 return error;
1695 }
1696
1697 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1698 HijackProcessEvents(listener_sp.get());
1699
1700 Error error = PrivateResume();
1701
1702 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1703
1704 // Undo the hijacking of process events...
1705 RestoreProcessEvents();
1706
1707 if (error.Success() && !StateIsStoppedState(state, false))
1708 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1709
1710 return error;
1711}
1712
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713StateType
1714Process::GetPrivateState ()
1715{
1716 return m_private_state.GetValue();
1717}
1718
1719void
1720Process::SetPrivateState (StateType new_state)
1721{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001722 if (m_finalize_called)
1723 return;
1724
Greg Clayton5160ce52013-03-27 23:08:40 +00001725 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001726 bool state_changed = false;
1727
1728 if (log)
1729 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1730
Andrew Kaylor29d65742013-05-10 17:19:04 +00001731 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 Mutex::Locker locker(m_private_state.GetMutex());
1733
1734 const StateType old_state = m_private_state.GetValueNoLock ();
1735 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001736
Greg Claytonaa49c832013-05-03 22:25:56 +00001737 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1738 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1739 if (old_state_is_stopped != new_state_is_stopped)
1740 {
1741 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001742 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001743 else
Ed Maste64fad602013-07-29 20:58:06 +00001744 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001745 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001746
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747 if (state_changed)
1748 {
1749 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001750 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001752 // Note, this currently assumes that all threads in the list
1753 // stop when the process stops. In the future we will want to
1754 // support a debugging model where some threads continue to run
1755 // while others are stopped. When that happens we will either need
1756 // a way for the thread list to identify which threads are stopping
1757 // or create a special thread list containing only threads which
1758 // actually stopped.
1759 //
1760 // The process plugin is responsible for managing the actual
1761 // behavior of the threads and should have stopped any threads
1762 // that are going to stop before we get here.
1763 m_thread_list.DidStop();
1764
Jim Ingham4b536182011-08-09 02:12:22 +00001765 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001766 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001767 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001768 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 }
1770 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001771 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1772 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1773 else
1774 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775 }
1776 else
1777 {
1778 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001779 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780 }
1781}
1782
Jim Ingham0faa43f2011-11-08 03:00:11 +00001783void
1784Process::SetRunningUserExpression (bool on)
1785{
1786 m_mod_id.SetRunningUserExpression (on);
1787}
1788
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789addr_t
1790Process::GetImageInfoAddress()
1791{
1792 return LLDB_INVALID_ADDRESS;
1793}
1794
Greg Clayton8f343b02010-11-04 01:54:29 +00001795//----------------------------------------------------------------------
1796// LoadImage
1797//
1798// This function provides a default implementation that works for most
1799// unix variants. Any Process subclasses that need to do shared library
1800// loading differently should override LoadImage and UnloadImage and
1801// do what is needed.
1802//----------------------------------------------------------------------
1803uint32_t
1804Process::LoadImage (const FileSpec &image_spec, Error &error)
1805{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001806 char path[PATH_MAX];
1807 image_spec.GetPath(path, sizeof(path));
1808
Greg Clayton8f343b02010-11-04 01:54:29 +00001809 DynamicLoader *loader = GetDynamicLoader();
1810 if (loader)
1811 {
1812 error = loader->CanLoadImage();
1813 if (error.Fail())
1814 return LLDB_INVALID_IMAGE_TOKEN;
1815 }
1816
1817 if (error.Success())
1818 {
1819 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001820
1821 if (thread_sp)
1822 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001823 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001824
1825 if (frame_sp)
1826 {
1827 ExecutionContext exe_ctx;
1828 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001829 EvaluateExpressionOptions expr_options;
1830 expr_options.SetUnwindOnError(true);
1831 expr_options.SetIgnoreBreakpoints(true);
1832 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001833 expr_options.SetResultIsInternal(true);
1834
Greg Clayton8f343b02010-11-04 01:54:29 +00001835 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001836 expr.Printf(R"(
1837 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1838 the_result.image_ptr = dlopen ("%s", 2);
1839 if (the_result.image_ptr == (void *) 0x0)
1840 {
1841 the_result.error_str = dlerror();
1842 }
1843 else
1844 {
1845 the_result.error_str = (const char *) 0x0;
1846 }
1847 the_result;
1848 )",
1849 path);
1850 const char *prefix = R"(
1851 extern "C" void* dlopen (const char *path, int mode);
1852 extern "C" const char *dlerror (void);
1853 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001854 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001855 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001856 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001857 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001858 expr.GetData(),
1859 prefix,
1860 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001861 expr_error);
1862 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001863 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001864 error = result_valobj_sp->GetError();
1865 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001866 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001867 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001868 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1869 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001870 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001871 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1872 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1873 {
1874 uint32_t image_token = m_image_tokens.size();
1875 m_image_tokens.push_back (image_ptr);
1876 return image_token;
1877 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001878 else if (image_ptr == 0)
1879 {
Jim Ingham6971b862014-07-19 00:37:06 +00001880 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1881 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001882 {
Jim Ingham6971b862014-07-19 00:37:06 +00001883 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001884 {
Enrico Granata2206b482014-10-30 18:27:31 +00001885 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1886 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001887 if (error.Success() && num_chars > 0)
1888 {
1889 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001890 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1891 }
1892 else
1893 {
1894 error.Clear();
1895 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001896 }
1897 }
1898 }
1899 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001900 }
1901 }
1902 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001903 else
1904 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001905 }
1906 }
1907 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001908 if (!error.AsCString())
1909 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001910 return LLDB_INVALID_IMAGE_TOKEN;
1911}
1912
1913//----------------------------------------------------------------------
1914// UnloadImage
1915//
1916// This function provides a default implementation that works for most
1917// unix variants. Any Process subclasses that need to do shared library
1918// loading differently should override LoadImage and UnloadImage and
1919// do what is needed.
1920//----------------------------------------------------------------------
1921Error
1922Process::UnloadImage (uint32_t image_token)
1923{
1924 Error error;
1925 if (image_token < m_image_tokens.size())
1926 {
1927 const addr_t image_addr = m_image_tokens[image_token];
1928 if (image_addr == LLDB_INVALID_ADDRESS)
1929 {
1930 error.SetErrorString("image already unloaded");
1931 }
1932 else
1933 {
1934 DynamicLoader *loader = GetDynamicLoader();
1935 if (loader)
1936 error = loader->CanLoadImage();
1937
1938 if (error.Success())
1939 {
1940 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001941
1942 if (thread_sp)
1943 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001944 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001945
1946 if (frame_sp)
1947 {
1948 ExecutionContext exe_ctx;
1949 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001950 EvaluateExpressionOptions expr_options;
1951 expr_options.SetUnwindOnError(true);
1952 expr_options.SetIgnoreBreakpoints(true);
1953 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001954 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001955 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001956 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001957 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001958 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001959 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001960 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001961 expr.GetData(),
1962 prefix,
1963 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001964 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001965 if (result_valobj_sp->GetError().Success())
1966 {
1967 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001968 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001969 {
1970 if (scalar.UInt(1))
1971 {
1972 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1973 }
1974 else
1975 {
1976 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1977 }
1978 }
1979 }
1980 else
1981 {
1982 error = result_valobj_sp->GetError();
1983 }
1984 }
1985 }
1986 }
1987 }
1988 }
1989 else
1990 {
1991 error.SetErrorString("invalid image token");
1992 }
1993 return error;
1994}
1995
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001996const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997Process::GetABI()
1998{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001999 if (!m_abi_sp)
2000 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2001 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002}
2003
Jim Ingham22777012010-09-23 02:01:19 +00002004LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002005Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002006{
2007 LanguageRuntimeCollection::iterator pos;
2008 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002009 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002010 {
Jim Inghamab175242012-03-10 00:22:19 +00002011 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002012
Jim Inghamab175242012-03-10 00:22:19 +00002013 m_language_runtimes[language] = runtime_sp;
2014 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002015 }
2016 else
2017 return (*pos).second.get();
2018}
2019
2020CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002021Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002022{
Jim Inghamab175242012-03-10 00:22:19 +00002023 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002024 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2025 return static_cast<CPPLanguageRuntime *> (runtime);
2026 return NULL;
2027}
2028
2029ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002030Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002031{
Jim Inghamab175242012-03-10 00:22:19 +00002032 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002033 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2034 return static_cast<ObjCLanguageRuntime *> (runtime);
2035 return NULL;
2036}
2037
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002038bool
2039Process::IsPossibleDynamicValue (ValueObject& in_value)
2040{
2041 if (in_value.IsDynamic())
2042 return false;
2043 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2044
2045 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2046 {
2047 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2048 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2049 }
2050
2051 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2052 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2053 return true;
2054
2055 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2056 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2057}
2058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002059BreakpointSiteList &
2060Process::GetBreakpointSiteList()
2061{
2062 return m_breakpoint_site_list;
2063}
2064
2065const BreakpointSiteList &
2066Process::GetBreakpointSiteList() const
2067{
2068 return m_breakpoint_site_list;
2069}
2070
2071
2072void
2073Process::DisableAllBreakpointSites ()
2074{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002075 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2076// bp_site->SetEnabled(true);
2077 DisableBreakpointSite(bp_site);
2078 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079}
2080
2081Error
2082Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2083{
2084 Error error (DisableBreakpointSiteByID (break_id));
2085
2086 if (error.Success())
2087 m_breakpoint_site_list.Remove(break_id);
2088
2089 return error;
2090}
2091
2092Error
2093Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2094{
2095 Error error;
2096 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2097 if (bp_site_sp)
2098 {
2099 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002100 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101 }
2102 else
2103 {
Daniel Malead01b2952012-11-29 21:49:15 +00002104 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105 }
2106
2107 return error;
2108}
2109
2110Error
2111Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2112{
2113 Error error;
2114 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2115 if (bp_site_sp)
2116 {
2117 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002118 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002119 }
2120 else
2121 {
Daniel Malead01b2952012-11-29 21:49:15 +00002122 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123 }
2124 return error;
2125}
2126
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002127lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002128Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002130 addr_t load_addr = LLDB_INVALID_ADDRESS;
2131
2132 bool show_error = true;
2133 switch (GetState())
2134 {
2135 case eStateInvalid:
2136 case eStateUnloaded:
2137 case eStateConnected:
2138 case eStateAttaching:
2139 case eStateLaunching:
2140 case eStateDetached:
2141 case eStateExited:
2142 show_error = false;
2143 break;
2144
2145 case eStateStopped:
2146 case eStateRunning:
2147 case eStateStepping:
2148 case eStateCrashed:
2149 case eStateSuspended:
2150 show_error = IsAlive();
2151 break;
2152 }
2153
2154 // Reset the IsIndirect flag here, in case the location changes from
2155 // pointing to a indirect symbol to a regular symbol.
2156 owner->SetIsIndirect (false);
2157
2158 if (owner->ShouldResolveIndirectFunctions())
2159 {
2160 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2161 if (symbol && symbol->IsIndirect())
2162 {
2163 Error error;
2164 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2165 if (!error.Success() && show_error)
2166 {
Greg Clayton44d93782014-01-27 23:43:24 +00002167 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2168 symbol->GetAddress().GetLoadAddress(&m_target),
2169 owner->GetBreakpoint().GetID(),
2170 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002171 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002172 return LLDB_INVALID_BREAK_ID;
2173 }
2174 Address resolved_address(load_addr);
2175 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2176 owner->SetIsIndirect(true);
2177 }
2178 else
2179 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2180 }
2181 else
2182 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2183
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184 if (load_addr != LLDB_INVALID_ADDRESS)
2185 {
2186 BreakpointSiteSP bp_site_sp;
2187
2188 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2189 // create a new breakpoint site and add it.
2190
2191 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2192
2193 if (bp_site_sp)
2194 {
2195 bp_site_sp->AddOwner (owner);
2196 owner->SetBreakpointSite (bp_site_sp);
2197 return bp_site_sp->GetID();
2198 }
2199 else
2200 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002201 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202 if (bp_site_sp)
2203 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002204 Error error = EnableBreakpointSite (bp_site_sp.get());
2205 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206 {
2207 owner->SetBreakpointSite (bp_site_sp);
2208 return m_breakpoint_site_list.Add (bp_site_sp);
2209 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002210 else
2211 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002212 if (show_error)
2213 {
2214 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002215 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2216 load_addr,
2217 owner->GetBreakpoint().GetID(),
2218 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002219 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002220 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002221 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222 }
2223 }
2224 }
2225 // We failed to enable the breakpoint
2226 return LLDB_INVALID_BREAK_ID;
2227
2228}
2229
2230void
2231Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2232{
2233 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2234 if (num_owners == 0)
2235 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002236 // Don't try to disable the site if we don't have a live process anymore.
2237 if (IsAlive())
2238 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2240 }
2241}
2242
2243
2244size_t
2245Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2246{
2247 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002248 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249
Jim Ingham20c77192011-06-29 19:42:28 +00002250 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002252 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2253 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002255 addr_t intersect_addr;
2256 size_t intersect_size;
2257 size_t opcode_offset;
2258 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002259 {
2260 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2261 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002262 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002263 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002264 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002265 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002267 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 }
2269 return bytes_removed;
2270}
2271
2272
Greg Claytonded470d2011-03-19 01:12:21 +00002273
2274size_t
2275Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2276{
2277 PlatformSP platform_sp (m_target.GetPlatform());
2278 if (platform_sp)
2279 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2280 return 0;
2281}
2282
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283Error
2284Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2285{
2286 Error error;
2287 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002288 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 const addr_t bp_addr = bp_site->GetLoadAddress();
2290 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002291 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 if (bp_site->IsEnabled())
2293 {
2294 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002295 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 +00002296 return error;
2297 }
2298
2299 if (bp_addr == LLDB_INVALID_ADDRESS)
2300 {
2301 error.SetErrorString("BreakpointSite contains an invalid load address.");
2302 return error;
2303 }
2304 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2305 // trap for the breakpoint site
2306 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2307
2308 if (bp_opcode_size == 0)
2309 {
Daniel Malead01b2952012-11-29 21:49:15 +00002310 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311 }
2312 else
2313 {
2314 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2315
2316 if (bp_opcode_bytes == NULL)
2317 {
2318 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2319 return error;
2320 }
2321
2322 // Save the original opcode by reading it
2323 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2324 {
2325 // Write a software breakpoint in place of the original opcode
2326 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2327 {
2328 uint8_t verify_bp_opcode_bytes[64];
2329 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2330 {
2331 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2332 {
2333 bp_site->SetEnabled(true);
2334 bp_site->SetType (BreakpointSite::eSoftware);
2335 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002336 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 bp_site->GetID(),
2338 (uint64_t)bp_addr);
2339 }
2340 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002341 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342 }
2343 else
2344 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2345 }
2346 else
2347 error.SetErrorString("Unable to write breakpoint trap to memory.");
2348 }
2349 else
2350 error.SetErrorString("Unable to read memory at breakpoint address.");
2351 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002352 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002353 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 bp_site->GetID(),
2355 (uint64_t)bp_addr,
2356 error.AsCString());
2357 return error;
2358}
2359
2360Error
2361Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2362{
2363 Error error;
2364 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002365 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 addr_t bp_addr = bp_site->GetLoadAddress();
2367 lldb::user_id_t breakID = bp_site->GetID();
2368 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002369 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370
2371 if (bp_site->IsHardware())
2372 {
2373 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2374 }
2375 else if (bp_site->IsEnabled())
2376 {
2377 const size_t break_op_size = bp_site->GetByteSize();
2378 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2379 if (break_op_size > 0)
2380 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002381 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002382 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002383 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 bool break_op_found = false;
2385
2386 // Read the breakpoint opcode
2387 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2388 {
2389 bool verify = false;
2390 // Make sure we have the a breakpoint opcode exists at this address
2391 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2392 {
2393 break_op_found = true;
2394 // We found a valid breakpoint opcode at this address, now restore
2395 // the saved opcode.
2396 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2397 {
2398 verify = true;
2399 }
2400 else
2401 error.SetErrorString("Memory write failed when restoring original opcode.");
2402 }
2403 else
2404 {
2405 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2406 // Set verify to true and so we can check if the original opcode has already been restored
2407 verify = true;
2408 }
2409
2410 if (verify)
2411 {
Greg Claytonc982c762010-07-09 20:39:50 +00002412 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002413 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 // Verify that our original opcode made it back to the inferior
2415 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2416 {
2417 // compare the memory we just read with the original opcode
2418 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2419 {
2420 // SUCCESS
2421 bp_site->SetEnabled(false);
2422 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002423 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 +00002424 return error;
2425 }
2426 else
2427 {
2428 if (break_op_found)
2429 error.SetErrorString("Failed to restore original opcode.");
2430 }
2431 }
2432 else
2433 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2434 }
2435 }
2436 else
2437 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2438 }
2439 }
2440 else
2441 {
2442 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002443 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 +00002444 return error;
2445 }
2446
2447 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002448 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 bp_site->GetID(),
2450 (uint64_t)bp_addr,
2451 error.AsCString());
2452 return error;
2453
2454}
2455
Greg Clayton58be07b2011-01-07 06:08:19 +00002456// Uncomment to verify memory caching works after making changes to caching code
2457//#define VERIFY_MEMORY_READS
2458
Sean Callanan64c0cf22012-06-07 22:26:42 +00002459size_t
2460Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2461{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002462 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002463 if (!GetDisableMemoryCache())
2464 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002465#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002466 // Memory caching is enabled, with debug verification
2467
2468 if (buf && size)
2469 {
2470 // Uncomment the line below to make sure memory caching is working.
2471 // I ran this through the test suite and got no assertions, so I am
2472 // pretty confident this is working well. If any changes are made to
2473 // memory caching, uncomment the line below and test your changes!
2474
2475 // Verify all memory reads by using the cache first, then redundantly
2476 // reading the same memory from the inferior and comparing to make sure
2477 // everything is exactly the same.
2478 std::string verify_buf (size, '\0');
2479 assert (verify_buf.size() == size);
2480 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2481 Error verify_error;
2482 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2483 assert (cache_bytes_read == verify_bytes_read);
2484 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2485 assert (verify_error.Success() == error.Success());
2486 return cache_bytes_read;
2487 }
2488 return 0;
2489#else // !defined(VERIFY_MEMORY_READS)
2490 // Memory caching is enabled, without debug verification
2491
2492 return m_memory_cache.Read (addr, buf, size, error);
2493#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002494 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002495 else
2496 {
2497 // Memory caching is disabled
2498
2499 return ReadMemoryFromInferior (addr, buf, size, error);
2500 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002501}
Greg Clayton58be07b2011-01-07 06:08:19 +00002502
Greg Clayton4c82d422012-05-18 23:20:01 +00002503size_t
2504Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2505{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002506 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002507 out_str.clear();
2508 addr_t curr_addr = addr;
2509 while (1)
2510 {
2511 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2512 if (length == 0)
2513 break;
2514 out_str.append(buf, length);
2515 // If we got "length - 1" bytes, we didn't get the whole C string, we
2516 // need to read some more characters
2517 if (length == sizeof(buf) - 1)
2518 curr_addr += length;
2519 else
2520 break;
2521 }
2522 return out_str.size();
2523}
2524
Greg Clayton58be07b2011-01-07 06:08:19 +00002525
2526size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002527Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2528 size_t type_width)
2529{
2530 size_t total_bytes_read = 0;
2531 if (dst && max_bytes && type_width && max_bytes >= type_width)
2532 {
2533 // Ensure a null terminator independent of the number of bytes that is read.
2534 memset (dst, 0, max_bytes);
2535 size_t bytes_left = max_bytes - type_width;
2536
2537 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2538 assert(sizeof(terminator) >= type_width &&
2539 "Attempting to validate a string with more than 4 bytes per character!");
2540
2541 addr_t curr_addr = addr;
2542 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2543 char *curr_dst = dst;
2544
2545 error.Clear();
2546 while (bytes_left > 0 && error.Success())
2547 {
2548 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2549 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2550 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2551
2552 if (bytes_read == 0)
2553 break;
2554
2555 // Search for a null terminator of correct size and alignment in bytes_read
2556 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2557 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2558 if (::strncmp(&dst[i], terminator, type_width) == 0)
2559 {
2560 error.Clear();
2561 return i;
2562 }
2563
2564 total_bytes_read += bytes_read;
2565 curr_dst += bytes_read;
2566 curr_addr += bytes_read;
2567 bytes_left -= bytes_read;
2568 }
2569 }
2570 else
2571 {
2572 if (max_bytes)
2573 error.SetErrorString("invalid arguments");
2574 }
2575 return total_bytes_read;
2576}
2577
2578// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2579// null terminators.
2580size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002581Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002582{
2583 size_t total_cstr_len = 0;
2584 if (dst && dst_max_len)
2585 {
Greg Claytone91b7952011-12-15 03:14:23 +00002586 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002587 // NULL out everything just to be safe
2588 memset (dst, 0, dst_max_len);
2589 Error error;
2590 addr_t curr_addr = addr;
2591 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2592 size_t bytes_left = dst_max_len - 1;
2593 char *curr_dst = dst;
2594
2595 while (bytes_left > 0)
2596 {
2597 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2598 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2599 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2600
2601 if (bytes_read == 0)
2602 {
Greg Claytone91b7952011-12-15 03:14:23 +00002603 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002604 dst[total_cstr_len] = '\0';
2605 break;
2606 }
2607 const size_t len = strlen(curr_dst);
2608
2609 total_cstr_len += len;
2610
2611 if (len < bytes_to_read)
2612 break;
2613
2614 curr_dst += bytes_read;
2615 curr_addr += bytes_read;
2616 bytes_left -= bytes_read;
2617 }
2618 }
Greg Claytone91b7952011-12-15 03:14:23 +00002619 else
2620 {
2621 if (dst == NULL)
2622 result_error.SetErrorString("invalid arguments");
2623 else
2624 result_error.Clear();
2625 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002626 return total_cstr_len;
2627}
2628
2629size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002630Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2631{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632 if (buf == NULL || size == 0)
2633 return 0;
2634
2635 size_t bytes_read = 0;
2636 uint8_t *bytes = (uint8_t *)buf;
2637
2638 while (bytes_read < size)
2639 {
2640 const size_t curr_size = size - bytes_read;
2641 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2642 bytes + bytes_read,
2643 curr_size,
2644 error);
2645 bytes_read += curr_bytes_read;
2646 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2647 break;
2648 }
2649
2650 // Replace any software breakpoint opcodes that fall into this range back
2651 // into "buf" before we return
2652 if (bytes_read > 0)
2653 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2654 return bytes_read;
2655}
2656
Greg Clayton58a4c462010-12-16 20:01:20 +00002657uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002658Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002659{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002660 Scalar scalar;
2661 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2662 return scalar.ULongLong(fail_value);
2663 return fail_value;
2664}
2665
2666addr_t
2667Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2668{
2669 Scalar scalar;
2670 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2671 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2672 return LLDB_INVALID_ADDRESS;
2673}
2674
2675
2676bool
2677Process::WritePointerToMemory (lldb::addr_t vm_addr,
2678 lldb::addr_t ptr_value,
2679 Error &error)
2680{
2681 Scalar scalar;
2682 const uint32_t addr_byte_size = GetAddressByteSize();
2683 if (addr_byte_size <= 4)
2684 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002685 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002686 scalar = ptr_value;
2687 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002688}
2689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002690size_t
2691Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2692{
2693 size_t bytes_written = 0;
2694 const uint8_t *bytes = (const uint8_t *)buf;
2695
2696 while (bytes_written < size)
2697 {
2698 const size_t curr_size = size - bytes_written;
2699 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2700 bytes + bytes_written,
2701 curr_size,
2702 error);
2703 bytes_written += curr_bytes_written;
2704 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2705 break;
2706 }
2707 return bytes_written;
2708}
2709
2710size_t
2711Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2712{
Greg Clayton58be07b2011-01-07 06:08:19 +00002713#if defined (ENABLE_MEMORY_CACHING)
2714 m_memory_cache.Flush (addr, size);
2715#endif
2716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 if (buf == NULL || size == 0)
2718 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002719
Jim Ingham4b536182011-08-09 02:12:22 +00002720 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722 // We need to write any data that would go where any current software traps
2723 // (enabled software breakpoints) any software traps (breakpoints) that we
2724 // may have placed in our tasks memory.
2725
Greg Claytond8cf1a12013-06-12 00:46:38 +00002726 BreakpointSiteList bp_sites_in_range;
2727
2728 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002730 // No breakpoint sites overlap
2731 if (bp_sites_in_range.IsEmpty())
2732 return WriteMemoryPrivate (addr, buf, size, error);
2733 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002735 const uint8_t *ubuf = (const uint8_t *)buf;
2736 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737
Greg Claytond8cf1a12013-06-12 00:46:38 +00002738 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2739
2740 if (error.Success())
2741 {
2742 addr_t intersect_addr;
2743 size_t intersect_size;
2744 size_t opcode_offset;
2745 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2746 assert(intersects);
2747 assert(addr <= intersect_addr && intersect_addr < addr + size);
2748 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2749 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2750
2751 // Check for bytes before this breakpoint
2752 const addr_t curr_addr = addr + bytes_written;
2753 if (intersect_addr > curr_addr)
2754 {
2755 // There are some bytes before this breakpoint that we need to
2756 // just write to memory
2757 size_t curr_size = intersect_addr - curr_addr;
2758 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2759 ubuf + bytes_written,
2760 curr_size,
2761 error);
2762 bytes_written += curr_bytes_written;
2763 if (curr_bytes_written != curr_size)
2764 {
2765 // We weren't able to write all of the requested bytes, we
2766 // are done looping and will return the number of bytes that
2767 // we have written so far.
2768 if (error.Success())
2769 error.SetErrorToGenericError();
2770 }
2771 }
2772 // Now write any bytes that would cover up any software breakpoints
2773 // directly into the breakpoint opcode buffer
2774 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2775 bytes_written += intersect_size;
2776 }
2777 });
2778
2779 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002780 WriteMemoryPrivate (addr + bytes_written,
2781 ubuf + bytes_written,
2782 size - bytes_written,
2783 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002784 }
2785 }
2786 else
2787 {
2788 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789 }
2790
2791 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002792 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002794
2795size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002796Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002797{
2798 if (byte_size == UINT32_MAX)
2799 byte_size = scalar.GetByteSize();
2800 if (byte_size > 0)
2801 {
2802 uint8_t buf[32];
2803 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2804 if (mem_size > 0)
2805 return WriteMemory(addr, buf, mem_size, error);
2806 else
2807 error.SetErrorString ("failed to get scalar as memory data");
2808 }
2809 else
2810 {
2811 error.SetErrorString ("invalid scalar value");
2812 }
2813 return 0;
2814}
2815
2816size_t
2817Process::ReadScalarIntegerFromMemory (addr_t addr,
2818 uint32_t byte_size,
2819 bool is_signed,
2820 Scalar &scalar,
2821 Error &error)
2822{
Greg Clayton7060f892013-05-01 23:41:30 +00002823 uint64_t uval = 0;
2824 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002825 {
Greg Clayton7060f892013-05-01 23:41:30 +00002826 error.SetErrorString ("byte size is zero");
2827 }
2828 else if (byte_size & (byte_size - 1))
2829 {
2830 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2831 }
2832 else if (byte_size <= sizeof(uval))
2833 {
2834 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002835 if (bytes_read == byte_size)
2836 {
2837 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002838 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002839 if (byte_size <= 4)
2840 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002841 else
Greg Clayton7060f892013-05-01 23:41:30 +00002842 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002843 if (is_signed)
2844 scalar.SignExtend(byte_size * 8);
2845 return bytes_read;
2846 }
2847 }
2848 else
2849 {
2850 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2851 }
2852 return 0;
2853}
2854
Greg Claytond495c532011-05-17 03:37:42 +00002855#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002856addr_t
2857Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2858{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002859 if (GetPrivateState() != eStateStopped)
2860 return LLDB_INVALID_ADDRESS;
2861
Greg Claytond495c532011-05-17 03:37:42 +00002862#if defined (USE_ALLOCATE_MEMORY_CACHE)
2863 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2864#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002865 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002866 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002867 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002868 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 +00002869 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002870 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002871 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002872 m_mod_id.GetStopID(),
2873 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002874 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002875#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002876}
2877
Sean Callanan90539452011-09-20 23:01:51 +00002878bool
2879Process::CanJIT ()
2880{
Sean Callanana7b443a2012-02-14 22:50:38 +00002881 if (m_can_jit == eCanJITDontKnow)
2882 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002883 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002884 Error err;
2885
2886 uint64_t allocated_memory = AllocateMemory(8,
2887 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2888 err);
2889
2890 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002891 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002892 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002893 if (log)
2894 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2895 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002896 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002897 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002898 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002899 if (log)
2900 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2901 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002902
2903 DeallocateMemory (allocated_memory);
2904 }
2905
Sean Callanan90539452011-09-20 23:01:51 +00002906 return m_can_jit == eCanJITYes;
2907}
2908
2909void
2910Process::SetCanJIT (bool can_jit)
2911{
2912 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2913}
2914
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002915Error
2916Process::DeallocateMemory (addr_t ptr)
2917{
Greg Claytond495c532011-05-17 03:37:42 +00002918 Error error;
2919#if defined (USE_ALLOCATE_MEMORY_CACHE)
2920 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2921 {
Daniel Malead01b2952012-11-29 21:49:15 +00002922 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002923 }
2924#else
2925 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002926
Greg Clayton5160ce52013-03-27 23:08:40 +00002927 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002928 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002929 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 +00002930 ptr,
2931 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002932 m_mod_id.GetStopID(),
2933 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002934#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002935 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936}
2937
Han Ming Ongc811d382012-11-17 00:33:14 +00002938
Greg Claytonc9660542012-02-05 02:38:54 +00002939ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002940Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002941 lldb::addr_t header_addr,
2942 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002943{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002944 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002945 if (module_sp)
2946 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002947 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002948 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002949 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002950 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002951 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002952 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002953}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954
2955Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002956Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002957{
2958 Error error;
2959 error.SetErrorString("watchpoints are not supported");
2960 return error;
2961}
2962
2963Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002964Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965{
2966 Error error;
2967 error.SetErrorString("watchpoints are not supported");
2968 return error;
2969}
2970
2971StateType
2972Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2973{
2974 StateType state;
2975 // Now wait for the process to launch and return control to us, and then
2976 // call DidLaunch:
2977 while (1)
2978 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002979 event_sp.reset();
2980 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2981
Greg Clayton2637f822011-11-17 01:23:07 +00002982 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002984
2985 // If state is invalid, then we timed out
2986 if (state == eStateInvalid)
2987 break;
2988
2989 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002990 HandlePrivateEvent (event_sp);
2991 }
2992 return state;
2993}
2994
2995Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002996Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997{
2998 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003000 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003001 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003002 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003003 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003004 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005
Greg Claytonaa149cb2011-08-11 02:48:45 +00003006 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003007 if (exe_module)
3008 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003009 char local_exec_file_path[PATH_MAX];
3010 char platform_exec_file_path[PATH_MAX];
3011 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3012 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003013 if (exe_module->GetFileSpec().Exists())
3014 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003015 // Install anything that might need to be installed prior to launching.
3016 // For host systems, this will do nothing, but if we are connected to a
3017 // remote platform it will install any needed binaries
3018 error = GetTarget().Install(&launch_info);
3019 if (error.Fail())
3020 return error;
3021
Greg Clayton71337622011-02-24 22:24:29 +00003022 if (PrivateStateThreadIsValid ())
3023 PausePrivateStateThread ();
3024
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003025 error = WillLaunch (exe_module);
3026 if (error.Success())
3027 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003028 const bool restarted = false;
3029 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003030 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003031
Ed Maste64fad602013-07-29 20:58:06 +00003032 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003033 {
3034 // Now launch using these arguments.
3035 error = DoLaunch (exe_module, launch_info);
3036 }
3037 else
3038 {
3039 // This shouldn't happen
3040 error.SetErrorString("failed to acquire process run lock");
3041 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003042
3043 if (error.Fail())
3044 {
3045 if (GetID() != LLDB_INVALID_PROCESS_ID)
3046 {
3047 SetID (LLDB_INVALID_PROCESS_ID);
3048 const char *error_string = error.AsCString();
3049 if (error_string == NULL)
3050 error_string = "launch failed";
3051 SetExitStatus (-1, error_string);
3052 }
3053 }
3054 else
3055 {
3056 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003057 TimeValue timeout_time;
3058 timeout_time = TimeValue::Now();
3059 timeout_time.OffsetWithSeconds(10);
3060 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061
Greg Clayton1a38ea72011-06-22 01:42:17 +00003062 if (state == eStateInvalid || event_sp.get() == NULL)
3063 {
3064 // We were able to launch the process, but we failed to
3065 // catch the initial stop.
3066 SetExitStatus (0, "failed to catch stop after launch");
3067 Destroy();
3068 }
3069 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003070 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003071
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072 DidLaunch ();
3073
Greg Claytonc859e2d2012-02-13 23:10:39 +00003074 DynamicLoader *dyld = GetDynamicLoader ();
3075 if (dyld)
3076 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003077
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003078 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003079
Jason Molendaeef51062013-11-05 03:57:19 +00003080 SystemRuntime *system_runtime = GetSystemRuntime ();
3081 if (system_runtime)
3082 system_runtime->DidLaunch();
3083
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003084 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Todd Fialaf72fa672014-10-07 16:05:21 +00003085
3086 // Note, the stop event was consumed above, but not handled. This was done
3087 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3088 // Directly set the state. This is done to prevent a stop message with a bunch
3089 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3090 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003091
3092 if (PrivateStateThreadIsValid ())
3093 ResumePrivateStateThread ();
3094 else
3095 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 }
3097 else if (state == eStateExited)
3098 {
3099 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3100 // not likely to work, and return an invalid pid.
3101 HandlePrivateEvent (event_sp);
3102 }
3103 }
3104 }
3105 }
3106 else
3107 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003108 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003109 }
3110 }
3111 return error;
3112}
3113
Greg Claytonc3776bf2012-02-09 06:16:32 +00003114
3115Error
3116Process::LoadCore ()
3117{
3118 Error error = DoLoadCore();
3119 if (error.Success())
3120 {
3121 if (PrivateStateThreadIsValid ())
3122 ResumePrivateStateThread ();
3123 else
3124 StartPrivateStateThread ();
3125
Greg Claytonc859e2d2012-02-13 23:10:39 +00003126 DynamicLoader *dyld = GetDynamicLoader ();
3127 if (dyld)
3128 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003129
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003130 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003131
Jason Molendaeef51062013-11-05 03:57:19 +00003132 SystemRuntime *system_runtime = GetSystemRuntime ();
3133 if (system_runtime)
3134 system_runtime->DidAttach();
3135
Greg Claytonc859e2d2012-02-13 23:10:39 +00003136 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003137 // We successfully loaded a core file, now pretend we stopped so we can
3138 // show all of the threads in the core file and explore the crashed
3139 // state.
3140 SetPrivateState (eStateStopped);
3141
3142 }
3143 return error;
3144}
3145
Greg Claytonc859e2d2012-02-13 23:10:39 +00003146DynamicLoader *
3147Process::GetDynamicLoader ()
3148{
3149 if (m_dyld_ap.get() == NULL)
3150 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3151 return m_dyld_ap.get();
3152}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003153
Todd Fialaaf245d12014-06-30 21:05:18 +00003154const lldb::DataBufferSP
3155Process::GetAuxvData()
3156{
3157 return DataBufferSP ();
3158}
3159
Andrew MacPherson17220c12014-03-05 10:12:43 +00003160JITLoaderList &
3161Process::GetJITLoaders ()
3162{
3163 if (!m_jit_loaders_ap)
3164 {
3165 m_jit_loaders_ap.reset(new JITLoaderList());
3166 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3167 }
3168 return *m_jit_loaders_ap;
3169}
3170
Jason Molendaeef51062013-11-05 03:57:19 +00003171SystemRuntime *
3172Process::GetSystemRuntime ()
3173{
3174 if (m_system_runtime_ap.get() == NULL)
3175 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3176 return m_system_runtime_ap.get();
3177}
3178
Todd Fiala76e0fc92014-08-27 22:58:26 +00003179Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3180 NextEventAction (process),
3181 m_exec_count (exec_count)
3182{
3183 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3184 if (log)
3185 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3186}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003187
Jim Inghambb3a2832011-01-29 01:49:25 +00003188Process::NextEventAction::EventActionResult
3189Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003190{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003191 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3192
Jim Inghambb3a2832011-01-29 01:49:25 +00003193 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003194 if (log)
3195 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3196
3197 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003198 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003199 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003200 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003201 return eEventActionRetry;
3202
3203 case eStateStopped:
3204 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003205 {
3206 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003207 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003208 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003209 // We don't want these events to be reported, so go set the ShouldReportStop here:
3210 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3211
Greg Claytonc9ed4782011-11-12 02:10:56 +00003212 if (m_exec_count > 0)
3213 {
3214 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003215
3216 if (log)
3217 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3218
Jim Ingham221d51c2013-05-08 00:35:16 +00003219 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003220 return eEventActionRetry;
3221 }
3222 else
3223 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003224 if (log)
3225 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3226
Greg Claytonc9ed4782011-11-12 02:10:56 +00003227 m_process->CompleteAttach ();
3228 return eEventActionSuccess;
3229 }
3230 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003231 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003232
Greg Clayton513c26c2011-01-29 07:10:55 +00003233 default:
3234 case eStateExited:
3235 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003236 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003237 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003238
3239 m_exit_string.assign ("No valid Process");
3240 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003241}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003242
Jim Inghambb3a2832011-01-29 01:49:25 +00003243Process::NextEventAction::EventActionResult
3244Process::AttachCompletionHandler::HandleBeingInterrupted()
3245{
3246 return eEventActionSuccess;
3247}
3248
3249const char *
3250Process::AttachCompletionHandler::GetExitString ()
3251{
3252 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253}
3254
Greg Clayton8012cad2014-11-17 19:39:20 +00003255Listener &
3256ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3257{
3258 if (m_listener_sp)
3259 return *m_listener_sp;
3260 else
3261 return debugger.GetListener();
3262}
3263
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003265Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003268 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003269 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003270 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003271 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003272 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003273
Greg Clayton144f3a92011-11-15 03:53:30 +00003274 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003275 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003276 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003277 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003278 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003279
Greg Clayton144f3a92011-11-15 03:53:30 +00003280 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003281 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003282 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3283
3284 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003286 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3287 if (error.Success())
3288 {
Ed Maste64fad602013-07-29 20:58:06 +00003289 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003290 {
3291 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003292 const bool restarted = false;
3293 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003294 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003295 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003296 }
3297 else
3298 {
3299 // This shouldn't happen
3300 error.SetErrorString("failed to acquire process run lock");
3301 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003302
Greg Clayton144f3a92011-11-15 03:53:30 +00003303 if (error.Fail())
3304 {
3305 if (GetID() != LLDB_INVALID_PROCESS_ID)
3306 {
3307 SetID (LLDB_INVALID_PROCESS_ID);
3308 if (error.AsCString() == NULL)
3309 error.SetErrorString("attach failed");
3310
3311 SetExitStatus(-1, error.AsCString());
3312 }
3313 }
3314 else
3315 {
3316 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3317 StartPrivateStateThread();
3318 }
3319 return error;
3320 }
Greg Claytone996fd32011-03-08 22:40:15 +00003321 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003322 else
Greg Claytone996fd32011-03-08 22:40:15 +00003323 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003324 ProcessInstanceInfoList process_infos;
3325 PlatformSP platform_sp (m_target.GetPlatform ());
3326
3327 if (platform_sp)
3328 {
3329 ProcessInstanceInfoMatch match_info;
3330 match_info.GetProcessInfo() = attach_info;
3331 match_info.SetNameMatchType (eNameMatchEquals);
3332 platform_sp->FindProcesses (match_info, process_infos);
3333 const uint32_t num_matches = process_infos.GetSize();
3334 if (num_matches == 1)
3335 {
3336 attach_pid = process_infos.GetProcessIDAtIndex(0);
3337 // Fall through and attach using the above process ID
3338 }
3339 else
3340 {
3341 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3342 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003343 {
3344 StreamString s;
3345 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3346 for (size_t i = 0; i < num_matches; i++)
3347 {
3348 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3349 }
3350 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3351 process_name,
3352 s.GetData());
3353 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003354 else
3355 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3356 }
3357 }
3358 else
3359 {
3360 error.SetErrorString ("invalid platform, can't find processes by name");
3361 return error;
3362 }
Greg Claytone996fd32011-03-08 22:40:15 +00003363 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003364 }
3365 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003366 {
3367 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003368 }
3369 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003370
3371 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003372 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003373 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003374 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003375 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003376
Ed Maste64fad602013-07-29 20:58:06 +00003377 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003378 {
3379 // Now attach using these arguments.
3380 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003381 const bool restarted = false;
3382 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003383 error = DoAttachToProcessWithID (attach_pid, attach_info);
3384 }
3385 else
3386 {
3387 // This shouldn't happen
3388 error.SetErrorString("failed to acquire process run lock");
3389 }
3390
Greg Clayton144f3a92011-11-15 03:53:30 +00003391 if (error.Success())
3392 {
3393
3394 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3395 StartPrivateStateThread();
3396 }
3397 else
Greg Claytone996fd32011-03-08 22:40:15 +00003398 {
3399 if (GetID() != LLDB_INVALID_PROCESS_ID)
3400 {
3401 SetID (LLDB_INVALID_PROCESS_ID);
3402 const char *error_string = error.AsCString();
3403 if (error_string == NULL)
3404 error_string = "attach failed";
3405
3406 SetExitStatus(-1, error_string);
3407 }
3408 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003409 }
3410 }
3411 return error;
3412}
3413
Greg Clayton93d3c8332011-02-16 04:46:07 +00003414void
3415Process::CompleteAttach ()
3416{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003417 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3418 if (log)
3419 log->Printf ("Process::%s()", __FUNCTION__);
3420
Greg Clayton93d3c8332011-02-16 04:46:07 +00003421 // Let the process subclass figure out at much as it can about the process
3422 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003423 ArchSpec process_arch;
3424 DidAttach(process_arch);
3425
3426 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003427 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003428 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003429 if (log)
3430 {
3431 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3432 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3433 __FUNCTION__,
3434 triple_str ? triple_str : "<null>");
3435 }
3436 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003437
Jim Ingham4299fdb2011-09-15 01:10:17 +00003438 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3439 // the same as the one we've already set, switch architectures.
3440 PlatformSP platform_sp (m_target.GetPlatform ());
3441 assert (platform_sp.get());
3442 if (platform_sp)
3443 {
Greg Clayton70512312012-05-08 01:45:38 +00003444 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003445 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003446 {
3447 ArchSpec platform_arch;
3448 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3449 if (platform_sp)
3450 {
3451 m_target.SetPlatform (platform_sp);
3452 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003453 if (log)
3454 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 +00003455 }
3456 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003457 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003458 {
3459 ProcessInstanceInfo process_info;
3460 platform_sp->GetProcessInfo (GetID(), process_info);
3461 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003462 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003463 {
Greg Clayton70512312012-05-08 01:45:38 +00003464 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003465 if (log)
3466 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 ());
3467 }
Greg Clayton70512312012-05-08 01:45:38 +00003468 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003469 }
3470
3471 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003472 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003473 DynamicLoader *dyld = GetDynamicLoader ();
3474 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003475 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003476 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003477 if (log)
3478 {
3479 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3480 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3481 __FUNCTION__,
3482 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3483 dyld->GetPluginName().AsCString ("<unnamed>"));
3484 }
3485 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003486
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003487 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003488
Jason Molendaeef51062013-11-05 03:57:19 +00003489 SystemRuntime *system_runtime = GetSystemRuntime ();
3490 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003491 {
Jason Molendaeef51062013-11-05 03:57:19 +00003492 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003493 if (log)
3494 {
3495 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3496 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3497 __FUNCTION__,
3498 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3499 system_runtime->GetPluginName().AsCString("<unnamed>"));
3500 }
3501 }
Jason Molendaeef51062013-11-05 03:57:19 +00003502
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003503 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003504 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003505 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003506 Mutex::Locker modules_locker(target_modules.GetMutex());
3507 size_t num_modules = target_modules.GetSize();
3508 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003509
Andy Gibbsa297a972013-06-19 19:04:53 +00003510 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003511 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003512 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003513 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003514 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003515 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003516 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003517 break;
3518 }
3519 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003520 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003521 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003522 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003523 if (log)
3524 {
3525 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3526 log->Printf ("Process::%s after looping through modules, target executable is %s",
3527 __FUNCTION__,
3528 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3529 }
3530 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003531}
3532
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003533Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003534Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003535{
Greg Claytonb766a732011-02-04 01:58:07 +00003536 m_abi_sp.reset();
3537 m_process_input_reader.reset();
3538
3539 // Find the process and its architecture. Make sure it matches the architecture
3540 // of the current Target, and if not adjust it.
3541
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003542 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003543 if (error.Success())
3544 {
Greg Clayton71337622011-02-24 22:24:29 +00003545 if (GetID() != LLDB_INVALID_PROCESS_ID)
3546 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003547 EventSP event_sp;
3548 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3549
3550 if (state == eStateStopped || state == eStateCrashed)
3551 {
3552 // If we attached and actually have a process on the other end, then
3553 // this ended up being the equivalent of an attach.
3554 CompleteAttach ();
3555
3556 // This delays passing the stopped event to listeners till
3557 // CompleteAttach gets a chance to complete...
3558 HandlePrivateEvent (event_sp);
3559
3560 }
Greg Clayton71337622011-02-24 22:24:29 +00003561 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003562
3563 if (PrivateStateThreadIsValid ())
3564 ResumePrivateStateThread ();
3565 else
3566 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003567 }
3568 return error;
3569}
3570
3571
3572Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003573Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003574{
Greg Clayton5160ce52013-03-27 23:08:40 +00003575 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003576 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003577 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003578 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003579 StateAsCString(m_public_state.GetValue()),
3580 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003581
3582 Error error (WillResume());
3583 // Tell the process it is about to resume before the thread list
3584 if (error.Success())
3585 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003586 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587 // can let all of our threads know that they are about to be
3588 // resumed. Threads will each be called with
3589 // Thread::WillResume(StateType) where StateType contains the state
3590 // that they are supposed to have when the process is resumed
3591 // (suspended/running/stepping). Threads should also check
3592 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003593 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003594 if (m_thread_list.WillResume())
3595 {
Jim Ingham372787f2012-04-07 00:00:41 +00003596 // Last thing, do the PreResumeActions.
3597 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003598 {
Jim Ingham0161b492013-02-09 01:29:05 +00003599 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003600 }
3601 else
3602 {
3603 m_mod_id.BumpResumeID();
3604 error = DoResume();
3605 if (error.Success())
3606 {
3607 DidResume();
3608 m_thread_list.DidResume();
3609 if (log)
3610 log->Printf ("Process thinks the process has resumed.");
3611 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003612 }
3613 }
3614 else
3615 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003616 // Somebody wanted to run without running. So generate a continue & a stopped event,
3617 // and let the world handle them.
3618 if (log)
3619 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3620
3621 SetPrivateState(eStateRunning);
3622 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003623 }
3624 }
Jim Ingham444586b2011-01-24 06:34:17 +00003625 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003626 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003627 return error;
3628}
3629
3630Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003631Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003633 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3634 // in case it was already set and some thread plan logic calls halt on its
3635 // own.
3636 m_clear_thread_plans_on_stop |= clear_thread_plans;
3637
Jim Inghamaacc3182012-06-06 00:29:30 +00003638 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3639 // we could just straightaway get another event. It just narrows the window...
3640 m_currently_handling_event.WaitForValueEqualTo(false);
3641
3642
Jim Inghambb3a2832011-01-29 01:49:25 +00003643 // Pause our private state thread so we can ensure no one else eats
3644 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003645 Listener halt_listener ("lldb.process.halt_listener");
3646 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003647
Jim Inghambb3a2832011-01-29 01:49:25 +00003648 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003649 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003650
Greg Clayton06357c92014-07-30 17:38:47 +00003651 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003652 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003653 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003654
Greg Clayton513c26c2011-01-29 07:10:55 +00003655 bool caused_stop = false;
3656
3657 // Ask the process subclass to actually halt our process
3658 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003659 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003660 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003661 if (m_public_state.GetValue() == eStateAttaching)
3662 {
Greg Clayton06357c92014-07-30 17:38:47 +00003663 // Don't hijack and eat the eStateExited as the code that was doing
3664 // the attach will be waiting for this event...
3665 RestorePrivateProcessEvents();
3666 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003667 SetExitStatus(SIGKILL, "Cancelled async attach.");
3668 Destroy ();
3669 }
3670 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003671 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003672 // If "caused_stop" is true, then DoHalt stopped the process. If
3673 // "caused_stop" is false, the process was already stopped.
3674 // If the DoHalt caused the process to stop, then we want to catch
3675 // this event and set the interrupted bool to true before we pass
3676 // this along so clients know that the process was interrupted by
3677 // a halt command.
3678 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003679 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003680 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003681 TimeValue timeout_time;
3682 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003683 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003684 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3685 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003686
Jim Ingham0f16e732011-02-08 05:20:59 +00003687 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003688 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003689 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003690 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003691 }
3692 else
3693 {
Greg Clayton2637f822011-11-17 01:23:07 +00003694 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003695 {
3696 // We caused the process to interrupt itself, so mark this
3697 // as such in the stop event so clients can tell an interrupted
3698 // process from a natural stop
3699 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3700 }
3701 else
3702 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003703 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003704 if (log)
3705 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3706 error.SetErrorString ("Did not get stopped event after halt.");
3707 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003708 }
3709 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003710 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003711 }
3712 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003713 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003714 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003715 if (!restored_process_events)
3716 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003717
3718 // Post any event we might have consumed. If all goes well, we will have
3719 // stopped the process, intercepted the event and set the interrupted
3720 // bool in the event. Post it to the private event queue and that will end up
3721 // correctly setting the state.
3722 if (event_sp)
3723 m_private_state_broadcaster.BroadcastEvent(event_sp);
3724
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725 return error;
3726}
3727
3728Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003729Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3730{
3731 Error error;
3732 if (m_public_state.GetValue() == eStateRunning)
3733 {
3734 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3735 if (log)
3736 log->Printf("Process::Destroy() About to halt.");
3737 error = Halt();
3738 if (error.Success())
3739 {
3740 // Consume the halt event.
3741 TimeValue timeout (TimeValue::Now());
3742 timeout.OffsetWithSeconds(1);
3743 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3744
3745 // If the process exited while we were waiting for it to stop, put the exited event into
3746 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3747 // they don't have a process anymore...
3748
3749 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3750 {
3751 if (log)
3752 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3753 return error;
3754 }
3755 else
3756 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3757
3758 if (state != eStateStopped)
3759 {
3760 if (log)
3761 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3762 // If we really couldn't stop the process then we should just error out here, but if the
3763 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3764 StateType private_state = m_private_state.GetValue();
3765 if (private_state != eStateStopped)
3766 {
3767 return error;
3768 }
3769 }
3770 }
3771 else
3772 {
3773 if (log)
3774 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3775 }
3776 }
3777 return error;
3778}
3779
3780Error
Jim Inghamacff8952013-05-02 00:27:30 +00003781Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003783 EventSP exit_event_sp;
3784 Error error;
3785 m_destroy_in_process = true;
3786
3787 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003788
3789 if (error.Success())
3790 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003791 if (DetachRequiresHalt())
3792 {
3793 error = HaltForDestroyOrDetach (exit_event_sp);
3794 if (!error.Success())
3795 {
3796 m_destroy_in_process = false;
3797 return error;
3798 }
3799 else if (exit_event_sp)
3800 {
3801 // We shouldn't need to do anything else here. There's no process left to detach from...
3802 StopPrivateStateThread();
3803 m_destroy_in_process = false;
3804 return error;
3805 }
3806 }
3807
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003808 m_thread_list.DiscardThreadPlans();
3809 DisableAllBreakpointSites();
3810
Jim Inghamacff8952013-05-02 00:27:30 +00003811 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003812 if (error.Success())
3813 {
3814 DidDetach();
3815 StopPrivateStateThread();
3816 }
Jim Inghamacff8952013-05-02 00:27:30 +00003817 else
3818 {
3819 return error;
3820 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003822 m_destroy_in_process = false;
3823
3824 // If we exited when we were waiting for a process to stop, then
3825 // forward the event here so we don't lose the event
3826 if (exit_event_sp)
3827 {
3828 // Directly broadcast our exited event because we shut down our
3829 // private state thread above
3830 BroadcastEvent(exit_event_sp);
3831 }
3832
3833 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3834 // the last events through the event system, in which case we might strand the write lock. Unlock
3835 // it here so when we do to tear down the process we don't get an error destroying the lock.
3836
Ed Maste64fad602013-07-29 20:58:06 +00003837 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003838 return error;
3839}
3840
3841Error
3842Process::Destroy ()
3843{
Jim Ingham09437922013-03-01 20:04:25 +00003844
3845 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3846 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3847 // failed and the process stays around for some reason it won't be in a confused state.
3848
3849 m_destroy_in_process = true;
3850
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003851 Error error (WillDestroy());
3852 if (error.Success())
3853 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003854 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003855 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003856 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003857 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003858 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003859
Jim Inghamaacc3182012-06-06 00:29:30 +00003860 if (m_public_state.GetValue() != eStateRunning)
3861 {
3862 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3863 // kill it, we don't want it hitting a breakpoint...
3864 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3865 // we're not going to have much luck doing this now.
3866 m_thread_list.DiscardThreadPlans();
3867 DisableAllBreakpointSites();
3868 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003869
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003870 error = DoDestroy();
3871 if (error.Success())
3872 {
3873 DidDestroy();
3874 StopPrivateStateThread();
3875 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003876 m_stdio_communication.StopReadThread();
3877 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003878
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003879 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003880 {
3881 m_process_input_reader->SetIsDone(true);
3882 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003883 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003884 }
3885
Greg Clayton85fb1b92012-09-11 02:33:37 +00003886 // If we exited when we were waiting for a process to stop, then
3887 // forward the event here so we don't lose the event
3888 if (exit_event_sp)
3889 {
3890 // Directly broadcast our exited event because we shut down our
3891 // private state thread above
3892 BroadcastEvent(exit_event_sp);
3893 }
3894
Jim Inghamb1e2e842012-04-12 18:49:31 +00003895 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3896 // the last events through the event system, in which case we might strand the write lock. Unlock
3897 // 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 +00003898 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003899 }
Jim Ingham09437922013-03-01 20:04:25 +00003900
3901 m_destroy_in_process = false;
3902
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003903 return error;
3904}
3905
3906Error
3907Process::Signal (int signal)
3908{
3909 Error error (WillSignal());
3910 if (error.Success())
3911 {
3912 error = DoSignal(signal);
3913 if (error.Success())
3914 DidSignal();
3915 }
3916 return error;
3917}
3918
Greg Clayton514487e2011-02-15 21:59:32 +00003919lldb::ByteOrder
3920Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921{
Greg Clayton514487e2011-02-15 21:59:32 +00003922 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003923}
3924
3925uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003926Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003927{
Greg Clayton514487e2011-02-15 21:59:32 +00003928 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003929}
3930
Greg Clayton514487e2011-02-15 21:59:32 +00003931
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003932bool
3933Process::ShouldBroadcastEvent (Event *event_ptr)
3934{
3935 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3936 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003937 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003938
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003939 switch (state)
3940 {
Greg Claytonb766a732011-02-04 01:58:07 +00003941 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003942 case eStateAttaching:
3943 case eStateLaunching:
3944 case eStateDetached:
3945 case eStateExited:
3946 case eStateUnloaded:
3947 // These events indicate changes in the state of the debugging session, always report them.
3948 return_value = true;
3949 break;
3950 case eStateInvalid:
3951 // We stopped for no apparent reason, don't report it.
3952 return_value = false;
3953 break;
3954 case eStateRunning:
3955 case eStateStepping:
3956 // If we've started the target running, we handle the cases where we
3957 // are already running and where there is a transition from stopped to
3958 // running differently.
3959 // running -> running: Automatically suppress extra running events
3960 // stopped -> running: Report except when there is one or more no votes
3961 // and no yes votes.
3962 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003963 if (m_force_next_event_delivery)
3964 return_value = true;
3965 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003966 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003967 switch (m_last_broadcast_state)
3968 {
3969 case eStateRunning:
3970 case eStateStepping:
3971 // We always suppress multiple runnings with no PUBLIC stop in between.
3972 return_value = false;
3973 break;
3974 default:
3975 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003976 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003977 // events. If I run the lldb/test/thread/a.out file and
3978 // break at main.cpp:58, run and hit the breakpoints on
3979 // multiple threads, then somehow during the stepping over
3980 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981
Jim Ingham1460e4b2014-01-10 23:46:59 +00003982 // This is a transition from stop to run.
3983 switch (m_thread_list.ShouldReportRun (event_ptr))
3984 {
3985 case eVoteYes:
3986 case eVoteNoOpinion:
3987 return_value = true;
3988 break;
3989 case eVoteNo:
3990 return_value = false;
3991 break;
3992 }
3993 break;
3994 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003995 }
3996 break;
3997 case eStateStopped:
3998 case eStateCrashed:
3999 case eStateSuspended:
4000 {
4001 // We've stopped. First see if we're going to restart the target.
4002 // If we are going to stop, then we always broadcast the event.
4003 // 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 +00004004 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004005
Jim Inghamcb4ca112012-05-16 01:32:14 +00004006 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004007 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004008 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004009 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004010 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004011 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004012 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004013 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4014 // so they can properly set their state.
4015 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004016 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004017 }
4018 else
4019 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004020 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4021 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004022
Jim Ingham0161b492013-02-09 01:29:05 +00004023 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4024 // Asking the thread list is also not likely to go well, since we are running again.
4025 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004026
Jim Ingham0161b492013-02-09 01:29:05 +00004027 if (!was_restarted)
4028 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004029
Jim Ingham221d51c2013-05-08 00:35:16 +00004030 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004031 {
Jim Ingham0161b492013-02-09 01:29:05 +00004032 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4033 if (log)
4034 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004035 should_resume, StateAsCString(state),
4036 was_restarted, stop_vote);
4037
Jim Ingham0161b492013-02-09 01:29:05 +00004038 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004039 {
4040 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004041 return_value = true;
4042 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004044 case eVoteNo:
4045 return_value = false;
4046 break;
4047 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004048
Jim Inghamcb95f342012-09-05 21:13:56 +00004049 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004050 {
4051 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004052 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4053 static_cast<void*>(event_ptr),
4054 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004055 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004056 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004057 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004059 }
4060 else
4061 {
4062 return_value = true;
4063 SynchronouslyNotifyStateChanged (state);
4064 }
4065 }
4066 }
Jim Ingham0161b492013-02-09 01:29:05 +00004067 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004068 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004069
Jim Ingham1460e4b2014-01-10 23:46:59 +00004070 // Forcing the next event delivery is a one shot deal. So reset it here.
4071 m_force_next_event_delivery = false;
4072
Jim Ingham0161b492013-02-09 01:29:05 +00004073 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4074 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4075 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4076 // because the PublicState reflects the last event pulled off the queue, and there may be several
4077 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4078 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004079
Jim Ingham0161b492013-02-09 01:29:05 +00004080 if (return_value)
4081 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004082
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004083 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004084 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004085 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004086 StateAsCString(m_last_broadcast_state),
4087 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004088 return return_value;
4089}
4090
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091
4092bool
Jim Ingham372787f2012-04-07 00:00:41 +00004093Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094{
Greg Clayton5160ce52013-03-27 23:08:40 +00004095 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096
Greg Clayton8b82f082011-04-12 05:54:46 +00004097 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004099 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4100
Jim Ingham372787f2012-04-07 00:00:41 +00004101 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004102 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004103
4104 // Create a thread that watches our internal state and controls which
4105 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004106 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004107
Zachary Turner39de3112014-09-09 20:54:56 +00004108 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004109 {
Zachary Turner39de3112014-09-09 20:54:56 +00004110 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4111 if (already_running)
4112 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4113 else
4114 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004115 }
Jim Ingham372787f2012-04-07 00:00:41 +00004116 else
Todd Fiala17096d72014-07-16 19:03:16 +00004117 {
4118 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004119 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004120 else
Zachary Turner39de3112014-09-09 20:54:56 +00004121 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004122 }
4123
Jim Ingham076b3042012-04-10 01:21:57 +00004124 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00004125 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004126 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004127 {
4128 ResumePrivateStateThread();
4129 return true;
4130 }
4131 else
4132 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004133}
4134
4135void
4136Process::PausePrivateStateThread ()
4137{
4138 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4139}
4140
4141void
4142Process::ResumePrivateStateThread ()
4143{
4144 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4145}
4146
4147void
4148Process::StopPrivateStateThread ()
4149{
Greg Clayton8b82f082011-04-12 05:54:46 +00004150 if (PrivateStateThreadIsValid ())
4151 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004152 else
4153 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004154 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004155 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004156 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004157 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004158}
4159
4160void
4161Process::ControlPrivateStateThread (uint32_t signal)
4162{
Greg Clayton5160ce52013-03-27 23:08:40 +00004163 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004164
4165 assert (signal == eBroadcastInternalStateControlStop ||
4166 signal == eBroadcastInternalStateControlPause ||
4167 signal == eBroadcastInternalStateControlResume);
4168
4169 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004170 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004171
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004172 // Signal the private state thread. First we should copy this is case the
4173 // thread starts exiting since the private state thread will NULL this out
4174 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004175 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004176 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004177 {
4178 TimeValue timeout_time;
4179 bool timed_out;
4180
4181 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4182
4183 timeout_time = TimeValue::Now();
4184 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004185 if (log)
4186 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4188 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4189
4190 if (signal == eBroadcastInternalStateControlStop)
4191 {
4192 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004193 {
Zachary Turner39de3112014-09-09 20:54:56 +00004194 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004195 if (log)
4196 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4197 }
4198 else
4199 {
4200 if (log)
4201 log->Printf ("The control event killed the private state thread without having to cancel.");
4202 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004203
4204 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004205 private_state_thread.Join(&result);
4206 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004207 }
4208 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004209 else
4210 {
4211 if (log)
4212 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4213 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004214}
4215
4216void
Jim Inghamcfc09352012-07-27 23:57:19 +00004217Process::SendAsyncInterrupt ()
4218{
4219 if (PrivateStateThreadIsValid())
4220 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4221 else
4222 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4223}
4224
4225void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004226Process::HandlePrivateEvent (EventSP &event_sp)
4227{
Greg Clayton5160ce52013-03-27 23:08:40 +00004228 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004229 m_resume_requested = false;
4230
Jim Inghamaacc3182012-06-06 00:29:30 +00004231 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004232
Greg Clayton414f5d32011-01-25 02:58:48 +00004233 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004234
4235 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004236 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004237 {
Jim Ingham754ab982011-01-29 04:05:41 +00004238 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004239 if (log)
4240 log->Printf ("Ran next event action, result was %d.", action_result);
4241
Jim Inghambb3a2832011-01-29 01:49:25 +00004242 switch (action_result)
4243 {
4244 case NextEventAction::eEventActionSuccess:
4245 SetNextEventAction(NULL);
4246 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004247
Jim Inghambb3a2832011-01-29 01:49:25 +00004248 case NextEventAction::eEventActionRetry:
4249 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004250
Jim Inghambb3a2832011-01-29 01:49:25 +00004251 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004252 // Handle Exiting Here. If we already got an exited event,
4253 // we should just propagate it. Otherwise, swallow this event,
4254 // and set our state to exit so the next event will kill us.
4255 if (new_state != eStateExited)
4256 {
4257 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004258 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004259 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004260 SetNextEventAction(NULL);
4261 return;
4262 }
4263 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004264 break;
4265 }
4266 }
4267
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004268 // See if we should broadcast this state to external clients?
4269 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004270
4271 if (should_broadcast)
4272 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004273 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004274 if (log)
4275 {
Daniel Malead01b2952012-11-29 21:49:15 +00004276 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004277 __FUNCTION__,
4278 GetID(),
4279 StateAsCString(new_state),
4280 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004281 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004282 }
Jim Ingham9575d842011-03-11 03:53:59 +00004283 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004284 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004285 {
4286 // Only push the input handler if we aren't fowarding events,
4287 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004288 // Or don't push it if we are launching since it will come up stopped.
4289 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004290 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004291 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004292 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004293 else if (StateIsStoppedState(new_state, false))
4294 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004295 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004296 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4297 {
4298 // If the lldb_private::Debugger is handling the events, we don't
4299 // want to pop the process IOHandler here, we want to do it when
4300 // we receive the stopped event so we can carefully control when
4301 // the process IOHandler is popped because when we stop we want to
4302 // display some text stating how and why we stopped, then maybe some
4303 // process/thread/frame info, and then we want the "(lldb) " prompt
4304 // to show up. If we pop the process IOHandler here, then we will
4305 // cause the command interpreter to become the top IOHandler after
4306 // the process pops off and it will update its prompt right away...
4307 // See the Debugger.cpp file where it calls the function as
4308 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4309 // Otherwise we end up getting overlapping "(lldb) " prompts and
4310 // garbled output.
4311 //
4312 // If we aren't handling the events in the debugger (which is indicated
4313 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4314 // are hijacked, then we always pop the process IO handler manually.
4315 // Hijacking happens when the internal process state thread is running
4316 // thread plans, or when commands want to run in synchronous mode
4317 // and they call "process->WaitForProcessToStop()". An example of something
4318 // that will hijack the events is a simple expression:
4319 //
4320 // (lldb) expr (int)puts("hello")
4321 //
4322 // This will cause the internal process state thread to resume and halt
4323 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4324 // events) and we do need the IO handler to be pushed and popped
4325 // correctly.
4326
4327 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4328 PopProcessIOHandler ();
4329 }
4330 }
Jim Ingham9575d842011-03-11 03:53:59 +00004331
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004332 BroadcastEvent (event_sp);
4333 }
4334 else
4335 {
4336 if (log)
4337 {
Daniel Malead01b2952012-11-29 21:49:15 +00004338 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004339 __FUNCTION__,
4340 GetID(),
4341 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004342 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004343 }
4344 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004345 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004346}
4347
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004348thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004349Process::PrivateStateThread (void *arg)
4350{
4351 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004352 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353 return result;
4354}
4355
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004356thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004357Process::RunPrivateStateThread ()
4358{
Jim Ingham076b3042012-04-10 01:21:57 +00004359 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004360 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004361
Greg Clayton5160ce52013-03-27 23:08:40 +00004362 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004363 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004364 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4365 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004366
4367 bool exit_now = false;
4368 while (!exit_now)
4369 {
4370 EventSP event_sp;
4371 WaitForEventsPrivate (NULL, event_sp, control_only);
4372 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4373 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004374 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004375 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4376 __FUNCTION__, static_cast<void*>(this), GetID(),
4377 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004378
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004379 switch (event_sp->GetType())
4380 {
4381 case eBroadcastInternalStateControlStop:
4382 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004383 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004384
4385 case eBroadcastInternalStateControlPause:
4386 control_only = true;
4387 break;
4388
4389 case eBroadcastInternalStateControlResume:
4390 control_only = false;
4391 break;
4392 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004393
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004394 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004395 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004396 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004397 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4398 {
4399 if (m_public_state.GetValue() == eStateAttaching)
4400 {
4401 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004402 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4403 __FUNCTION__, static_cast<void*>(this),
4404 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004405 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4406 }
4407 else
4408 {
4409 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004410 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4411 __FUNCTION__, static_cast<void*>(this),
4412 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004413 Halt();
4414 }
4415 continue;
4416 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004417
4418 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4419
4420 if (internal_state != eStateInvalid)
4421 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004422 if (m_clear_thread_plans_on_stop &&
4423 StateIsStoppedState(internal_state, true))
4424 {
4425 m_clear_thread_plans_on_stop = false;
4426 m_thread_list.DiscardThreadPlans();
4427 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004428 HandlePrivateEvent (event_sp);
4429 }
4430
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004431 if (internal_state == eStateInvalid ||
4432 internal_state == eStateExited ||
4433 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004434 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004435 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004436 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4437 __FUNCTION__, static_cast<void*>(this), GetID(),
4438 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004439
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004440 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004441 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004442 }
4443
Caroline Tice20ad3c42010-10-29 21:48:37 +00004444 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004445 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004446 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4447 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004448
Ed Maste64fad602013-07-29 20:58:06 +00004449 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004450 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004451 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004452 return NULL;
4453}
4454
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004455//------------------------------------------------------------------
4456// Process Event Data
4457//------------------------------------------------------------------
4458
4459Process::ProcessEventData::ProcessEventData () :
4460 EventData (),
4461 m_process_sp (),
4462 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004463 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004464 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004465 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004466{
4467}
4468
4469Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4470 EventData (),
4471 m_process_sp (process_sp),
4472 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004473 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004474 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004475 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004476{
4477}
4478
4479Process::ProcessEventData::~ProcessEventData()
4480{
4481}
4482
4483const ConstString &
4484Process::ProcessEventData::GetFlavorString ()
4485{
4486 static ConstString g_flavor ("Process::ProcessEventData");
4487 return g_flavor;
4488}
4489
4490const ConstString &
4491Process::ProcessEventData::GetFlavor () const
4492{
4493 return ProcessEventData::GetFlavorString ();
4494}
4495
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004496void
4497Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4498{
4499 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004500 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4501 // the public event queue, then other times when we're pretending that this is where we stopped at the
4502 // end of expression evaluation. m_update_state is used to distinguish these
4503 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004504 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004505 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004506 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004507
Jim Ingham221d51c2013-05-08 00:35:16 +00004508 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004509
4510 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4511 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4512 // end up restarting the process.
4513 if (m_interrupted)
4514 return;
4515
4516 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004517 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004518 {
4519 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004520 uint32_t num_threads = curr_thread_list.GetSize();
4521 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004522
Jim Ingham4b536182011-08-09 02:12:22 +00004523 // The actions might change one of the thread's stop_info's opinions about whether we should
4524 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004525
4526 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4527 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4528 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4529 // 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
4530 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004531 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004532 for (idx = 0; idx < num_threads; ++idx)
4533 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4534
Jim Inghamc7078c22012-12-13 22:24:15 +00004535 // Use this to track whether we should continue from here. We will only continue the target running if
4536 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4537 // then it doesn't matter what the other threads say...
4538
4539 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004540
Jim Ingham0ad7e052013-04-25 02:04:59 +00004541 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4542 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4543 // thing to do is, and it's better to let the user decide than continue behind their backs.
4544
4545 bool does_anybody_have_an_opinion = false;
4546
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004547 for (idx = 0; idx < num_threads; ++idx)
4548 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004549 curr_thread_list = m_process_sp->GetThreadList();
4550 if (curr_thread_list.GetSize() != num_threads)
4551 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004552 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004553 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004554 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 +00004555 break;
4556 }
4557
4558 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4559
4560 if (thread_sp->GetIndexID() != thread_index_array[idx])
4561 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004562 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004563 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004564 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004565 idx,
4566 thread_index_array[idx],
4567 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004568 break;
4569 }
4570
Jim Inghamb15bfc72010-10-20 00:39:53 +00004571 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004572 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004573 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004574 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004575 bool this_thread_wants_to_stop;
4576 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004577 {
Jim Ingham0161b492013-02-09 01:29:05 +00004578 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4579 }
4580 else
4581 {
4582 stop_info_sp->PerformAction(event_ptr);
4583 // The stop action might restart the target. If it does, then we want to mark that in the
4584 // event so that whoever is receiving it will know to wait for the running event and reflect
4585 // that state appropriately.
4586 // We also need to stop processing actions, since they aren't expecting the target to be running.
4587
4588 // FIXME: we might have run.
4589 if (stop_info_sp->HasTargetRunSinceMe())
4590 {
4591 SetRestarted (true);
4592 break;
4593 }
4594
4595 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004596 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004597
Jim Inghamc7078c22012-12-13 22:24:15 +00004598 if (still_should_stop == false)
4599 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004600 }
4601 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004602
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004603
Jim Inghama8ca6e22013-05-03 23:04:37 +00004604 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004605 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004606 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004607 {
4608 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004609 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004610 // Use the public resume method here, since this is just
4611 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004612 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004613 }
4614 else
4615 {
4616 // If we didn't restart, run the Stop Hooks here:
4617 // They might also restart the target, so watch for that.
4618 m_process_sp->GetTarget().RunStopHooks();
4619 if (m_process_sp->GetPrivateState() == eStateRunning)
4620 SetRestarted(true);
4621 }
Jim Ingham9575d842011-03-11 03:53:59 +00004622 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004623 }
4624}
4625
4626void
4627Process::ProcessEventData::Dump (Stream *s) const
4628{
4629 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004630 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4631 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004632
Greg Clayton8b82f082011-04-12 05:54:46 +00004633 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004634}
4635
4636const Process::ProcessEventData *
4637Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4638{
4639 if (event_ptr)
4640 {
4641 const EventData *event_data = event_ptr->GetData();
4642 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4643 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4644 }
4645 return NULL;
4646}
4647
4648ProcessSP
4649Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4650{
4651 ProcessSP process_sp;
4652 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4653 if (data)
4654 process_sp = data->GetProcessSP();
4655 return process_sp;
4656}
4657
4658StateType
4659Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4660{
4661 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4662 if (data == NULL)
4663 return eStateInvalid;
4664 else
4665 return data->GetState();
4666}
4667
4668bool
4669Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4670{
4671 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4672 if (data == NULL)
4673 return false;
4674 else
4675 return data->GetRestarted();
4676}
4677
4678void
4679Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4680{
4681 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4682 if (data != NULL)
4683 data->SetRestarted(new_value);
4684}
4685
Jim Ingham0161b492013-02-09 01:29:05 +00004686size_t
4687Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4688{
4689 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4690 if (data != NULL)
4691 return data->GetNumRestartedReasons();
4692 else
4693 return 0;
4694}
4695
4696const char *
4697Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4698{
4699 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4700 if (data != NULL)
4701 return data->GetRestartedReasonAtIndex(idx);
4702 else
4703 return NULL;
4704}
4705
4706void
4707Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4708{
4709 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4710 if (data != NULL)
4711 data->AddRestartedReason(reason);
4712}
4713
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004714bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004715Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4716{
4717 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4718 if (data == NULL)
4719 return false;
4720 else
4721 return data->GetInterrupted ();
4722}
4723
4724void
4725Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4726{
4727 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4728 if (data != NULL)
4729 data->SetInterrupted(new_value);
4730}
4731
4732bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004733Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4734{
4735 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4736 if (data)
4737 {
4738 data->SetUpdateStateOnRemoval();
4739 return true;
4740 }
4741 return false;
4742}
4743
Greg Claytond9e416c2012-02-18 05:35:26 +00004744lldb::TargetSP
4745Process::CalculateTarget ()
4746{
4747 return m_target.shared_from_this();
4748}
4749
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004750void
Greg Clayton0603aa92010-10-04 01:05:56 +00004751Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004752{
Greg Claytonc14ee322011-09-22 04:58:26 +00004753 exe_ctx.SetTargetPtr (&m_target);
4754 exe_ctx.SetProcessPtr (this);
4755 exe_ctx.SetThreadPtr(NULL);
4756 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004757}
4758
Greg Claytone996fd32011-03-08 22:40:15 +00004759//uint32_t
4760//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4761//{
4762// return 0;
4763//}
4764//
4765//ArchSpec
4766//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4767//{
4768// return Host::GetArchSpecForExistingProcess (pid);
4769//}
4770//
4771//ArchSpec
4772//Process::GetArchSpecForExistingProcess (const char *process_name)
4773//{
4774// return Host::GetArchSpecForExistingProcess (process_name);
4775//}
4776//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004777void
4778Process::AppendSTDOUT (const char * s, size_t len)
4779{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004780 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004781 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004782 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004783}
4784
4785void
Greg Clayton93e86192011-11-13 04:45:22 +00004786Process::AppendSTDERR (const char * s, size_t len)
4787{
4788 Mutex::Locker locker (m_stdio_communication_mutex);
4789 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004790 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004791}
4792
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004793void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004794Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004795{
4796 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004797 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004798 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4799}
4800
4801size_t
4802Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4803{
4804 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004805 if (m_profile_data.empty())
4806 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004807
4808 std::string &one_profile_data = m_profile_data.front();
4809 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004810 if (bytes_available > 0)
4811 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004812 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004813 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004814 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4815 static_cast<void*>(buf),
4816 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004817 if (bytes_available > buf_size)
4818 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004819 memcpy(buf, one_profile_data.c_str(), buf_size);
4820 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004821 bytes_available = buf_size;
4822 }
4823 else
4824 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004825 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004826 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004827 }
4828 }
4829 return bytes_available;
4830}
4831
4832
Greg Clayton93e86192011-11-13 04:45:22 +00004833//------------------------------------------------------------------
4834// Process STDIO
4835//------------------------------------------------------------------
4836
4837size_t
4838Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4839{
4840 Mutex::Locker locker(m_stdio_communication_mutex);
4841 size_t bytes_available = m_stdout_data.size();
4842 if (bytes_available > 0)
4843 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004844 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004845 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004846 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4847 static_cast<void*>(buf),
4848 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004849 if (bytes_available > buf_size)
4850 {
4851 memcpy(buf, m_stdout_data.c_str(), buf_size);
4852 m_stdout_data.erase(0, buf_size);
4853 bytes_available = buf_size;
4854 }
4855 else
4856 {
4857 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4858 m_stdout_data.clear();
4859 }
4860 }
4861 return bytes_available;
4862}
4863
4864
4865size_t
4866Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4867{
4868 Mutex::Locker locker(m_stdio_communication_mutex);
4869 size_t bytes_available = m_stderr_data.size();
4870 if (bytes_available > 0)
4871 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004872 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004873 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004874 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4875 static_cast<void*>(buf),
4876 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004877 if (bytes_available > buf_size)
4878 {
4879 memcpy(buf, m_stderr_data.c_str(), buf_size);
4880 m_stderr_data.erase(0, buf_size);
4881 bytes_available = buf_size;
4882 }
4883 else
4884 {
4885 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4886 m_stderr_data.clear();
4887 }
4888 }
4889 return bytes_available;
4890}
4891
4892void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004893Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4894{
4895 Process *process = (Process *) baton;
4896 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4897}
4898
Greg Clayton44d93782014-01-27 23:43:24 +00004899class IOHandlerProcessSTDIO :
4900 public IOHandler
4901{
4902public:
4903 IOHandlerProcessSTDIO (Process *process,
4904 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00004905 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00004906 m_process (process),
4907 m_read_file (),
4908 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004909 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004910 {
4911 m_read_file.SetDescriptor(GetInputFD(), false);
4912 }
4913
4914 virtual
4915 ~IOHandlerProcessSTDIO ()
4916 {
4917
4918 }
4919
4920 bool
4921 OpenPipes ()
4922 {
Greg Clayton100eb932014-07-02 21:10:39 +00004923 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004924 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004925 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004926 }
4927
4928 void
4929 ClosePipes()
4930 {
Greg Clayton100eb932014-07-02 21:10:39 +00004931 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004932 }
4933
4934 // Each IOHandler gets to run until it is done. It should read data
4935 // from the "in" and place output into "out" and "err and return
4936 // when done.
4937 virtual void
4938 Run ()
4939 {
4940 if (m_read_file.IsValid() && m_write_file.IsValid())
4941 {
4942 SetIsDone(false);
4943 if (OpenPipes())
4944 {
4945 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004946 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004947 TerminalState terminal_state;
4948 terminal_state.Save (read_fd, false);
4949 Terminal terminal(read_fd);
4950 terminal.SetCanonical(false);
4951 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004952// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004953#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004954 while (!GetIsDone())
4955 {
4956 fd_set read_fdset;
4957 FD_ZERO (&read_fdset);
4958 FD_SET (read_fd, &read_fdset);
4959 FD_SET (pipe_read_fd, &read_fdset);
4960 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4961 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4962 if (num_set_fds < 0)
4963 {
4964 const int select_errno = errno;
4965
4966 if (select_errno != EINTR)
4967 SetIsDone(true);
4968 }
4969 else if (num_set_fds > 0)
4970 {
4971 char ch = 0;
4972 size_t n;
4973 if (FD_ISSET (read_fd, &read_fdset))
4974 {
4975 n = 1;
4976 if (m_read_file.Read(&ch, n).Success() && n == 1)
4977 {
4978 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4979 SetIsDone(true);
4980 }
4981 else
4982 SetIsDone(true);
4983 }
4984 if (FD_ISSET (pipe_read_fd, &read_fdset))
4985 {
4986 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004987 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004988 {
Greg Clayton100eb932014-07-02 21:10:39 +00004989 switch (ch)
4990 {
4991 case 'q':
4992 SetIsDone(true);
4993 break;
4994 case 'i':
4995 if (StateIsRunningState(m_process->GetState()))
4996 m_process->Halt();
4997 break;
4998 }
Greg Clayton19e11352014-02-26 22:47:33 +00004999 }
Greg Clayton44d93782014-01-27 23:43:24 +00005000 }
5001 }
5002 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00005003#endif
Greg Clayton44d93782014-01-27 23:43:24 +00005004 terminal_state.Restore();
5005
5006 }
5007 else
5008 SetIsDone(true);
5009 }
5010 else
5011 SetIsDone(true);
5012 }
5013
5014 // Hide any characters that have been displayed so far so async
5015 // output can be displayed. Refresh() will be called after the
5016 // output has been displayed.
5017 virtual void
5018 Hide ()
5019 {
5020
5021 }
5022 // Called when the async output has been received in order to update
5023 // the input reader (refresh the prompt and redisplay any current
5024 // line(s) that are being edited
5025 virtual void
5026 Refresh ()
5027 {
5028
5029 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005030
Greg Clayton44d93782014-01-27 23:43:24 +00005031 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00005032 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00005033 {
Greg Clayton19e11352014-02-26 22:47:33 +00005034 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00005035 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00005036 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005037
Greg Claytonf0066ad2014-05-02 00:45:31 +00005038 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00005039 Interrupt ()
5040 {
Greg Clayton19e11352014-02-26 22:47:33 +00005041 // Do only things that are safe to do in an interrupt context (like in
5042 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5043 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5044 // that was written to the pipe and then call m_process->Halt() from a
5045 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005046 if (m_active)
5047 {
5048 char ch = 'i'; // Send 'i' for interrupt
5049 return m_pipe.Write (&ch, 1) == 1;
5050 }
5051 else
5052 {
5053 // This IOHandler might be pushed on the stack, but not being run currently
5054 // so do the right thing if we aren't actively watching for STDIN by sending
5055 // the interrupt to the process. Otherwise the write to the pipe above would
5056 // do nothing. This can happen when the command interpreter is running and
5057 // gets a "expression ...". It will be on the IOHandler thread and sending
5058 // the input is complete to the delegate which will cause the expression to
5059 // run, which will push the process IO handler, but not run it.
5060
5061 if (StateIsRunningState(m_process->GetState()))
5062 {
5063 m_process->SendAsyncInterrupt();
5064 return true;
5065 }
5066 }
5067 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005068 }
Greg Clayton44d93782014-01-27 23:43:24 +00005069
5070 virtual void
5071 GotEOF()
5072 {
5073
5074 }
5075
5076protected:
5077 Process *m_process;
5078 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5079 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005080 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005081};
5082
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005083void
Greg Clayton44d93782014-01-27 23:43:24 +00005084Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005085{
5086 // First set up the Read Thread for reading/handling process I/O
5087
Greg Clayton44d93782014-01-27 23:43:24 +00005088 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005089
5090 if (conn_ap.get())
5091 {
5092 m_stdio_communication.SetConnection (conn_ap.release());
5093 if (m_stdio_communication.IsConnected())
5094 {
5095 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5096 m_stdio_communication.StartReadThread();
5097
5098 // Now read thread is set up, set up input reader.
5099
5100 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005101 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005102 }
5103 }
5104}
5105
Greg Claytonb4874f12014-02-28 18:22:24 +00005106bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005107Process::ProcessIOHandlerIsActive ()
5108{
5109 IOHandlerSP io_handler_sp (m_process_input_reader);
5110 if (io_handler_sp)
5111 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5112 return false;
5113}
5114bool
Greg Clayton44d93782014-01-27 23:43:24 +00005115Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005116{
Greg Clayton44d93782014-01-27 23:43:24 +00005117 IOHandlerSP io_handler_sp (m_process_input_reader);
5118 if (io_handler_sp)
5119 {
5120 io_handler_sp->SetIsDone(false);
5121 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005122 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005123 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005124 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005125}
5126
Greg Claytonb4874f12014-02-28 18:22:24 +00005127bool
Greg Clayton44d93782014-01-27 23:43:24 +00005128Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005129{
Greg Clayton44d93782014-01-27 23:43:24 +00005130 IOHandlerSP io_handler_sp (m_process_input_reader);
5131 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005132 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5133 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005134}
5135
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005136// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005137void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005138Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005139{
Greg Clayton6920b522012-08-22 18:39:03 +00005140 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005141}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005142
Greg Clayton99d0faf2010-11-18 23:32:35 +00005143void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005144Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005145{
Greg Clayton6920b522012-08-22 18:39:03 +00005146 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005147}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005148
Jim Ingham1624a2d2014-05-05 02:26:40 +00005149ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005150Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005151 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005152 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005153 Stream &errors)
5154{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005155 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005156
Jim Ingham77787032011-01-20 02:03:18 +00005157 if (thread_plan_sp.get() == NULL)
5158 {
5159 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005160 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005161 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005162
Jim Ingham7d7931d2013-03-28 00:05:34 +00005163 if (!thread_plan_sp->ValidatePlan(NULL))
5164 {
5165 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005166 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005167 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005168
Greg Claytonc14ee322011-09-22 04:58:26 +00005169 if (exe_ctx.GetProcessPtr() != this)
5170 {
5171 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005172 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005173 }
5174
5175 Thread *thread = exe_ctx.GetThreadPtr();
5176 if (thread == NULL)
5177 {
5178 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005179 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005180 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005181
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005182 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5183 // For that to be true the plan can't be private - since private plans suppress themselves in the
5184 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005185
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005186 bool orig_plan_private = thread_plan_sp->GetPrivate();
5187 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005188
Jim Ingham444586b2011-01-24 06:34:17 +00005189 if (m_private_state.GetValue() != eStateStopped)
5190 {
5191 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005192 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005193 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005194
Jim Ingham66243842011-08-13 00:56:10 +00005195 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005196 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005197 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005198 if (!selected_frame_sp)
5199 {
5200 thread->SetSelectedFrame(0);
5201 selected_frame_sp = thread->GetSelectedFrame();
5202 if (!selected_frame_sp)
5203 {
5204 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005205 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005206 }
5207 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005208
Jim Ingham11b0e052013-02-19 23:22:45 +00005209 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005210
5211 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5212 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005213
Greg Claytonc14ee322011-09-22 04:58:26 +00005214 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005215
Jim Ingham66243842011-08-13 00:56:10 +00005216 uint32_t selected_tid;
5217 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005218 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005219 {
5220 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005221 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005222 }
5223 else
5224 {
5225 selected_tid = LLDB_INVALID_THREAD_ID;
5226 }
5227
Zachary Turner39de3112014-09-09 20:54:56 +00005228 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005229 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005230 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005231
Greg Clayton5160ce52013-03-27 23:08:40 +00005232 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005233 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005234 {
Jim Ingham076b3042012-04-10 01:21:57 +00005235 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5236 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005237 // 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 +00005238 // we are fielding public events here.
5239 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005240 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 +00005241
Jim Ingham372787f2012-04-07 00:00:41 +00005242 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005243
5244 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5245 // returning control here.
5246 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5247 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5248 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5249 // do just what we want.
5250 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5251 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5252 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5253 old_state = m_public_state.GetValue();
5254 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005255
Jim Ingham076b3042012-04-10 01:21:57 +00005256 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005257 StartPrivateStateThread(true);
5258 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005259
Jim Ingham372787f2012-04-07 00:00:41 +00005260 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005261
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005262 if (options.GetDebug())
5263 {
5264 // In this case, we aren't actually going to run, we just want to stop right away.
5265 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5266 // FIXME: To make this prettier we should invent some stop reason for this, but that
5267 // is only cosmetic, and this functionality is only of use to lldb developers who can
5268 // live with not pretty...
5269 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005270 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005271 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005272
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005273 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005274
Sean Callanana46ec452012-07-11 21:31:24 +00005275 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005276
Jim Ingham77787032011-01-20 02:03:18 +00005277 {
Sean Callanana46ec452012-07-11 21:31:24 +00005278 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5279 // restored on exit to the function.
5280 //
5281 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5282 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005283
Sean Callanana46ec452012-07-11 21:31:24 +00005284 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005285
Jim Inghamf48169b2010-11-30 02:22:11 +00005286 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005287 {
5288 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005289 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005290 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005291 thread->GetIndexID(),
5292 thread->GetID(),
5293 s.GetData());
5294 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005295
Sean Callanana46ec452012-07-11 21:31:24 +00005296 bool got_event;
5297 lldb::EventSP event_sp;
5298 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005299
Sean Callanana46ec452012-07-11 21:31:24 +00005300 TimeValue* timeout_ptr = NULL;
5301 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005302
Jim Ingham0161b492013-02-09 01:29:05 +00005303 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 +00005304 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005305 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005306 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005307
Jim Ingham0161b492013-02-09 01:29:05 +00005308 // This is just for accounting:
5309 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005310
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005311 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005312 uint32_t one_thread_timeout_usec;
5313 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005314
5315 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5316 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5317 // first timeout already.
5318
5319 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005320 {
5321 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005322 one_thread_timeout_usec = 0;
5323 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005324 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005325 else
Jim Ingham0161b492013-02-09 01:29:05 +00005326 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005327 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005328
Jim Ingham914f4e72014-03-28 21:58:28 +00005329 // If the overall wait is forever, then we only need to set the one thread timeout:
5330 if (timeout_usec == 0)
5331 {
Ed Maste801335c2014-03-31 19:28:14 +00005332 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005333 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005334 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005335 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005336 }
Jim Ingham0161b492013-02-09 01:29:05 +00005337 else
5338 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005339 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5340 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5341 uint64_t computed_one_thread_timeout;
5342 if (option_one_thread_timeout != 0)
5343 {
5344 if (timeout_usec < option_one_thread_timeout)
5345 {
5346 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005347 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005348 }
5349 computed_one_thread_timeout = option_one_thread_timeout;
5350 }
5351 else
5352 {
5353 computed_one_thread_timeout = timeout_usec / 2;
5354 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5355 computed_one_thread_timeout = default_one_thread_timeout_usec;
5356 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005357 one_thread_timeout_usec = computed_one_thread_timeout;
5358 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5359
Jim Ingham0161b492013-02-09 01:29:05 +00005360 }
Jim Ingham0161b492013-02-09 01:29:05 +00005361 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005362
5363 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005364 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 +00005365 options.GetStopOthers(),
5366 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005367 before_first_timeout,
5368 one_thread_timeout_usec,
5369 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005370
Jim Ingham1460e4b2014-01-10 23:46:59 +00005371 // This isn't going to work if there are unfetched events on the queue.
5372 // Are there cases where we might want to run the remaining events here, and then try to
5373 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005374
Jim Ingham1460e4b2014-01-10 23:46:59 +00005375 Event *other_events = listener.PeekAtNextEvent();
5376 if (other_events != NULL)
5377 {
5378 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005379 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005380 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005381
Jim Ingham1460e4b2014-01-10 23:46:59 +00005382 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5383 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5384 // event coalescing to cause us to lose OUR running event...
5385 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005386
Jim Ingham8559a352012-11-26 23:52:18 +00005387 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5388 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005389
5390#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5391 // It's pretty much impossible to write test cases for things like:
5392 // One thread timeout expires, I go to halt, but the process already stopped
5393 // on the function call stop breakpoint. Turning on this define will make us not
5394 // fetch the first event till after the halt. So if you run a quick function, it will have
5395 // completed, and the completion event will be waiting, when you interrupt for halt.
5396 // The expression evaluation should still succeed.
5397 bool miss_first_event = true;
5398#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005399 TimeValue one_thread_timeout;
5400 TimeValue final_timeout;
5401
Jim Ingham35878c42014-04-08 21:33:21 +00005402
Sean Callanana46ec452012-07-11 21:31:24 +00005403 while (1)
5404 {
5405 // We usually want to resume the process if we get to the top of the loop.
5406 // The only exception is if we get two running events with no intervening
5407 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005408 if (log)
5409 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5410 do_resume,
5411 handle_running_event,
5412 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005413
Jim Ingham184e9812013-01-15 02:47:48 +00005414 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005415 {
5416 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005417
Jim Ingham184e9812013-01-15 02:47:48 +00005418 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005419 {
Jim Ingham0161b492013-02-09 01:29:05 +00005420 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005421 Error resume_error = PrivateResume ();
5422 if (!resume_error.Success())
5423 {
Jim Ingham0161b492013-02-09 01:29:05 +00005424 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5425 num_resumes,
5426 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005427 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005428 break;
5429 }
Sean Callanana46ec452012-07-11 21:31:24 +00005430 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005431
Jim Ingham0161b492013-02-09 01:29:05 +00005432 TimeValue resume_timeout = TimeValue::Now();
5433 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005434
Jim Ingham0161b492013-02-09 01:29:05 +00005435 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005436 if (!got_event)
5437 {
5438 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005439 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5440 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005441
Jim Ingham0161b492013-02-09 01:29:05 +00005442 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005443 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005444 break;
5445 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005446
Sean Callanana46ec452012-07-11 21:31:24 +00005447 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005448
Sean Callanana46ec452012-07-11 21:31:24 +00005449 if (stop_state != eStateRunning)
5450 {
Jim Ingham0161b492013-02-09 01:29:05 +00005451 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005452
Jim Ingham0161b492013-02-09 01:29:05 +00005453 if (stop_state == eStateStopped)
5454 {
5455 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5456 if (log)
5457 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5458 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5459 num_resumes,
5460 StateAsCString(stop_state),
5461 restarted,
5462 do_resume,
5463 handle_running_event);
5464 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005465
Jim Ingham0161b492013-02-09 01:29:05 +00005466 if (restarted)
5467 {
5468 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5469 // event here. But if I do, the best thing is to Halt and then get out of here.
5470 Halt();
5471 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005472
Jim Ingham35e1bda2012-10-16 21:41:58 +00005473 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5474 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005475 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005476 break;
5477 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005478
Sean Callanana46ec452012-07-11 21:31:24 +00005479 if (log)
5480 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5481 // We need to call the function synchronously, so spin waiting for it to return.
5482 // If we get interrupted while executing, we're going to lose our context, and
5483 // won't be able to gather the result at this point.
5484 // We set the timeout AFTER the resume, since the resume takes some time and we
5485 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005486 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005487 else
5488 {
Sean Callanana46ec452012-07-11 21:31:24 +00005489 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005490 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005491 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005492
Jim Ingham0161b492013-02-09 01:29:05 +00005493 if (before_first_timeout)
5494 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005495 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005496 {
5497 one_thread_timeout = TimeValue::Now();
5498 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005499 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005500 }
Jim Ingham0161b492013-02-09 01:29:05 +00005501 else
5502 {
5503 if (timeout_usec == 0)
5504 timeout_ptr = NULL;
5505 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005506 {
5507 final_timeout = TimeValue::Now();
5508 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005509 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005510 }
Jim Ingham0161b492013-02-09 01:29:05 +00005511 }
5512 }
5513 else
5514 {
5515 if (timeout_usec == 0)
5516 timeout_ptr = NULL;
5517 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005518 {
5519 final_timeout = TimeValue::Now();
5520 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005521 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005522 }
Jim Ingham0161b492013-02-09 01:29:05 +00005523 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005524
Jim Ingham0161b492013-02-09 01:29:05 +00005525 do_resume = true;
5526 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005527
Sean Callanana46ec452012-07-11 21:31:24 +00005528 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005529 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005530
Jim Ingham0f16e732011-02-08 05:20:59 +00005531 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005532 {
Sean Callanana46ec452012-07-11 21:31:24 +00005533 if (timeout_ptr)
5534 {
Matt Kopec676a4872013-02-21 23:55:31 +00005535 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005536 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5537 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005538 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005539 else
Sean Callanana46ec452012-07-11 21:31:24 +00005540 {
5541 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5542 }
5543 }
Jim Ingham35878c42014-04-08 21:33:21 +00005544
5545#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5546 // See comment above...
5547 if (miss_first_event)
5548 {
5549 usleep(1000);
5550 miss_first_event = false;
5551 got_event = false;
5552 }
5553 else
5554#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005555 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005556
Sean Callanana46ec452012-07-11 21:31:24 +00005557 if (got_event)
5558 {
5559 if (event_sp.get())
5560 {
5561 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005562 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005563 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005564 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005565 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005566 errors.Printf ("Execution halted by user interrupt.");
5567 if (log)
5568 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005569 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005570 }
5571 else
5572 {
5573 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5574 if (log)
5575 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005576
Jim Inghamcfc09352012-07-27 23:57:19 +00005577 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005578 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005579 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005580 {
Jim Ingham0161b492013-02-09 01:29:05 +00005581 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005582 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5583 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005584 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005585 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005586 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005587 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005588 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005589 }
5590 else
5591 {
Jim Ingham0161b492013-02-09 01:29:05 +00005592 // If we were restarted, we just need to go back up to fetch another event.
5593 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005594 {
5595 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005596 {
5597 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5598 }
5599 keep_going = true;
5600 do_resume = false;
5601 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005602
Jim Inghamcfc09352012-07-27 23:57:19 +00005603 }
5604 else
5605 {
Jim Ingham0161b492013-02-09 01:29:05 +00005606 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5607 StopReason stop_reason = eStopReasonInvalid;
5608 if (stop_info_sp)
5609 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005610
Jim Ingham0161b492013-02-09 01:29:05 +00005611 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5612 // it is OUR plan that is complete?
5613 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005614 {
5615 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005616 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5617 // Now mark this plan as private so it doesn't get reported as the stop reason
5618 // after this point.
5619 if (thread_plan_sp)
5620 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005621 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005622 }
5623 else
5624 {
Jim Ingham0161b492013-02-09 01:29:05 +00005625 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005626 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005627 {
5628 if (log)
5629 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005630 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005631 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005632 {
5633 event_to_broadcast_sp = event_sp;
5634 }
Jim Ingham0161b492013-02-09 01:29:05 +00005635 }
Jim Ingham184e9812013-01-15 02:47:48 +00005636 else
Jim Ingham0161b492013-02-09 01:29:05 +00005637 {
5638 if (log)
5639 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005640 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005641 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005642 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005643 }
Jim Ingham184e9812013-01-15 02:47:48 +00005644 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005645 }
Sean Callanana46ec452012-07-11 21:31:24 +00005646 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005647 }
5648 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005649
Jim Inghamcfc09352012-07-27 23:57:19 +00005650 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005651 // This shouldn't really happen, but sometimes we do get two running events without an
5652 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005653 do_resume = false;
5654 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005655 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005656 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005657
Jim Inghamcfc09352012-07-27 23:57:19 +00005658 default:
5659 if (log)
5660 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005661
Jim Inghamcfc09352012-07-27 23:57:19 +00005662 if (stop_state == eStateExited)
5663 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005664
Sean Callananbf154da2012-08-08 17:35:10 +00005665 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005666 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005667 break;
5668 }
Sean Callanana46ec452012-07-11 21:31:24 +00005669 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005670
Sean Callanana46ec452012-07-11 21:31:24 +00005671 if (keep_going)
5672 continue;
5673 else
5674 break;
5675 }
5676 else
5677 {
5678 if (log)
5679 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005680 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005681 break;
5682 }
5683 }
5684 else
5685 {
5686 // If we didn't get an event that means we've timed out...
5687 // We will interrupt the process here. Depending on what we were asked to do we will
5688 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005689
Sean Callanana46ec452012-07-11 21:31:24 +00005690 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005691 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005692 {
Jim Ingham0161b492013-02-09 01:29:05 +00005693 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005694 {
5695 if (timeout_usec != 0)
5696 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005697 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005698 "running for %" PRIu32 " usec with all threads enabled.",
5699 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005700 }
5701 else
5702 {
5703 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005704 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005705 }
5706 }
Sean Callanana46ec452012-07-11 21:31:24 +00005707 else
5708 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005709 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005710 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005711 }
5712 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005713 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005714 "abandoning execution.",
5715 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005716 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005717
Jim Ingham0161b492013-02-09 01:29:05 +00005718 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5719 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5720 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5721 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5722 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005723
Jim Ingham0161b492013-02-09 01:29:05 +00005724 bool back_to_top = true;
5725 uint32_t try_halt_again = 0;
5726 bool do_halt = true;
5727 const uint32_t num_retries = 5;
5728 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005729 {
Jim Ingham0161b492013-02-09 01:29:05 +00005730 Error halt_error;
5731 if (do_halt)
5732 {
5733 if (log)
5734 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5735 halt_error = Halt();
5736 }
5737 if (halt_error.Success())
5738 {
5739 if (log)
5740 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005741
Jim Ingham0161b492013-02-09 01:29:05 +00005742 real_timeout = TimeValue::Now();
5743 real_timeout.OffsetWithMicroSeconds(500000);
5744
5745 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005746
Jim Ingham0161b492013-02-09 01:29:05 +00005747 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005748 {
Jim Ingham0161b492013-02-09 01:29:05 +00005749 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5750 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005751 {
Jim Ingham0161b492013-02-09 01:29:05 +00005752 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5753 if (stop_state == lldb::eStateStopped
5754 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5755 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005756 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005757
Jim Ingham0161b492013-02-09 01:29:05 +00005758 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005759 {
Jim Ingham0161b492013-02-09 01:29:05 +00005760 // Between the time we initiated the Halt and the time we delivered it, the process could have
5761 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005762
Jim Ingham0161b492013-02-09 01:29:05 +00005763 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5764 {
5765 if (log)
5766 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5767 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005768 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005769 back_to_top = false;
5770 break;
5771 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005772
Jim Ingham0161b492013-02-09 01:29:05 +00005773 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5774 {
5775 if (log)
5776 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5777 "Exiting wait loop.");
5778 try_halt_again++;
5779 do_halt = false;
5780 continue;
5781 }
Sean Callanana46ec452012-07-11 21:31:24 +00005782
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005783 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005784 {
5785 if (log)
5786 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005787 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005788 back_to_top = false;
5789 break;
5790 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005791
Jim Ingham0161b492013-02-09 01:29:05 +00005792 if (before_first_timeout)
5793 {
5794 // Set all the other threads to run, and return to the top of the loop, which will continue;
5795 before_first_timeout = false;
5796 thread_plan_sp->SetStopOthers (false);
5797 if (log)
5798 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005799
Jim Ingham0161b492013-02-09 01:29:05 +00005800 back_to_top = true;
5801 break;
5802 }
5803 else
5804 {
5805 // Running all threads failed, so return Interrupted.
5806 if (log)
5807 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005808 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005809 back_to_top = false;
5810 break;
5811 }
Sean Callanana46ec452012-07-11 21:31:24 +00005812 }
5813 }
5814 else
Jim Ingham0161b492013-02-09 01:29:05 +00005815 { if (log)
5816 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5817 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005818 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005819 back_to_top = false;
5820 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005821 }
5822 }
Jim Ingham0161b492013-02-09 01:29:05 +00005823 else
5824 {
5825 try_halt_again++;
5826 continue;
5827 }
Sean Callanana46ec452012-07-11 21:31:24 +00005828 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005829
Jim Ingham0161b492013-02-09 01:29:05 +00005830 if (!back_to_top || try_halt_again > num_retries)
5831 break;
5832 else
5833 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005834 }
Sean Callanana46ec452012-07-11 21:31:24 +00005835 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005836
Sean Callanana46ec452012-07-11 21:31:24 +00005837 // 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 +00005838 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005839 {
5840 StopPrivateStateThread();
5841 Error error;
5842 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005843 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005844 {
5845 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5846 }
Jason Molenda76513fd2014-10-15 23:39:31 +00005847 if (old_state != eStateInvalid)
5848 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00005849 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005850
Jim Ingham184e9812013-01-15 02:47:48 +00005851 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5852 // could happen:
5853 // 1) The execution successfully completed
5854 // 2) We hit a breakpoint, and ignore_breakpoints was true
5855 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005856 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5857 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005858
Jim Ingham8646d3c2014-05-05 02:47:44 +00005859 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005860 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005861 {
5862 thread_plan_sp->RestoreThreadState();
5863 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005864
Sean Callanana46ec452012-07-11 21:31:24 +00005865 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005866 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005867 {
5868 if (log)
5869 {
5870 StreamString s;
5871 if (event_sp)
5872 event_sp->Dump (&s);
5873 else
5874 {
5875 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5876 }
5877
5878 StreamString ts;
5879
5880 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005881
Sean Callanana46ec452012-07-11 21:31:24 +00005882 do
5883 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005884 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005885 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005886 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005887 break;
5888 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005889 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005890 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005891 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005892 break;
5893 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005894 else
Sean Callanana46ec452012-07-11 21:31:24 +00005895 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005896 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5897
5898 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005899 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005900 event_explanation = "<no event data>";
5901 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005902 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005903
Jim Inghamcfc09352012-07-27 23:57:19 +00005904 Process *process = event_data->GetProcessSP().get();
5905
5906 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005907 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005908 event_explanation = "<no process>";
5909 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005910 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005911
Jim Inghamcfc09352012-07-27 23:57:19 +00005912 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005913
Jim Inghamcfc09352012-07-27 23:57:19 +00005914 uint32_t num_threads = thread_list.GetSize();
5915 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005916
Jim Inghamcfc09352012-07-27 23:57:19 +00005917 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005918
Jim Inghamcfc09352012-07-27 23:57:19 +00005919 for (thread_index = 0;
5920 thread_index < num_threads;
5921 ++thread_index)
5922 {
5923 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005924
Jim Inghamcfc09352012-07-27 23:57:19 +00005925 if (!thread)
5926 {
5927 ts.Printf("<?> ");
5928 continue;
5929 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005930
Daniel Malead01b2952012-11-29 21:49:15 +00005931 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005932 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005933
Jim Inghamcfc09352012-07-27 23:57:19 +00005934 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005935 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005936 else
5937 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005938
Jim Inghamcfc09352012-07-27 23:57:19 +00005939 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5940 if (stop_info_sp)
5941 {
5942 const char *stop_desc = stop_info_sp->GetDescription();
5943 if (stop_desc)
5944 ts.PutCString (stop_desc);
5945 }
5946 ts.Printf(">");
5947 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005948
Jim Inghamcfc09352012-07-27 23:57:19 +00005949 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005950 }
Sean Callanana46ec452012-07-11 21:31:24 +00005951 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005952
Jim Inghamcfc09352012-07-27 23:57:19 +00005953 if (event_explanation)
5954 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005955 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005956 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5957 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005958
Jim Inghame4483cf2013-09-27 01:13:01 +00005959 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005960 {
5961 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005962 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5963 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005964 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5965 thread_plan_sp->SetPrivate (orig_plan_private);
5966 }
5967 else
5968 {
5969 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005970 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5971 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005972 }
5973 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005974 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005975 {
5976 if (log)
5977 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005978
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005979 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005980 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005981 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005982 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005983 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005984 }
5985 else
5986 {
Sean Callanana46ec452012-07-11 21:31:24 +00005987 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005988 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005989 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005990 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005991 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005992 }
5993 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5994 {
5995 if (log)
5996 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005997 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005998 }
5999 else
6000 {
6001 if (log)
6002 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006003 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006004 {
6005 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006006 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006007 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6008 thread_plan_sp->SetPrivate (orig_plan_private);
6009 }
6010 }
6011 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006012
Sean Callanana46ec452012-07-11 21:31:24 +00006013 // Thread we ran the function in may have gone away because we ran the target
6014 // Check that it's still there, and if it is put it back in the context. Also restore the
6015 // frame in the context if it is still present.
6016 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6017 if (thread)
6018 {
6019 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6020 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006021
Sean Callanana46ec452012-07-11 21:31:24 +00006022 // Also restore the current process'es selected frame & thread, since this function calling may
6023 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006024
Sean Callanana46ec452012-07-11 21:31:24 +00006025 if (selected_tid != LLDB_INVALID_THREAD_ID)
6026 {
6027 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6028 {
6029 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006030 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006031 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006032 if (old_frame_sp)
6033 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006034 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006035 }
6036 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006037
Sean Callanana46ec452012-07-11 21:31:24 +00006038 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006039
Sean Callanana46ec452012-07-11 21:31:24 +00006040 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006041 {
Sean Callanana46ec452012-07-11 21:31:24 +00006042 if (log)
6043 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6044 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006045 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006046
Jim Inghamf48169b2010-11-30 02:22:11 +00006047 return return_value;
6048}
6049
6050const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006051Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006052{
6053 const char *result_name;
6054
6055 switch (result)
6056 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006057 case eExpressionCompleted:
6058 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006059 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006060 case eExpressionDiscarded:
6061 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006062 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006063 case eExpressionInterrupted:
6064 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006065 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006066 case eExpressionHitBreakpoint:
6067 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006068 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006069 case eExpressionSetupError:
6070 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006071 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006072 case eExpressionParseError:
6073 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006074 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006075 case eExpressionResultUnavailable:
6076 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006077 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006078 case eExpressionTimedOut:
6079 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006080 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006081 case eExpressionStoppedForDebug:
6082 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006083 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006084 }
6085 return result_name;
6086}
6087
Greg Clayton7260f622011-04-18 08:33:37 +00006088void
6089Process::GetStatus (Stream &strm)
6090{
6091 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006092 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006093 {
6094 if (state == eStateExited)
6095 {
6096 int exit_status = GetExitStatus();
6097 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006098 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006099 GetID(),
6100 exit_status,
6101 exit_status,
6102 exit_description ? exit_description : "");
6103 }
6104 else
6105 {
6106 if (state == eStateConnected)
6107 strm.Printf ("Connected to remote target.\n");
6108 else
Daniel Malead01b2952012-11-29 21:49:15 +00006109 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006110 }
6111 }
6112 else
6113 {
Daniel Malead01b2952012-11-29 21:49:15 +00006114 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006115 }
6116}
6117
6118size_t
6119Process::GetThreadStatus (Stream &strm,
6120 bool only_threads_with_stop_reason,
6121 uint32_t start_frame,
6122 uint32_t num_frames,
6123 uint32_t num_frames_with_source)
6124{
6125 size_t num_thread_infos_dumped = 0;
6126
Jim Ingham4a65fb12014-03-07 11:20:03 +00006127 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6128 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6129 // ID's, and look them up one by one:
6130
6131 uint32_t num_threads;
6132 std::vector<uint32_t> thread_index_array;
6133 //Scope for thread list locker;
6134 {
6135 Mutex::Locker locker (GetThreadList().GetMutex());
6136 ThreadList &curr_thread_list = GetThreadList();
6137 num_threads = curr_thread_list.GetSize();
6138 uint32_t idx;
6139 thread_index_array.resize(num_threads);
6140 for (idx = 0; idx < num_threads; ++idx)
6141 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
6142 }
6143
Greg Clayton7260f622011-04-18 08:33:37 +00006144 for (uint32_t i = 0; i < num_threads; i++)
6145 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006146 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
6147 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006148 {
6149 if (only_threads_with_stop_reason)
6150 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006151 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006152 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006153 continue;
6154 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006155 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006156 start_frame,
6157 num_frames,
6158 num_frames_with_source);
6159 ++num_thread_infos_dumped;
6160 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006161 else
6162 {
6163 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6164 if (log)
6165 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6166
6167 }
Greg Clayton7260f622011-04-18 08:33:37 +00006168 }
6169 return num_thread_infos_dumped;
6170}
6171
Greg Claytona9f40ad2012-02-22 04:37:26 +00006172void
6173Process::AddInvalidMemoryRegion (const LoadRange &region)
6174{
6175 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6176}
6177
6178bool
6179Process::RemoveInvalidMemoryRange (const LoadRange &region)
6180{
6181 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6182}
6183
Jim Ingham372787f2012-04-07 00:00:41 +00006184void
6185Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6186{
6187 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6188}
6189
6190bool
6191Process::RunPreResumeActions ()
6192{
6193 bool result = true;
6194 while (!m_pre_resume_actions.empty())
6195 {
6196 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6197 m_pre_resume_actions.pop_back();
6198 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006199 if (result == true)
6200 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006201 }
6202 return result;
6203}
6204
6205void
6206Process::ClearPreResumeActions ()
6207{
6208 m_pre_resume_actions.clear();
6209}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006210
Greg Claytonfa559e52012-05-18 02:38:05 +00006211void
6212Process::Flush ()
6213{
6214 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006215 m_extended_thread_list.Flush();
6216 m_extended_thread_stop_id = 0;
6217 m_queue_list.Clear();
6218 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006219}
Greg Clayton90ba8112012-12-05 00:16:59 +00006220
6221void
6222Process::DidExec ()
6223{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006224 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6225 if (log)
6226 log->Printf ("Process::%s()", __FUNCTION__);
6227
Greg Clayton90ba8112012-12-05 00:16:59 +00006228 Target &target = GetTarget();
6229 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006230 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006231 m_dynamic_checkers_ap.reset();
6232 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006233 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006234 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006235 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006236 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006237 m_image_tokens.clear();
6238 m_allocated_memory_cache.Clear();
6239 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006240 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006241 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006242 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00006243 DoDidExec();
6244 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006245 // Flush the process (threads and all stack frames) after running CompleteAttach()
6246 // in case the dynamic loader loaded things in new locations.
6247 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006248
6249 // After we figure out what was loaded/unloaded in CompleteAttach,
6250 // we need to let the target know so it can do any cleanup it needs to.
6251 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006252}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006253
Jim Ingham1460e4b2014-01-10 23:46:59 +00006254addr_t
6255Process::ResolveIndirectFunction(const Address *address, Error &error)
6256{
6257 if (address == nullptr)
6258 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006259 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006260 return LLDB_INVALID_ADDRESS;
6261 }
6262
6263 addr_t function_addr = LLDB_INVALID_ADDRESS;
6264
6265 addr_t addr = address->GetLoadAddress(&GetTarget());
6266 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6267 if (iter != m_resolved_indirect_addresses.end())
6268 {
6269 function_addr = (*iter).second;
6270 }
6271 else
6272 {
6273 if (!InferiorCall(this, address, function_addr))
6274 {
6275 Symbol *symbol = address->CalculateSymbolContextSymbol();
6276 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6277 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6278 function_addr = LLDB_INVALID_ADDRESS;
6279 }
6280 else
6281 {
6282 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6283 }
6284 }
6285 return function_addr;
6286}
6287
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006288void
6289Process::ModulesDidLoad (ModuleList &module_list)
6290{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006291 SystemRuntime *sys_runtime = GetSystemRuntime();
6292 if (sys_runtime)
6293 {
6294 sys_runtime->ModulesDidLoad (module_list);
6295 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006296
Kuba Breckaafdf8422014-10-10 23:43:03 +00006297 GetJITLoaders().ModulesDidLoad (module_list);
6298
6299 // Give runtimes a chance to be created.
6300 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6301
6302 // Tell runtimes about new modules.
6303 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6304 {
6305 InstrumentationRuntimeSP runtime = pos->second;
6306 runtime->ModulesDidLoad(module_list);
6307 }
6308
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006309}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006310
6311ThreadCollectionSP
6312Process::GetHistoryThreads(lldb::addr_t addr)
6313{
6314 ThreadCollectionSP threads;
6315
6316 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6317
6318 if (! memory_history.get()) {
6319 return threads;
6320 }
6321
6322 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6323
6324 return threads;
6325}
Kuba Brecka63927542014-10-11 01:59:32 +00006326
6327InstrumentationRuntimeSP
6328Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6329{
6330 InstrumentationRuntimeCollection::iterator pos;
6331 pos = m_instrumentation_runtimes.find (type);
6332 if (pos == m_instrumentation_runtimes.end())
6333 {
6334 return InstrumentationRuntimeSP();
6335 }
6336 else
6337 return (*pos).second;
6338}