blob: d337d8110c893fd9534d589cc9651fbbeab30b70 [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])
483 launch_info.SetShell (option_arg);
484 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000485 launch_info.SetShell (LLDB_DEFAULT_SHELL);
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 Clayton44d93782014-01-27 23:43:24 +0000954Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955{
Jim Ingham4b536182011-08-09 02:12:22 +0000956 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
957 // We have to actually check each event, and in the case of a stopped event check the restarted flag
958 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000959 if (event_sp_ptr)
960 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000961 StateType state = GetState();
962 // If we are exited or detached, we won't ever get back to any
963 // other valid state...
964 if (state == eStateDetached || state == eStateExited)
965 return state;
966
Daniel Malea9e9919f2013-10-09 16:56:28 +0000967 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
968 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000969 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
970 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000971
972 if (!wait_always &&
973 StateIsStoppedState(state, true) &&
974 StateIsStoppedState(GetPrivateState(), true)) {
975 if (log)
976 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
977 __FUNCTION__);
978 return state;
979 }
980
Jim Ingham4b536182011-08-09 02:12:22 +0000981 while (state != eStateInvalid)
982 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000983 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000984 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000985 if (event_sp_ptr && event_sp)
986 *event_sp_ptr = event_sp;
987
Jim Ingham4b536182011-08-09 02:12:22 +0000988 switch (state)
989 {
990 case eStateCrashed:
991 case eStateDetached:
992 case eStateExited:
993 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000994 // We need to toggle the run lock as this won't get done in
995 // SetPublicState() if the process is hijacked.
996 if (hijack_listener)
997 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000998 return state;
999 case eStateStopped:
1000 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1001 continue;
1002 else
Greg Clayton44d93782014-01-27 23:43:24 +00001003 {
1004 // We need to toggle the run lock as this won't get done in
1005 // SetPublicState() if the process is hijacked.
1006 if (hijack_listener)
1007 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001008 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001009 }
Jim Ingham4b536182011-08-09 02:12:22 +00001010 default:
1011 continue;
1012 }
1013 }
1014 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015}
1016
1017
1018StateType
1019Process::WaitForState
1020(
1021 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001022 const StateType *match_states,
1023 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024)
1025{
1026 EventSP event_sp;
1027 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001028 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001029 while (state != eStateInvalid)
1030 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001031 // If we are exited or detached, we won't ever get back to any
1032 // other valid state...
1033 if (state == eStateDetached || state == eStateExited)
1034 return state;
1035
Greg Clayton44d93782014-01-27 23:43:24 +00001036 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037
1038 for (i=0; i<num_match_states; ++i)
1039 {
1040 if (match_states[i] == state)
1041 return state;
1042 }
1043 }
1044 return state;
1045}
1046
Jim Ingham30f9b212010-10-11 23:53:14 +00001047bool
1048Process::HijackProcessEvents (Listener *listener)
1049{
1050 if (listener != NULL)
1051 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001052 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001053 }
1054 else
1055 return false;
1056}
1057
1058void
1059Process::RestoreProcessEvents ()
1060{
1061 RestoreBroadcaster();
1062}
1063
Jim Ingham0f16e732011-02-08 05:20:59 +00001064bool
1065Process::HijackPrivateProcessEvents (Listener *listener)
1066{
1067 if (listener != NULL)
1068 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001069 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001070 }
1071 else
1072 return false;
1073}
1074
1075void
1076Process::RestorePrivateProcessEvents ()
1077{
1078 m_private_state_broadcaster.RestoreBroadcaster();
1079}
1080
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001082Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083{
Greg Clayton5160ce52013-03-27 23:08:40 +00001084 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085
1086 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001087 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1088 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089
Greg Clayton44d93782014-01-27 23:43:24 +00001090 Listener *listener = hijack_listener;
1091 if (listener == NULL)
1092 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001093
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001095 if (listener->WaitForEventForBroadcasterWithType (timeout,
1096 this,
1097 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1098 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001099 {
1100 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1101 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1102 else if (log)
1103 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1104 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105
1106 if (log)
1107 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001108 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109 StateAsCString(state));
1110 return state;
1111}
1112
1113Event *
1114Process::PeekAtStateChangedEvents ()
1115{
Greg Clayton5160ce52013-03-27 23:08:40 +00001116 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117
1118 if (log)
1119 log->Printf ("Process::%s...", __FUNCTION__);
1120
1121 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001122 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1123 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001124 if (log)
1125 {
1126 if (event_ptr)
1127 {
1128 log->Printf ("Process::%s (event_ptr) => %s",
1129 __FUNCTION__,
1130 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1131 }
1132 else
1133 {
1134 log->Printf ("Process::%s no events found",
1135 __FUNCTION__);
1136 }
1137 }
1138 return event_ptr;
1139}
1140
1141StateType
1142Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1143{
Greg Clayton5160ce52013-03-27 23:08:40 +00001144 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145
1146 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001147 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1148 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149
1150 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001151 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1152 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001153 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001154 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001155 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1156 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157
1158 // This is a bit of a hack, but when we wait here we could very well return
1159 // to the command-line, and that could disable the log, which would render the
1160 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001162 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1163 __FUNCTION__, static_cast<const void *>(timeout),
1164 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165 return state;
1166}
1167
1168bool
1169Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1170{
Greg Clayton5160ce52013-03-27 23:08:40 +00001171 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172
1173 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001174 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1175 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176
1177 if (control_only)
1178 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1179 else
1180 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1181}
1182
1183bool
1184Process::IsRunning () const
1185{
1186 return StateIsRunningState (m_public_state.GetValue());
1187}
1188
1189int
1190Process::GetExitStatus ()
1191{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001192 Mutex::Locker locker (m_exit_status_mutex);
1193
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194 if (m_public_state.GetValue() == eStateExited)
1195 return m_exit_status;
1196 return -1;
1197}
1198
Greg Clayton85851dd2010-12-04 00:10:17 +00001199
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200const char *
1201Process::GetExitDescription ()
1202{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001203 Mutex::Locker locker (m_exit_status_mutex);
1204
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1206 return m_exit_string.c_str();
1207 return NULL;
1208}
1209
Greg Clayton6779606a2011-01-22 23:43:18 +00001210bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001211Process::SetExitStatus (int status, const char *cstr)
1212{
Greg Clayton5160ce52013-03-27 23:08:40 +00001213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001214 if (log)
1215 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1216 status, status,
1217 cstr ? "\"" : "",
1218 cstr ? cstr : "NULL",
1219 cstr ? "\"" : "");
1220
Greg Clayton6779606a2011-01-22 23:43:18 +00001221 // We were already in the exited state
1222 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001223 {
Greg Clayton385d6032011-01-26 23:47:29 +00001224 if (log)
1225 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001226 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001227 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001228
Todd Fiala7b0917a2014-09-15 20:07:33 +00001229 // use a mutex to protect the status and string during updating
1230 {
1231 Mutex::Locker locker (m_exit_status_mutex);
1232
1233 m_exit_status = status;
1234 if (cstr)
1235 m_exit_string = cstr;
1236 else
1237 m_exit_string.clear();
1238 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001239
Greg Clayton6779606a2011-01-22 23:43:18 +00001240 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001241
Greg Clayton6779606a2011-01-22 23:43:18 +00001242 SetPrivateState (eStateExited);
1243 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001244}
1245
1246// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001247// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248// found in the global target list (we want to be completely sure that the
1249// lldb_private::Process doesn't go away before we can deliver the signal.
1250bool
Greg Claytone4e45922011-11-16 05:37:56 +00001251Process::SetProcessExitStatus (void *callback_baton,
1252 lldb::pid_t pid,
1253 bool exited,
1254 int signo, // Zero for no signal
1255 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256)
1257{
Greg Clayton5160ce52013-03-27 23:08:40 +00001258 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001259 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001260 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001261 callback_baton,
1262 pid,
1263 exited,
1264 signo,
1265 exit_status);
1266
1267 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268 {
Greg Clayton66111032010-06-23 01:19:29 +00001269 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270 if (target_sp)
1271 {
1272 ProcessSP process_sp (target_sp->GetProcessSP());
1273 if (process_sp)
1274 {
1275 const char *signal_cstr = NULL;
1276 if (signo)
1277 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1278
1279 process_sp->SetExitStatus (exit_status, signal_cstr);
1280 }
1281 }
1282 return true;
1283 }
1284 return false;
1285}
1286
1287
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001288void
1289Process::UpdateThreadListIfNeeded ()
1290{
1291 const uint32_t stop_id = GetStopID();
1292 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1293 {
Greg Clayton2637f822011-11-17 01:23:07 +00001294 const StateType state = GetPrivateState();
1295 if (StateIsStoppedState (state, true))
1296 {
1297 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001298 // m_thread_list does have its own mutex, but we need to
1299 // hold onto the mutex between the call to UpdateThreadList(...)
1300 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001301 ThreadList &old_thread_list = m_thread_list;
1302 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001303 ThreadList new_thread_list(this);
1304 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001305 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001306 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001307 {
Jim Ingham09437922013-03-01 20:04:25 +00001308 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1309 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1310 // shutting us down, causing a deadlock.
1311 if (!m_destroy_in_process)
1312 {
1313 OperatingSystem *os = GetOperatingSystem ();
1314 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001315 {
1316 // Clear any old backing threads where memory threads might have been
1317 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001318 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001319 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001320 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001321
1322 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001323 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1324 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1325 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 +00001326 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001327 else
1328 {
1329 // No OS plug-in, the new thread list is the same as the real thread list
1330 new_thread_list = real_thread_list;
1331 }
Jim Ingham09437922013-03-01 20:04:25 +00001332 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001333
1334 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001335 m_thread_list.Update (new_thread_list);
1336 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001337
Jason Molenda4ff13262013-11-20 00:31:38 +00001338 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1339 {
1340 // Clear any extended threads that we may have accumulated previously
1341 m_extended_thread_list.Clear();
1342 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001343
1344 m_queue_list.Clear();
1345 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001346 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001347 }
Greg Clayton2637f822011-11-17 01:23:07 +00001348 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001349 }
1350}
1351
Jason Molenda5e8dce42013-12-13 00:29:16 +00001352void
1353Process::UpdateQueueListIfNeeded ()
1354{
1355 if (m_system_runtime_ap.get())
1356 {
1357 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1358 {
1359 const StateType state = GetPrivateState();
1360 if (StateIsStoppedState (state, true))
1361 {
1362 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1363 m_queue_list_stop_id = GetLastNaturalStopID();
1364 }
1365 }
1366 }
1367}
1368
Greg Claytona4d87472013-01-18 23:41:08 +00001369ThreadSP
1370Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1371{
1372 OperatingSystem *os = GetOperatingSystem ();
1373 if (os)
1374 return os->CreateThread(tid, context);
1375 return ThreadSP();
1376}
1377
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001378uint32_t
1379Process::GetNextThreadIndexID (uint64_t thread_id)
1380{
1381 return AssignIndexIDToThread(thread_id);
1382}
1383
1384bool
1385Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1386{
1387 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1388 if (iterator == m_thread_id_to_index_id_map.end())
1389 {
1390 return false;
1391 }
1392 else
1393 {
1394 return true;
1395 }
1396}
1397
1398uint32_t
1399Process::AssignIndexIDToThread(uint64_t thread_id)
1400{
1401 uint32_t result = 0;
1402 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1403 if (iterator == m_thread_id_to_index_id_map.end())
1404 {
1405 result = ++m_thread_index_id;
1406 m_thread_id_to_index_id_map[thread_id] = result;
1407 }
1408 else
1409 {
1410 result = iterator->second;
1411 }
1412
1413 return result;
1414}
1415
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416StateType
1417Process::GetState()
1418{
1419 // If any other threads access this we will need a mutex for it
1420 return m_public_state.GetValue ();
1421}
1422
1423void
Jim Ingham221d51c2013-05-08 00:35:16 +00001424Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425{
Greg Clayton5160ce52013-03-27 23:08:40 +00001426 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001428 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001429 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001431
1432 // On the transition from Run to Stopped, we unlock the writer end of the
1433 // run lock. The lock gets locked in Resume, which is the public API
1434 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001435 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1436 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001437 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001438 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001439 if (log)
1440 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001441 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001442 }
1443 else
1444 {
1445 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1446 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001447 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001448 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001449 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001450 {
1451 if (log)
1452 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001453 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001454 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001455 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001456 }
1457 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458}
1459
Jim Ingham3b8285d2012-04-19 01:40:33 +00001460Error
1461Process::Resume ()
1462{
Greg Clayton5160ce52013-03-27 23:08:40 +00001463 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001464 if (log)
1465 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001466 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001467 {
1468 Error error("Resume request failed - process still running.");
1469 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001470 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001471 return error;
1472 }
1473 return PrivateResume();
1474}
1475
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476StateType
1477Process::GetPrivateState ()
1478{
1479 return m_private_state.GetValue();
1480}
1481
1482void
1483Process::SetPrivateState (StateType new_state)
1484{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001485 if (m_finalize_called)
1486 return;
1487
Greg Clayton5160ce52013-03-27 23:08:40 +00001488 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001489 bool state_changed = false;
1490
1491 if (log)
1492 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1493
Andrew Kaylor29d65742013-05-10 17:19:04 +00001494 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001495 Mutex::Locker locker(m_private_state.GetMutex());
1496
1497 const StateType old_state = m_private_state.GetValueNoLock ();
1498 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001499
Greg Claytonaa49c832013-05-03 22:25:56 +00001500 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1501 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1502 if (old_state_is_stopped != new_state_is_stopped)
1503 {
1504 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001505 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001506 else
Ed Maste64fad602013-07-29 20:58:06 +00001507 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001508 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001509
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510 if (state_changed)
1511 {
1512 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001513 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001515 // Note, this currently assumes that all threads in the list
1516 // stop when the process stops. In the future we will want to
1517 // support a debugging model where some threads continue to run
1518 // while others are stopped. When that happens we will either need
1519 // a way for the thread list to identify which threads are stopping
1520 // or create a special thread list containing only threads which
1521 // actually stopped.
1522 //
1523 // The process plugin is responsible for managing the actual
1524 // behavior of the threads and should have stopped any threads
1525 // that are going to stop before we get here.
1526 m_thread_list.DidStop();
1527
Jim Ingham4b536182011-08-09 02:12:22 +00001528 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001529 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001531 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001532 }
1533 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001534 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1535 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1536 else
1537 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001538 }
1539 else
1540 {
1541 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001542 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001543 }
1544}
1545
Jim Ingham0faa43f2011-11-08 03:00:11 +00001546void
1547Process::SetRunningUserExpression (bool on)
1548{
1549 m_mod_id.SetRunningUserExpression (on);
1550}
1551
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001552addr_t
1553Process::GetImageInfoAddress()
1554{
1555 return LLDB_INVALID_ADDRESS;
1556}
1557
Greg Clayton8f343b02010-11-04 01:54:29 +00001558//----------------------------------------------------------------------
1559// LoadImage
1560//
1561// This function provides a default implementation that works for most
1562// unix variants. Any Process subclasses that need to do shared library
1563// loading differently should override LoadImage and UnloadImage and
1564// do what is needed.
1565//----------------------------------------------------------------------
1566uint32_t
1567Process::LoadImage (const FileSpec &image_spec, Error &error)
1568{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001569 char path[PATH_MAX];
1570 image_spec.GetPath(path, sizeof(path));
1571
Greg Clayton8f343b02010-11-04 01:54:29 +00001572 DynamicLoader *loader = GetDynamicLoader();
1573 if (loader)
1574 {
1575 error = loader->CanLoadImage();
1576 if (error.Fail())
1577 return LLDB_INVALID_IMAGE_TOKEN;
1578 }
1579
1580 if (error.Success())
1581 {
1582 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001583
1584 if (thread_sp)
1585 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001586 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001587
1588 if (frame_sp)
1589 {
1590 ExecutionContext exe_ctx;
1591 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001592 EvaluateExpressionOptions expr_options;
1593 expr_options.SetUnwindOnError(true);
1594 expr_options.SetIgnoreBreakpoints(true);
1595 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001596 expr_options.SetResultIsInternal(true);
1597
Greg Clayton8f343b02010-11-04 01:54:29 +00001598 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001599 expr.Printf(R"(
1600 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1601 the_result.image_ptr = dlopen ("%s", 2);
1602 if (the_result.image_ptr == (void *) 0x0)
1603 {
1604 the_result.error_str = dlerror();
1605 }
1606 else
1607 {
1608 the_result.error_str = (const char *) 0x0;
1609 }
1610 the_result;
1611 )",
1612 path);
1613 const char *prefix = R"(
1614 extern "C" void* dlopen (const char *path, int mode);
1615 extern "C" const char *dlerror (void);
1616 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001617 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001618 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001619 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001620 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001621 expr.GetData(),
1622 prefix,
1623 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001624 expr_error);
1625 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001626 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001627 error = result_valobj_sp->GetError();
1628 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001629 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001630 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001631 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1632 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001633 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001634 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1635 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1636 {
1637 uint32_t image_token = m_image_tokens.size();
1638 m_image_tokens.push_back (image_ptr);
1639 return image_token;
1640 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001641 else if (image_ptr == 0)
1642 {
Jim Ingham6971b862014-07-19 00:37:06 +00001643 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1644 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001645 {
Jim Ingham6971b862014-07-19 00:37:06 +00001646 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001647 {
Jim Inghamcf973792014-07-17 21:53:48 +00001648 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001649 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001650 if (error.Success() && num_chars > 0)
1651 {
1652 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001653 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001654 }
1655 }
1656 }
1657 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001658 }
1659 }
1660 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001661 else
1662 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001663 }
1664 }
1665 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001666 if (!error.AsCString())
1667 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001668 return LLDB_INVALID_IMAGE_TOKEN;
1669}
1670
1671//----------------------------------------------------------------------
1672// UnloadImage
1673//
1674// This function provides a default implementation that works for most
1675// unix variants. Any Process subclasses that need to do shared library
1676// loading differently should override LoadImage and UnloadImage and
1677// do what is needed.
1678//----------------------------------------------------------------------
1679Error
1680Process::UnloadImage (uint32_t image_token)
1681{
1682 Error error;
1683 if (image_token < m_image_tokens.size())
1684 {
1685 const addr_t image_addr = m_image_tokens[image_token];
1686 if (image_addr == LLDB_INVALID_ADDRESS)
1687 {
1688 error.SetErrorString("image already unloaded");
1689 }
1690 else
1691 {
1692 DynamicLoader *loader = GetDynamicLoader();
1693 if (loader)
1694 error = loader->CanLoadImage();
1695
1696 if (error.Success())
1697 {
1698 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001699
1700 if (thread_sp)
1701 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001702 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001703
1704 if (frame_sp)
1705 {
1706 ExecutionContext exe_ctx;
1707 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001708 EvaluateExpressionOptions expr_options;
1709 expr_options.SetUnwindOnError(true);
1710 expr_options.SetIgnoreBreakpoints(true);
1711 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001712 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001713 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001714 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001715 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001716 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001717 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001718 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001719 expr.GetData(),
1720 prefix,
1721 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001722 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001723 if (result_valobj_sp->GetError().Success())
1724 {
1725 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001726 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001727 {
1728 if (scalar.UInt(1))
1729 {
1730 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1731 }
1732 else
1733 {
1734 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1735 }
1736 }
1737 }
1738 else
1739 {
1740 error = result_valobj_sp->GetError();
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747 else
1748 {
1749 error.SetErrorString("invalid image token");
1750 }
1751 return error;
1752}
1753
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001754const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755Process::GetABI()
1756{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001757 if (!m_abi_sp)
1758 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1759 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001760}
1761
Jim Ingham22777012010-09-23 02:01:19 +00001762LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001763Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001764{
1765 LanguageRuntimeCollection::iterator pos;
1766 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001767 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001768 {
Jim Inghamab175242012-03-10 00:22:19 +00001769 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001770
Jim Inghamab175242012-03-10 00:22:19 +00001771 m_language_runtimes[language] = runtime_sp;
1772 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001773 }
1774 else
1775 return (*pos).second.get();
1776}
1777
1778CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001779Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001780{
Jim Inghamab175242012-03-10 00:22:19 +00001781 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001782 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1783 return static_cast<CPPLanguageRuntime *> (runtime);
1784 return NULL;
1785}
1786
1787ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001788Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001789{
Jim Inghamab175242012-03-10 00:22:19 +00001790 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001791 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1792 return static_cast<ObjCLanguageRuntime *> (runtime);
1793 return NULL;
1794}
1795
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001796bool
1797Process::IsPossibleDynamicValue (ValueObject& in_value)
1798{
1799 if (in_value.IsDynamic())
1800 return false;
1801 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1802
1803 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1804 {
1805 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1806 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1807 }
1808
1809 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1810 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1811 return true;
1812
1813 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1814 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1815}
1816
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817BreakpointSiteList &
1818Process::GetBreakpointSiteList()
1819{
1820 return m_breakpoint_site_list;
1821}
1822
1823const BreakpointSiteList &
1824Process::GetBreakpointSiteList() const
1825{
1826 return m_breakpoint_site_list;
1827}
1828
1829
1830void
1831Process::DisableAllBreakpointSites ()
1832{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001833 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1834// bp_site->SetEnabled(true);
1835 DisableBreakpointSite(bp_site);
1836 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837}
1838
1839Error
1840Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1841{
1842 Error error (DisableBreakpointSiteByID (break_id));
1843
1844 if (error.Success())
1845 m_breakpoint_site_list.Remove(break_id);
1846
1847 return error;
1848}
1849
1850Error
1851Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1852{
1853 Error error;
1854 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1855 if (bp_site_sp)
1856 {
1857 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001858 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001859 }
1860 else
1861 {
Daniel Malead01b2952012-11-29 21:49:15 +00001862 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001863 }
1864
1865 return error;
1866}
1867
1868Error
1869Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1870{
1871 Error error;
1872 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1873 if (bp_site_sp)
1874 {
1875 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001876 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001877 }
1878 else
1879 {
Daniel Malead01b2952012-11-29 21:49:15 +00001880 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001881 }
1882 return error;
1883}
1884
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001885lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001886Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001887{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001888 addr_t load_addr = LLDB_INVALID_ADDRESS;
1889
1890 bool show_error = true;
1891 switch (GetState())
1892 {
1893 case eStateInvalid:
1894 case eStateUnloaded:
1895 case eStateConnected:
1896 case eStateAttaching:
1897 case eStateLaunching:
1898 case eStateDetached:
1899 case eStateExited:
1900 show_error = false;
1901 break;
1902
1903 case eStateStopped:
1904 case eStateRunning:
1905 case eStateStepping:
1906 case eStateCrashed:
1907 case eStateSuspended:
1908 show_error = IsAlive();
1909 break;
1910 }
1911
1912 // Reset the IsIndirect flag here, in case the location changes from
1913 // pointing to a indirect symbol to a regular symbol.
1914 owner->SetIsIndirect (false);
1915
1916 if (owner->ShouldResolveIndirectFunctions())
1917 {
1918 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1919 if (symbol && symbol->IsIndirect())
1920 {
1921 Error error;
1922 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1923 if (!error.Success() && show_error)
1924 {
Greg Clayton44d93782014-01-27 23:43:24 +00001925 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1926 symbol->GetAddress().GetLoadAddress(&m_target),
1927 owner->GetBreakpoint().GetID(),
1928 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001929 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001930 return LLDB_INVALID_BREAK_ID;
1931 }
1932 Address resolved_address(load_addr);
1933 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1934 owner->SetIsIndirect(true);
1935 }
1936 else
1937 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1938 }
1939 else
1940 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1941
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001942 if (load_addr != LLDB_INVALID_ADDRESS)
1943 {
1944 BreakpointSiteSP bp_site_sp;
1945
1946 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1947 // create a new breakpoint site and add it.
1948
1949 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1950
1951 if (bp_site_sp)
1952 {
1953 bp_site_sp->AddOwner (owner);
1954 owner->SetBreakpointSite (bp_site_sp);
1955 return bp_site_sp->GetID();
1956 }
1957 else
1958 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001959 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 if (bp_site_sp)
1961 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001962 Error error = EnableBreakpointSite (bp_site_sp.get());
1963 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964 {
1965 owner->SetBreakpointSite (bp_site_sp);
1966 return m_breakpoint_site_list.Add (bp_site_sp);
1967 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001968 else
1969 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001970 if (show_error)
1971 {
1972 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001973 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1974 load_addr,
1975 owner->GetBreakpoint().GetID(),
1976 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001977 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001978 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001979 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980 }
1981 }
1982 }
1983 // We failed to enable the breakpoint
1984 return LLDB_INVALID_BREAK_ID;
1985
1986}
1987
1988void
1989Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1990{
1991 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1992 if (num_owners == 0)
1993 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001994 // Don't try to disable the site if we don't have a live process anymore.
1995 if (IsAlive())
1996 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1998 }
1999}
2000
2001
2002size_t
2003Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2004{
2005 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002006 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007
Jim Ingham20c77192011-06-29 19:42:28 +00002008 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002010 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2011 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002013 addr_t intersect_addr;
2014 size_t intersect_size;
2015 size_t opcode_offset;
2016 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002017 {
2018 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2019 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002020 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002021 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002022 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002023 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002025 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002026 }
2027 return bytes_removed;
2028}
2029
2030
Greg Claytonded470d2011-03-19 01:12:21 +00002031
2032size_t
2033Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2034{
2035 PlatformSP platform_sp (m_target.GetPlatform());
2036 if (platform_sp)
2037 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2038 return 0;
2039}
2040
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002041Error
2042Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2043{
2044 Error error;
2045 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002046 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002047 const addr_t bp_addr = bp_site->GetLoadAddress();
2048 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002049 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002050 if (bp_site->IsEnabled())
2051 {
2052 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002053 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 +00002054 return error;
2055 }
2056
2057 if (bp_addr == LLDB_INVALID_ADDRESS)
2058 {
2059 error.SetErrorString("BreakpointSite contains an invalid load address.");
2060 return error;
2061 }
2062 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2063 // trap for the breakpoint site
2064 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2065
2066 if (bp_opcode_size == 0)
2067 {
Daniel Malead01b2952012-11-29 21:49:15 +00002068 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002069 }
2070 else
2071 {
2072 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2073
2074 if (bp_opcode_bytes == NULL)
2075 {
2076 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2077 return error;
2078 }
2079
2080 // Save the original opcode by reading it
2081 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2082 {
2083 // Write a software breakpoint in place of the original opcode
2084 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2085 {
2086 uint8_t verify_bp_opcode_bytes[64];
2087 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2088 {
2089 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2090 {
2091 bp_site->SetEnabled(true);
2092 bp_site->SetType (BreakpointSite::eSoftware);
2093 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002094 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095 bp_site->GetID(),
2096 (uint64_t)bp_addr);
2097 }
2098 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002099 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100 }
2101 else
2102 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2103 }
2104 else
2105 error.SetErrorString("Unable to write breakpoint trap to memory.");
2106 }
2107 else
2108 error.SetErrorString("Unable to read memory at breakpoint address.");
2109 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002110 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002111 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112 bp_site->GetID(),
2113 (uint64_t)bp_addr,
2114 error.AsCString());
2115 return error;
2116}
2117
2118Error
2119Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2120{
2121 Error error;
2122 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002123 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124 addr_t bp_addr = bp_site->GetLoadAddress();
2125 lldb::user_id_t breakID = bp_site->GetID();
2126 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002127 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128
2129 if (bp_site->IsHardware())
2130 {
2131 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2132 }
2133 else if (bp_site->IsEnabled())
2134 {
2135 const size_t break_op_size = bp_site->GetByteSize();
2136 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2137 if (break_op_size > 0)
2138 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002139 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002140 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002141 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 bool break_op_found = false;
2143
2144 // Read the breakpoint opcode
2145 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2146 {
2147 bool verify = false;
2148 // Make sure we have the a breakpoint opcode exists at this address
2149 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2150 {
2151 break_op_found = true;
2152 // We found a valid breakpoint opcode at this address, now restore
2153 // the saved opcode.
2154 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2155 {
2156 verify = true;
2157 }
2158 else
2159 error.SetErrorString("Memory write failed when restoring original opcode.");
2160 }
2161 else
2162 {
2163 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2164 // Set verify to true and so we can check if the original opcode has already been restored
2165 verify = true;
2166 }
2167
2168 if (verify)
2169 {
Greg Claytonc982c762010-07-09 20:39:50 +00002170 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002171 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002172 // Verify that our original opcode made it back to the inferior
2173 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2174 {
2175 // compare the memory we just read with the original opcode
2176 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2177 {
2178 // SUCCESS
2179 bp_site->SetEnabled(false);
2180 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002181 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 +00002182 return error;
2183 }
2184 else
2185 {
2186 if (break_op_found)
2187 error.SetErrorString("Failed to restore original opcode.");
2188 }
2189 }
2190 else
2191 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2192 }
2193 }
2194 else
2195 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2196 }
2197 }
2198 else
2199 {
2200 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002201 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 +00002202 return error;
2203 }
2204
2205 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002206 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207 bp_site->GetID(),
2208 (uint64_t)bp_addr,
2209 error.AsCString());
2210 return error;
2211
2212}
2213
Greg Clayton58be07b2011-01-07 06:08:19 +00002214// Uncomment to verify memory caching works after making changes to caching code
2215//#define VERIFY_MEMORY_READS
2216
Sean Callanan64c0cf22012-06-07 22:26:42 +00002217size_t
2218Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2219{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002220 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002221 if (!GetDisableMemoryCache())
2222 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002223#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002224 // Memory caching is enabled, with debug verification
2225
2226 if (buf && size)
2227 {
2228 // Uncomment the line below to make sure memory caching is working.
2229 // I ran this through the test suite and got no assertions, so I am
2230 // pretty confident this is working well. If any changes are made to
2231 // memory caching, uncomment the line below and test your changes!
2232
2233 // Verify all memory reads by using the cache first, then redundantly
2234 // reading the same memory from the inferior and comparing to make sure
2235 // everything is exactly the same.
2236 std::string verify_buf (size, '\0');
2237 assert (verify_buf.size() == size);
2238 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2239 Error verify_error;
2240 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2241 assert (cache_bytes_read == verify_bytes_read);
2242 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2243 assert (verify_error.Success() == error.Success());
2244 return cache_bytes_read;
2245 }
2246 return 0;
2247#else // !defined(VERIFY_MEMORY_READS)
2248 // Memory caching is enabled, without debug verification
2249
2250 return m_memory_cache.Read (addr, buf, size, error);
2251#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002252 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002253 else
2254 {
2255 // Memory caching is disabled
2256
2257 return ReadMemoryFromInferior (addr, buf, size, error);
2258 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002259}
Greg Clayton58be07b2011-01-07 06:08:19 +00002260
Greg Clayton4c82d422012-05-18 23:20:01 +00002261size_t
2262Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2263{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002264 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002265 out_str.clear();
2266 addr_t curr_addr = addr;
2267 while (1)
2268 {
2269 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2270 if (length == 0)
2271 break;
2272 out_str.append(buf, length);
2273 // If we got "length - 1" bytes, we didn't get the whole C string, we
2274 // need to read some more characters
2275 if (length == sizeof(buf) - 1)
2276 curr_addr += length;
2277 else
2278 break;
2279 }
2280 return out_str.size();
2281}
2282
Greg Clayton58be07b2011-01-07 06:08:19 +00002283
2284size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002285Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2286 size_t type_width)
2287{
2288 size_t total_bytes_read = 0;
2289 if (dst && max_bytes && type_width && max_bytes >= type_width)
2290 {
2291 // Ensure a null terminator independent of the number of bytes that is read.
2292 memset (dst, 0, max_bytes);
2293 size_t bytes_left = max_bytes - type_width;
2294
2295 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2296 assert(sizeof(terminator) >= type_width &&
2297 "Attempting to validate a string with more than 4 bytes per character!");
2298
2299 addr_t curr_addr = addr;
2300 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2301 char *curr_dst = dst;
2302
2303 error.Clear();
2304 while (bytes_left > 0 && error.Success())
2305 {
2306 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2307 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2308 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2309
2310 if (bytes_read == 0)
2311 break;
2312
2313 // Search for a null terminator of correct size and alignment in bytes_read
2314 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2315 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2316 if (::strncmp(&dst[i], terminator, type_width) == 0)
2317 {
2318 error.Clear();
2319 return i;
2320 }
2321
2322 total_bytes_read += bytes_read;
2323 curr_dst += bytes_read;
2324 curr_addr += bytes_read;
2325 bytes_left -= bytes_read;
2326 }
2327 }
2328 else
2329 {
2330 if (max_bytes)
2331 error.SetErrorString("invalid arguments");
2332 }
2333 return total_bytes_read;
2334}
2335
2336// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2337// null terminators.
2338size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002339Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002340{
2341 size_t total_cstr_len = 0;
2342 if (dst && dst_max_len)
2343 {
Greg Claytone91b7952011-12-15 03:14:23 +00002344 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002345 // NULL out everything just to be safe
2346 memset (dst, 0, dst_max_len);
2347 Error error;
2348 addr_t curr_addr = addr;
2349 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2350 size_t bytes_left = dst_max_len - 1;
2351 char *curr_dst = dst;
2352
2353 while (bytes_left > 0)
2354 {
2355 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2356 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2357 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2358
2359 if (bytes_read == 0)
2360 {
Greg Claytone91b7952011-12-15 03:14:23 +00002361 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002362 dst[total_cstr_len] = '\0';
2363 break;
2364 }
2365 const size_t len = strlen(curr_dst);
2366
2367 total_cstr_len += len;
2368
2369 if (len < bytes_to_read)
2370 break;
2371
2372 curr_dst += bytes_read;
2373 curr_addr += bytes_read;
2374 bytes_left -= bytes_read;
2375 }
2376 }
Greg Claytone91b7952011-12-15 03:14:23 +00002377 else
2378 {
2379 if (dst == NULL)
2380 result_error.SetErrorString("invalid arguments");
2381 else
2382 result_error.Clear();
2383 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002384 return total_cstr_len;
2385}
2386
2387size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002388Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2389{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002390 if (buf == NULL || size == 0)
2391 return 0;
2392
2393 size_t bytes_read = 0;
2394 uint8_t *bytes = (uint8_t *)buf;
2395
2396 while (bytes_read < size)
2397 {
2398 const size_t curr_size = size - bytes_read;
2399 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2400 bytes + bytes_read,
2401 curr_size,
2402 error);
2403 bytes_read += curr_bytes_read;
2404 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2405 break;
2406 }
2407
2408 // Replace any software breakpoint opcodes that fall into this range back
2409 // into "buf" before we return
2410 if (bytes_read > 0)
2411 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2412 return bytes_read;
2413}
2414
Greg Clayton58a4c462010-12-16 20:01:20 +00002415uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002416Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002417{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002418 Scalar scalar;
2419 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2420 return scalar.ULongLong(fail_value);
2421 return fail_value;
2422}
2423
2424addr_t
2425Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2426{
2427 Scalar scalar;
2428 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2429 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2430 return LLDB_INVALID_ADDRESS;
2431}
2432
2433
2434bool
2435Process::WritePointerToMemory (lldb::addr_t vm_addr,
2436 lldb::addr_t ptr_value,
2437 Error &error)
2438{
2439 Scalar scalar;
2440 const uint32_t addr_byte_size = GetAddressByteSize();
2441 if (addr_byte_size <= 4)
2442 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002443 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002444 scalar = ptr_value;
2445 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002446}
2447
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448size_t
2449Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2450{
2451 size_t bytes_written = 0;
2452 const uint8_t *bytes = (const uint8_t *)buf;
2453
2454 while (bytes_written < size)
2455 {
2456 const size_t curr_size = size - bytes_written;
2457 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2458 bytes + bytes_written,
2459 curr_size,
2460 error);
2461 bytes_written += curr_bytes_written;
2462 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2463 break;
2464 }
2465 return bytes_written;
2466}
2467
2468size_t
2469Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2470{
Greg Clayton58be07b2011-01-07 06:08:19 +00002471#if defined (ENABLE_MEMORY_CACHING)
2472 m_memory_cache.Flush (addr, size);
2473#endif
2474
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475 if (buf == NULL || size == 0)
2476 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002477
Jim Ingham4b536182011-08-09 02:12:22 +00002478 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002479
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480 // We need to write any data that would go where any current software traps
2481 // (enabled software breakpoints) any software traps (breakpoints) that we
2482 // may have placed in our tasks memory.
2483
Greg Claytond8cf1a12013-06-12 00:46:38 +00002484 BreakpointSiteList bp_sites_in_range;
2485
2486 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002487 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002488 // No breakpoint sites overlap
2489 if (bp_sites_in_range.IsEmpty())
2490 return WriteMemoryPrivate (addr, buf, size, error);
2491 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002493 const uint8_t *ubuf = (const uint8_t *)buf;
2494 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002495
Greg Claytond8cf1a12013-06-12 00:46:38 +00002496 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2497
2498 if (error.Success())
2499 {
2500 addr_t intersect_addr;
2501 size_t intersect_size;
2502 size_t opcode_offset;
2503 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2504 assert(intersects);
2505 assert(addr <= intersect_addr && intersect_addr < addr + size);
2506 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2507 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2508
2509 // Check for bytes before this breakpoint
2510 const addr_t curr_addr = addr + bytes_written;
2511 if (intersect_addr > curr_addr)
2512 {
2513 // There are some bytes before this breakpoint that we need to
2514 // just write to memory
2515 size_t curr_size = intersect_addr - curr_addr;
2516 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2517 ubuf + bytes_written,
2518 curr_size,
2519 error);
2520 bytes_written += curr_bytes_written;
2521 if (curr_bytes_written != curr_size)
2522 {
2523 // We weren't able to write all of the requested bytes, we
2524 // are done looping and will return the number of bytes that
2525 // we have written so far.
2526 if (error.Success())
2527 error.SetErrorToGenericError();
2528 }
2529 }
2530 // Now write any bytes that would cover up any software breakpoints
2531 // directly into the breakpoint opcode buffer
2532 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2533 bytes_written += intersect_size;
2534 }
2535 });
2536
2537 if (bytes_written < size)
2538 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2539 ubuf + bytes_written,
2540 size - bytes_written,
2541 error);
2542 }
2543 }
2544 else
2545 {
2546 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547 }
2548
2549 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002550 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002551}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002552
2553size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002554Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002555{
2556 if (byte_size == UINT32_MAX)
2557 byte_size = scalar.GetByteSize();
2558 if (byte_size > 0)
2559 {
2560 uint8_t buf[32];
2561 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2562 if (mem_size > 0)
2563 return WriteMemory(addr, buf, mem_size, error);
2564 else
2565 error.SetErrorString ("failed to get scalar as memory data");
2566 }
2567 else
2568 {
2569 error.SetErrorString ("invalid scalar value");
2570 }
2571 return 0;
2572}
2573
2574size_t
2575Process::ReadScalarIntegerFromMemory (addr_t addr,
2576 uint32_t byte_size,
2577 bool is_signed,
2578 Scalar &scalar,
2579 Error &error)
2580{
Greg Clayton7060f892013-05-01 23:41:30 +00002581 uint64_t uval = 0;
2582 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002583 {
Greg Clayton7060f892013-05-01 23:41:30 +00002584 error.SetErrorString ("byte size is zero");
2585 }
2586 else if (byte_size & (byte_size - 1))
2587 {
2588 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2589 }
2590 else if (byte_size <= sizeof(uval))
2591 {
2592 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002593 if (bytes_read == byte_size)
2594 {
2595 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002596 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002597 if (byte_size <= 4)
2598 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002599 else
Greg Clayton7060f892013-05-01 23:41:30 +00002600 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002601 if (is_signed)
2602 scalar.SignExtend(byte_size * 8);
2603 return bytes_read;
2604 }
2605 }
2606 else
2607 {
2608 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2609 }
2610 return 0;
2611}
2612
Greg Claytond495c532011-05-17 03:37:42 +00002613#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614addr_t
2615Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2616{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002617 if (GetPrivateState() != eStateStopped)
2618 return LLDB_INVALID_ADDRESS;
2619
Greg Claytond495c532011-05-17 03:37:42 +00002620#if defined (USE_ALLOCATE_MEMORY_CACHE)
2621 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2622#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002623 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002624 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002625 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002626 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 +00002627 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002628 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002629 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002630 m_mod_id.GetStopID(),
2631 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002632 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002633#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634}
2635
Sean Callanan90539452011-09-20 23:01:51 +00002636bool
2637Process::CanJIT ()
2638{
Sean Callanana7b443a2012-02-14 22:50:38 +00002639 if (m_can_jit == eCanJITDontKnow)
2640 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002641 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002642 Error err;
2643
2644 uint64_t allocated_memory = AllocateMemory(8,
2645 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2646 err);
2647
2648 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002649 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002650 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002651 if (log)
2652 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2653 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002654 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002655 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002656 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002657 if (log)
2658 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2659 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002660
2661 DeallocateMemory (allocated_memory);
2662 }
2663
Sean Callanan90539452011-09-20 23:01:51 +00002664 return m_can_jit == eCanJITYes;
2665}
2666
2667void
2668Process::SetCanJIT (bool can_jit)
2669{
2670 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2671}
2672
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673Error
2674Process::DeallocateMemory (addr_t ptr)
2675{
Greg Claytond495c532011-05-17 03:37:42 +00002676 Error error;
2677#if defined (USE_ALLOCATE_MEMORY_CACHE)
2678 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2679 {
Daniel Malead01b2952012-11-29 21:49:15 +00002680 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002681 }
2682#else
2683 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002684
Greg Clayton5160ce52013-03-27 23:08:40 +00002685 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002686 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002687 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 +00002688 ptr,
2689 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002690 m_mod_id.GetStopID(),
2691 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002692#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002693 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694}
2695
Han Ming Ongc811d382012-11-17 00:33:14 +00002696
Greg Claytonc9660542012-02-05 02:38:54 +00002697ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002698Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002699 lldb::addr_t header_addr,
2700 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002701{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002702 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002703 if (module_sp)
2704 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002705 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002706 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002707 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002708 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002709 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002710 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002711}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712
2713Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002714Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002715{
2716 Error error;
2717 error.SetErrorString("watchpoints are not supported");
2718 return error;
2719}
2720
2721Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002722Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002723{
2724 Error error;
2725 error.SetErrorString("watchpoints are not supported");
2726 return error;
2727}
2728
2729StateType
2730Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2731{
2732 StateType state;
2733 // Now wait for the process to launch and return control to us, and then
2734 // call DidLaunch:
2735 while (1)
2736 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002737 event_sp.reset();
2738 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2739
Greg Clayton2637f822011-11-17 01:23:07 +00002740 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002742
2743 // If state is invalid, then we timed out
2744 if (state == eStateInvalid)
2745 break;
2746
2747 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748 HandlePrivateEvent (event_sp);
2749 }
2750 return state;
2751}
2752
2753Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002754Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002755{
2756 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002758 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002759 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002760 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002761 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002762 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002763
Greg Claytonaa149cb2011-08-11 02:48:45 +00002764 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765 if (exe_module)
2766 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002767 char local_exec_file_path[PATH_MAX];
2768 char platform_exec_file_path[PATH_MAX];
2769 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2770 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002771 if (exe_module->GetFileSpec().Exists())
2772 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002773 // Install anything that might need to be installed prior to launching.
2774 // For host systems, this will do nothing, but if we are connected to a
2775 // remote platform it will install any needed binaries
2776 error = GetTarget().Install(&launch_info);
2777 if (error.Fail())
2778 return error;
2779
Greg Clayton71337622011-02-24 22:24:29 +00002780 if (PrivateStateThreadIsValid ())
2781 PausePrivateStateThread ();
2782
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002783 error = WillLaunch (exe_module);
2784 if (error.Success())
2785 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002786 const bool restarted = false;
2787 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002788 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789
Ed Maste64fad602013-07-29 20:58:06 +00002790 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002791 {
2792 // Now launch using these arguments.
2793 error = DoLaunch (exe_module, launch_info);
2794 }
2795 else
2796 {
2797 // This shouldn't happen
2798 error.SetErrorString("failed to acquire process run lock");
2799 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800
2801 if (error.Fail())
2802 {
2803 if (GetID() != LLDB_INVALID_PROCESS_ID)
2804 {
2805 SetID (LLDB_INVALID_PROCESS_ID);
2806 const char *error_string = error.AsCString();
2807 if (error_string == NULL)
2808 error_string = "launch failed";
2809 SetExitStatus (-1, error_string);
2810 }
2811 }
2812 else
2813 {
2814 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002815 TimeValue timeout_time;
2816 timeout_time = TimeValue::Now();
2817 timeout_time.OffsetWithSeconds(10);
2818 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819
Greg Clayton1a38ea72011-06-22 01:42:17 +00002820 if (state == eStateInvalid || event_sp.get() == NULL)
2821 {
2822 // We were able to launch the process, but we failed to
2823 // catch the initial stop.
2824 SetExitStatus (0, "failed to catch stop after launch");
2825 Destroy();
2826 }
2827 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002829
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002830 DidLaunch ();
2831
Greg Claytonc859e2d2012-02-13 23:10:39 +00002832 DynamicLoader *dyld = GetDynamicLoader ();
2833 if (dyld)
2834 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002835
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002836 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002837
Jason Molendaeef51062013-11-05 03:57:19 +00002838 SystemRuntime *system_runtime = GetSystemRuntime ();
2839 if (system_runtime)
2840 system_runtime->DidLaunch();
2841
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002842 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Todd Fialaf72fa672014-10-07 16:05:21 +00002843
2844 // Note, the stop event was consumed above, but not handled. This was done
2845 // to give DidLaunch a chance to run. The target is either stopped or crashed.
2846 // Directly set the state. This is done to prevent a stop message with a bunch
2847 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
2848 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00002849
2850 if (PrivateStateThreadIsValid ())
2851 ResumePrivateStateThread ();
2852 else
2853 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002854 }
2855 else if (state == eStateExited)
2856 {
2857 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2858 // not likely to work, and return an invalid pid.
2859 HandlePrivateEvent (event_sp);
2860 }
2861 }
2862 }
2863 }
2864 else
2865 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002866 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002867 }
2868 }
2869 return error;
2870}
2871
Greg Claytonc3776bf2012-02-09 06:16:32 +00002872
2873Error
2874Process::LoadCore ()
2875{
2876 Error error = DoLoadCore();
2877 if (error.Success())
2878 {
2879 if (PrivateStateThreadIsValid ())
2880 ResumePrivateStateThread ();
2881 else
2882 StartPrivateStateThread ();
2883
Greg Claytonc859e2d2012-02-13 23:10:39 +00002884 DynamicLoader *dyld = GetDynamicLoader ();
2885 if (dyld)
2886 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002887
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002888 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002889
Jason Molendaeef51062013-11-05 03:57:19 +00002890 SystemRuntime *system_runtime = GetSystemRuntime ();
2891 if (system_runtime)
2892 system_runtime->DidAttach();
2893
Greg Claytonc859e2d2012-02-13 23:10:39 +00002894 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002895 // We successfully loaded a core file, now pretend we stopped so we can
2896 // show all of the threads in the core file and explore the crashed
2897 // state.
2898 SetPrivateState (eStateStopped);
2899
2900 }
2901 return error;
2902}
2903
Greg Claytonc859e2d2012-02-13 23:10:39 +00002904DynamicLoader *
2905Process::GetDynamicLoader ()
2906{
2907 if (m_dyld_ap.get() == NULL)
2908 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2909 return m_dyld_ap.get();
2910}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002911
Todd Fialaaf245d12014-06-30 21:05:18 +00002912const lldb::DataBufferSP
2913Process::GetAuxvData()
2914{
2915 return DataBufferSP ();
2916}
2917
Andrew MacPherson17220c12014-03-05 10:12:43 +00002918JITLoaderList &
2919Process::GetJITLoaders ()
2920{
2921 if (!m_jit_loaders_ap)
2922 {
2923 m_jit_loaders_ap.reset(new JITLoaderList());
2924 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2925 }
2926 return *m_jit_loaders_ap;
2927}
2928
Jason Molendaeef51062013-11-05 03:57:19 +00002929SystemRuntime *
2930Process::GetSystemRuntime ()
2931{
2932 if (m_system_runtime_ap.get() == NULL)
2933 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2934 return m_system_runtime_ap.get();
2935}
2936
Todd Fiala76e0fc92014-08-27 22:58:26 +00002937Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
2938 NextEventAction (process),
2939 m_exec_count (exec_count)
2940{
2941 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2942 if (log)
2943 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
2944}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002945
Jim Inghambb3a2832011-01-29 01:49:25 +00002946Process::NextEventAction::EventActionResult
2947Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948{
Todd Fiala76e0fc92014-08-27 22:58:26 +00002949 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2950
Jim Inghambb3a2832011-01-29 01:49:25 +00002951 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00002952 if (log)
2953 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
2954
2955 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002956 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002957 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002958 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002959 return eEventActionRetry;
2960
2961 case eStateStopped:
2962 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002963 {
2964 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002965 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002966 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002967 // We don't want these events to be reported, so go set the ShouldReportStop here:
2968 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2969
Greg Claytonc9ed4782011-11-12 02:10:56 +00002970 if (m_exec_count > 0)
2971 {
2972 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00002973
2974 if (log)
2975 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
2976
Jim Ingham221d51c2013-05-08 00:35:16 +00002977 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002978 return eEventActionRetry;
2979 }
2980 else
2981 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00002982 if (log)
2983 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
2984
Greg Claytonc9ed4782011-11-12 02:10:56 +00002985 m_process->CompleteAttach ();
2986 return eEventActionSuccess;
2987 }
2988 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002989 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002990
Greg Clayton513c26c2011-01-29 07:10:55 +00002991 default:
2992 case eStateExited:
2993 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002994 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002995 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002996
2997 m_exit_string.assign ("No valid Process");
2998 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002999}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003000
Jim Inghambb3a2832011-01-29 01:49:25 +00003001Process::NextEventAction::EventActionResult
3002Process::AttachCompletionHandler::HandleBeingInterrupted()
3003{
3004 return eEventActionSuccess;
3005}
3006
3007const char *
3008Process::AttachCompletionHandler::GetExitString ()
3009{
3010 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003011}
3012
3013Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003014Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003017 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003018 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003019 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003020 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003021 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003022
Greg Clayton144f3a92011-11-15 03:53:30 +00003023 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003024 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003025 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003026 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003027 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003028
Greg Clayton144f3a92011-11-15 03:53:30 +00003029 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003030 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003031 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3032
3033 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003035 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3036 if (error.Success())
3037 {
Ed Maste64fad602013-07-29 20:58:06 +00003038 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003039 {
3040 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003041 const bool restarted = false;
3042 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003043 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003044 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003045 }
3046 else
3047 {
3048 // This shouldn't happen
3049 error.SetErrorString("failed to acquire process run lock");
3050 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003051
Greg Clayton144f3a92011-11-15 03:53:30 +00003052 if (error.Fail())
3053 {
3054 if (GetID() != LLDB_INVALID_PROCESS_ID)
3055 {
3056 SetID (LLDB_INVALID_PROCESS_ID);
3057 if (error.AsCString() == NULL)
3058 error.SetErrorString("attach failed");
3059
3060 SetExitStatus(-1, error.AsCString());
3061 }
3062 }
3063 else
3064 {
3065 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3066 StartPrivateStateThread();
3067 }
3068 return error;
3069 }
Greg Claytone996fd32011-03-08 22:40:15 +00003070 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003071 else
Greg Claytone996fd32011-03-08 22:40:15 +00003072 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003073 ProcessInstanceInfoList process_infos;
3074 PlatformSP platform_sp (m_target.GetPlatform ());
3075
3076 if (platform_sp)
3077 {
3078 ProcessInstanceInfoMatch match_info;
3079 match_info.GetProcessInfo() = attach_info;
3080 match_info.SetNameMatchType (eNameMatchEquals);
3081 platform_sp->FindProcesses (match_info, process_infos);
3082 const uint32_t num_matches = process_infos.GetSize();
3083 if (num_matches == 1)
3084 {
3085 attach_pid = process_infos.GetProcessIDAtIndex(0);
3086 // Fall through and attach using the above process ID
3087 }
3088 else
3089 {
3090 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3091 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003092 {
3093 StreamString s;
3094 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3095 for (size_t i = 0; i < num_matches; i++)
3096 {
3097 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3098 }
3099 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3100 process_name,
3101 s.GetData());
3102 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003103 else
3104 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3105 }
3106 }
3107 else
3108 {
3109 error.SetErrorString ("invalid platform, can't find processes by name");
3110 return error;
3111 }
Greg Claytone996fd32011-03-08 22:40:15 +00003112 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003113 }
3114 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003115 {
3116 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003117 }
3118 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003119
3120 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003121 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003122 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003123 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003124 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003125
Ed Maste64fad602013-07-29 20:58:06 +00003126 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003127 {
3128 // Now attach using these arguments.
3129 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003130 const bool restarted = false;
3131 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003132 error = DoAttachToProcessWithID (attach_pid, attach_info);
3133 }
3134 else
3135 {
3136 // This shouldn't happen
3137 error.SetErrorString("failed to acquire process run lock");
3138 }
3139
Greg Clayton144f3a92011-11-15 03:53:30 +00003140 if (error.Success())
3141 {
3142
3143 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3144 StartPrivateStateThread();
3145 }
3146 else
Greg Claytone996fd32011-03-08 22:40:15 +00003147 {
3148 if (GetID() != LLDB_INVALID_PROCESS_ID)
3149 {
3150 SetID (LLDB_INVALID_PROCESS_ID);
3151 const char *error_string = error.AsCString();
3152 if (error_string == NULL)
3153 error_string = "attach failed";
3154
3155 SetExitStatus(-1, error_string);
3156 }
3157 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158 }
3159 }
3160 return error;
3161}
3162
Greg Clayton93d3c8332011-02-16 04:46:07 +00003163void
3164Process::CompleteAttach ()
3165{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003166 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3167 if (log)
3168 log->Printf ("Process::%s()", __FUNCTION__);
3169
Greg Clayton93d3c8332011-02-16 04:46:07 +00003170 // Let the process subclass figure out at much as it can about the process
3171 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003172 ArchSpec process_arch;
3173 DidAttach(process_arch);
3174
3175 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003176 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003177 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003178 if (log)
3179 {
3180 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3181 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3182 __FUNCTION__,
3183 triple_str ? triple_str : "<null>");
3184 }
3185 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003186
Jim Ingham4299fdb2011-09-15 01:10:17 +00003187 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3188 // the same as the one we've already set, switch architectures.
3189 PlatformSP platform_sp (m_target.GetPlatform ());
3190 assert (platform_sp.get());
3191 if (platform_sp)
3192 {
Greg Clayton70512312012-05-08 01:45:38 +00003193 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003194 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003195 {
3196 ArchSpec platform_arch;
3197 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3198 if (platform_sp)
3199 {
3200 m_target.SetPlatform (platform_sp);
3201 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003202 if (log)
3203 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 +00003204 }
3205 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003206 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003207 {
3208 ProcessInstanceInfo process_info;
3209 platform_sp->GetProcessInfo (GetID(), process_info);
3210 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003211 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003212 {
Greg Clayton70512312012-05-08 01:45:38 +00003213 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003214 if (log)
3215 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 ());
3216 }
Greg Clayton70512312012-05-08 01:45:38 +00003217 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003218 }
3219
3220 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003221 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003222 DynamicLoader *dyld = GetDynamicLoader ();
3223 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003224 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003225 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003226 if (log)
3227 {
3228 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3229 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3230 __FUNCTION__,
3231 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3232 dyld->GetPluginName().AsCString ("<unnamed>"));
3233 }
3234 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003235
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003236 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003237
Jason Molendaeef51062013-11-05 03:57:19 +00003238 SystemRuntime *system_runtime = GetSystemRuntime ();
3239 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003240 {
Jason Molendaeef51062013-11-05 03:57:19 +00003241 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003242 if (log)
3243 {
3244 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3245 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3246 __FUNCTION__,
3247 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3248 system_runtime->GetPluginName().AsCString("<unnamed>"));
3249 }
3250 }
Jason Molendaeef51062013-11-05 03:57:19 +00003251
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003252 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003253 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003254 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003255 Mutex::Locker modules_locker(target_modules.GetMutex());
3256 size_t num_modules = target_modules.GetSize();
3257 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003258
Andy Gibbsa297a972013-06-19 19:04:53 +00003259 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003260 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003261 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003262 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003263 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003264 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003265 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003266 break;
3267 }
3268 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003269 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003270 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003271 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003272 if (log)
3273 {
3274 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3275 log->Printf ("Process::%s after looping through modules, target executable is %s",
3276 __FUNCTION__,
3277 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3278 }
3279 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003280}
3281
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003282Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003283Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003284{
Greg Claytonb766a732011-02-04 01:58:07 +00003285 m_abi_sp.reset();
3286 m_process_input_reader.reset();
3287
3288 // Find the process and its architecture. Make sure it matches the architecture
3289 // of the current Target, and if not adjust it.
3290
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003291 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003292 if (error.Success())
3293 {
Greg Clayton71337622011-02-24 22:24:29 +00003294 if (GetID() != LLDB_INVALID_PROCESS_ID)
3295 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003296 EventSP event_sp;
3297 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3298
3299 if (state == eStateStopped || state == eStateCrashed)
3300 {
3301 // If we attached and actually have a process on the other end, then
3302 // this ended up being the equivalent of an attach.
3303 CompleteAttach ();
3304
3305 // This delays passing the stopped event to listeners till
3306 // CompleteAttach gets a chance to complete...
3307 HandlePrivateEvent (event_sp);
3308
3309 }
Greg Clayton71337622011-02-24 22:24:29 +00003310 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003311
3312 if (PrivateStateThreadIsValid ())
3313 ResumePrivateStateThread ();
3314 else
3315 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003316 }
3317 return error;
3318}
3319
3320
3321Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003322Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003323{
Greg Clayton5160ce52013-03-27 23:08:40 +00003324 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003326 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003327 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003328 StateAsCString(m_public_state.GetValue()),
3329 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330
3331 Error error (WillResume());
3332 // Tell the process it is about to resume before the thread list
3333 if (error.Success())
3334 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003335 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336 // can let all of our threads know that they are about to be
3337 // resumed. Threads will each be called with
3338 // Thread::WillResume(StateType) where StateType contains the state
3339 // that they are supposed to have when the process is resumed
3340 // (suspended/running/stepping). Threads should also check
3341 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003342 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003343 if (m_thread_list.WillResume())
3344 {
Jim Ingham372787f2012-04-07 00:00:41 +00003345 // Last thing, do the PreResumeActions.
3346 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347 {
Jim Ingham0161b492013-02-09 01:29:05 +00003348 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003349 }
3350 else
3351 {
3352 m_mod_id.BumpResumeID();
3353 error = DoResume();
3354 if (error.Success())
3355 {
3356 DidResume();
3357 m_thread_list.DidResume();
3358 if (log)
3359 log->Printf ("Process thinks the process has resumed.");
3360 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361 }
3362 }
3363 else
3364 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003365 // Somebody wanted to run without running. So generate a continue & a stopped event,
3366 // and let the world handle them.
3367 if (log)
3368 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3369
3370 SetPrivateState(eStateRunning);
3371 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003372 }
3373 }
Jim Ingham444586b2011-01-24 06:34:17 +00003374 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003375 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376 return error;
3377}
3378
3379Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003380Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003381{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003382 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3383 // in case it was already set and some thread plan logic calls halt on its
3384 // own.
3385 m_clear_thread_plans_on_stop |= clear_thread_plans;
3386
Jim Inghamaacc3182012-06-06 00:29:30 +00003387 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3388 // we could just straightaway get another event. It just narrows the window...
3389 m_currently_handling_event.WaitForValueEqualTo(false);
3390
3391
Jim Inghambb3a2832011-01-29 01:49:25 +00003392 // Pause our private state thread so we can ensure no one else eats
3393 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003394 Listener halt_listener ("lldb.process.halt_listener");
3395 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003396
Jim Inghambb3a2832011-01-29 01:49:25 +00003397 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003398 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003399
Greg Clayton06357c92014-07-30 17:38:47 +00003400 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003401 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003402 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003403
Greg Clayton513c26c2011-01-29 07:10:55 +00003404 bool caused_stop = false;
3405
3406 // Ask the process subclass to actually halt our process
3407 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003408 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003409 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003410 if (m_public_state.GetValue() == eStateAttaching)
3411 {
Greg Clayton06357c92014-07-30 17:38:47 +00003412 // Don't hijack and eat the eStateExited as the code that was doing
3413 // the attach will be waiting for this event...
3414 RestorePrivateProcessEvents();
3415 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003416 SetExitStatus(SIGKILL, "Cancelled async attach.");
3417 Destroy ();
3418 }
3419 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003420 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003421 // If "caused_stop" is true, then DoHalt stopped the process. If
3422 // "caused_stop" is false, the process was already stopped.
3423 // If the DoHalt caused the process to stop, then we want to catch
3424 // this event and set the interrupted bool to true before we pass
3425 // this along so clients know that the process was interrupted by
3426 // a halt command.
3427 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003428 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003429 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003430 TimeValue timeout_time;
3431 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003432 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003433 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3434 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003435
Jim Ingham0f16e732011-02-08 05:20:59 +00003436 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003437 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003438 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003439 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003440 }
3441 else
3442 {
Greg Clayton2637f822011-11-17 01:23:07 +00003443 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003444 {
3445 // We caused the process to interrupt itself, so mark this
3446 // as such in the stop event so clients can tell an interrupted
3447 // process from a natural stop
3448 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3449 }
3450 else
3451 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003452 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003453 if (log)
3454 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3455 error.SetErrorString ("Did not get stopped event after halt.");
3456 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003457 }
3458 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003459 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003460 }
3461 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003462 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003463 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003464 if (!restored_process_events)
3465 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003466
3467 // Post any event we might have consumed. If all goes well, we will have
3468 // stopped the process, intercepted the event and set the interrupted
3469 // bool in the event. Post it to the private event queue and that will end up
3470 // correctly setting the state.
3471 if (event_sp)
3472 m_private_state_broadcaster.BroadcastEvent(event_sp);
3473
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003474 return error;
3475}
3476
3477Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003478Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3479{
3480 Error error;
3481 if (m_public_state.GetValue() == eStateRunning)
3482 {
3483 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3484 if (log)
3485 log->Printf("Process::Destroy() About to halt.");
3486 error = Halt();
3487 if (error.Success())
3488 {
3489 // Consume the halt event.
3490 TimeValue timeout (TimeValue::Now());
3491 timeout.OffsetWithSeconds(1);
3492 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3493
3494 // If the process exited while we were waiting for it to stop, put the exited event into
3495 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3496 // they don't have a process anymore...
3497
3498 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3499 {
3500 if (log)
3501 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3502 return error;
3503 }
3504 else
3505 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3506
3507 if (state != eStateStopped)
3508 {
3509 if (log)
3510 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3511 // If we really couldn't stop the process then we should just error out here, but if the
3512 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3513 StateType private_state = m_private_state.GetValue();
3514 if (private_state != eStateStopped)
3515 {
3516 return error;
3517 }
3518 }
3519 }
3520 else
3521 {
3522 if (log)
3523 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3524 }
3525 }
3526 return error;
3527}
3528
3529Error
Jim Inghamacff8952013-05-02 00:27:30 +00003530Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003531{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003532 EventSP exit_event_sp;
3533 Error error;
3534 m_destroy_in_process = true;
3535
3536 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003537
3538 if (error.Success())
3539 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003540 if (DetachRequiresHalt())
3541 {
3542 error = HaltForDestroyOrDetach (exit_event_sp);
3543 if (!error.Success())
3544 {
3545 m_destroy_in_process = false;
3546 return error;
3547 }
3548 else if (exit_event_sp)
3549 {
3550 // We shouldn't need to do anything else here. There's no process left to detach from...
3551 StopPrivateStateThread();
3552 m_destroy_in_process = false;
3553 return error;
3554 }
3555 }
3556
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003557 m_thread_list.DiscardThreadPlans();
3558 DisableAllBreakpointSites();
3559
Jim Inghamacff8952013-05-02 00:27:30 +00003560 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 if (error.Success())
3562 {
3563 DidDetach();
3564 StopPrivateStateThread();
3565 }
Jim Inghamacff8952013-05-02 00:27:30 +00003566 else
3567 {
3568 return error;
3569 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003570 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003571 m_destroy_in_process = false;
3572
3573 // If we exited when we were waiting for a process to stop, then
3574 // forward the event here so we don't lose the event
3575 if (exit_event_sp)
3576 {
3577 // Directly broadcast our exited event because we shut down our
3578 // private state thread above
3579 BroadcastEvent(exit_event_sp);
3580 }
3581
3582 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3583 // the last events through the event system, in which case we might strand the write lock. Unlock
3584 // it here so when we do to tear down the process we don't get an error destroying the lock.
3585
Ed Maste64fad602013-07-29 20:58:06 +00003586 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587 return error;
3588}
3589
3590Error
3591Process::Destroy ()
3592{
Jim Ingham09437922013-03-01 20:04:25 +00003593
3594 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3595 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3596 // failed and the process stays around for some reason it won't be in a confused state.
3597
3598 m_destroy_in_process = true;
3599
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003600 Error error (WillDestroy());
3601 if (error.Success())
3602 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003603 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003604 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003605 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003606 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003607 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003608
Jim Inghamaacc3182012-06-06 00:29:30 +00003609 if (m_public_state.GetValue() != eStateRunning)
3610 {
3611 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3612 // kill it, we don't want it hitting a breakpoint...
3613 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3614 // we're not going to have much luck doing this now.
3615 m_thread_list.DiscardThreadPlans();
3616 DisableAllBreakpointSites();
3617 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003618
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003619 error = DoDestroy();
3620 if (error.Success())
3621 {
3622 DidDestroy();
3623 StopPrivateStateThread();
3624 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003625 m_stdio_communication.StopReadThread();
3626 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003627
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003628 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003629 {
3630 m_process_input_reader->SetIsDone(true);
3631 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003632 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003633 }
3634
Greg Clayton85fb1b92012-09-11 02:33:37 +00003635 // If we exited when we were waiting for a process to stop, then
3636 // forward the event here so we don't lose the event
3637 if (exit_event_sp)
3638 {
3639 // Directly broadcast our exited event because we shut down our
3640 // private state thread above
3641 BroadcastEvent(exit_event_sp);
3642 }
3643
Jim Inghamb1e2e842012-04-12 18:49:31 +00003644 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3645 // the last events through the event system, in which case we might strand the write lock. Unlock
3646 // 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 +00003647 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648 }
Jim Ingham09437922013-03-01 20:04:25 +00003649
3650 m_destroy_in_process = false;
3651
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003652 return error;
3653}
3654
3655Error
3656Process::Signal (int signal)
3657{
3658 Error error (WillSignal());
3659 if (error.Success())
3660 {
3661 error = DoSignal(signal);
3662 if (error.Success())
3663 DidSignal();
3664 }
3665 return error;
3666}
3667
Greg Clayton514487e2011-02-15 21:59:32 +00003668lldb::ByteOrder
3669Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003670{
Greg Clayton514487e2011-02-15 21:59:32 +00003671 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672}
3673
3674uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003675Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676{
Greg Clayton514487e2011-02-15 21:59:32 +00003677 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003678}
3679
Greg Clayton514487e2011-02-15 21:59:32 +00003680
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003681bool
3682Process::ShouldBroadcastEvent (Event *event_ptr)
3683{
3684 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3685 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003686 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003687
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003688 switch (state)
3689 {
Greg Claytonb766a732011-02-04 01:58:07 +00003690 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003691 case eStateAttaching:
3692 case eStateLaunching:
3693 case eStateDetached:
3694 case eStateExited:
3695 case eStateUnloaded:
3696 // These events indicate changes in the state of the debugging session, always report them.
3697 return_value = true;
3698 break;
3699 case eStateInvalid:
3700 // We stopped for no apparent reason, don't report it.
3701 return_value = false;
3702 break;
3703 case eStateRunning:
3704 case eStateStepping:
3705 // If we've started the target running, we handle the cases where we
3706 // are already running and where there is a transition from stopped to
3707 // running differently.
3708 // running -> running: Automatically suppress extra running events
3709 // stopped -> running: Report except when there is one or more no votes
3710 // and no yes votes.
3711 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003712 if (m_force_next_event_delivery)
3713 return_value = true;
3714 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003715 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003716 switch (m_last_broadcast_state)
3717 {
3718 case eStateRunning:
3719 case eStateStepping:
3720 // We always suppress multiple runnings with no PUBLIC stop in between.
3721 return_value = false;
3722 break;
3723 default:
3724 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003725 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003726 // events. If I run the lldb/test/thread/a.out file and
3727 // break at main.cpp:58, run and hit the breakpoints on
3728 // multiple threads, then somehow during the stepping over
3729 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003730
Jim Ingham1460e4b2014-01-10 23:46:59 +00003731 // This is a transition from stop to run.
3732 switch (m_thread_list.ShouldReportRun (event_ptr))
3733 {
3734 case eVoteYes:
3735 case eVoteNoOpinion:
3736 return_value = true;
3737 break;
3738 case eVoteNo:
3739 return_value = false;
3740 break;
3741 }
3742 break;
3743 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744 }
3745 break;
3746 case eStateStopped:
3747 case eStateCrashed:
3748 case eStateSuspended:
3749 {
3750 // We've stopped. First see if we're going to restart the target.
3751 // If we are going to stop, then we always broadcast the event.
3752 // 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 +00003753 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003754
Jim Inghamcb4ca112012-05-16 01:32:14 +00003755 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003756 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003757 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003758 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003759 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003760 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003761 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003762 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3763 // so they can properly set their state.
3764 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003765 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003766 }
3767 else
3768 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003769 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3770 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003771
Jim Ingham0161b492013-02-09 01:29:05 +00003772 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3773 // Asking the thread list is also not likely to go well, since we are running again.
3774 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003775
Jim Ingham0161b492013-02-09 01:29:05 +00003776 if (!was_restarted)
3777 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003778
Jim Ingham221d51c2013-05-08 00:35:16 +00003779 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780 {
Jim Ingham0161b492013-02-09 01:29:05 +00003781 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3782 if (log)
3783 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003784 should_resume, StateAsCString(state),
3785 was_restarted, stop_vote);
3786
Jim Ingham0161b492013-02-09 01:29:05 +00003787 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003788 {
3789 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003790 return_value = true;
3791 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003792 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003793 case eVoteNo:
3794 return_value = false;
3795 break;
3796 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003797
Jim Inghamcb95f342012-09-05 21:13:56 +00003798 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003799 {
3800 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003801 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3802 static_cast<void*>(event_ptr),
3803 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003804 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003805 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003806 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003807
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003808 }
3809 else
3810 {
3811 return_value = true;
3812 SynchronouslyNotifyStateChanged (state);
3813 }
3814 }
3815 }
Jim Ingham0161b492013-02-09 01:29:05 +00003816 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003818
Jim Ingham1460e4b2014-01-10 23:46:59 +00003819 // Forcing the next event delivery is a one shot deal. So reset it here.
3820 m_force_next_event_delivery = false;
3821
Jim Ingham0161b492013-02-09 01:29:05 +00003822 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3823 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3824 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3825 // because the PublicState reflects the last event pulled off the queue, and there may be several
3826 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3827 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003828
Jim Ingham0161b492013-02-09 01:29:05 +00003829 if (return_value)
3830 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003831
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003833 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003834 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003835 StateAsCString(m_last_broadcast_state),
3836 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003837 return return_value;
3838}
3839
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840
3841bool
Jim Ingham372787f2012-04-07 00:00:41 +00003842Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843{
Greg Clayton5160ce52013-03-27 23:08:40 +00003844 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003845
Greg Clayton8b82f082011-04-12 05:54:46 +00003846 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003848 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3849
Jim Ingham372787f2012-04-07 00:00:41 +00003850 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003851 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003852
3853 // Create a thread that watches our internal state and controls which
3854 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003855 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003856
Zachary Turner39de3112014-09-09 20:54:56 +00003857 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00003858 {
Zachary Turner39de3112014-09-09 20:54:56 +00003859 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3860 if (already_running)
3861 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3862 else
3863 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00003864 }
Jim Ingham372787f2012-04-07 00:00:41 +00003865 else
Todd Fiala17096d72014-07-16 19:03:16 +00003866 {
3867 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00003868 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003869 else
Zachary Turner39de3112014-09-09 20:54:56 +00003870 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003871 }
3872
Jim Ingham076b3042012-04-10 01:21:57 +00003873 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00003874 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00003875 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00003876 {
3877 ResumePrivateStateThread();
3878 return true;
3879 }
3880 else
3881 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003882}
3883
3884void
3885Process::PausePrivateStateThread ()
3886{
3887 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3888}
3889
3890void
3891Process::ResumePrivateStateThread ()
3892{
3893 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3894}
3895
3896void
3897Process::StopPrivateStateThread ()
3898{
Greg Clayton8b82f082011-04-12 05:54:46 +00003899 if (PrivateStateThreadIsValid ())
3900 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003901 else
3902 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003903 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003904 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003905 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003906 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003907}
3908
3909void
3910Process::ControlPrivateStateThread (uint32_t signal)
3911{
Greg Clayton5160ce52013-03-27 23:08:40 +00003912 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003913
3914 assert (signal == eBroadcastInternalStateControlStop ||
3915 signal == eBroadcastInternalStateControlPause ||
3916 signal == eBroadcastInternalStateControlResume);
3917
3918 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003919 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003920
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003921 // Signal the private state thread. First we should copy this is case the
3922 // thread starts exiting since the private state thread will NULL this out
3923 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00003924 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00003925 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003926 {
3927 TimeValue timeout_time;
3928 bool timed_out;
3929
3930 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3931
3932 timeout_time = TimeValue::Now();
3933 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003934 if (log)
3935 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003936 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3937 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3938
3939 if (signal == eBroadcastInternalStateControlStop)
3940 {
3941 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003942 {
Zachary Turner39de3112014-09-09 20:54:56 +00003943 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003944 if (log)
3945 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3946 }
3947 else
3948 {
3949 if (log)
3950 log->Printf ("The control event killed the private state thread without having to cancel.");
3951 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003952
3953 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00003954 private_state_thread.Join(&result);
3955 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003956 }
3957 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003958 else
3959 {
3960 if (log)
3961 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3962 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003963}
3964
3965void
Jim Inghamcfc09352012-07-27 23:57:19 +00003966Process::SendAsyncInterrupt ()
3967{
3968 if (PrivateStateThreadIsValid())
3969 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3970 else
3971 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3972}
3973
3974void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003975Process::HandlePrivateEvent (EventSP &event_sp)
3976{
Greg Clayton5160ce52013-03-27 23:08:40 +00003977 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003978 m_resume_requested = false;
3979
Jim Inghamaacc3182012-06-06 00:29:30 +00003980 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003981
Greg Clayton414f5d32011-01-25 02:58:48 +00003982 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003983
3984 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003985 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003986 {
Jim Ingham754ab982011-01-29 04:05:41 +00003987 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003988 if (log)
3989 log->Printf ("Ran next event action, result was %d.", action_result);
3990
Jim Inghambb3a2832011-01-29 01:49:25 +00003991 switch (action_result)
3992 {
3993 case NextEventAction::eEventActionSuccess:
3994 SetNextEventAction(NULL);
3995 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003996
Jim Inghambb3a2832011-01-29 01:49:25 +00003997 case NextEventAction::eEventActionRetry:
3998 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003999
Jim Inghambb3a2832011-01-29 01:49:25 +00004000 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004001 // Handle Exiting Here. If we already got an exited event,
4002 // we should just propagate it. Otherwise, swallow this event,
4003 // and set our state to exit so the next event will kill us.
4004 if (new_state != eStateExited)
4005 {
4006 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004007 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004008 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004009 SetNextEventAction(NULL);
4010 return;
4011 }
4012 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004013 break;
4014 }
4015 }
4016
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004017 // See if we should broadcast this state to external clients?
4018 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004019
4020 if (should_broadcast)
4021 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004022 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004023 if (log)
4024 {
Daniel Malead01b2952012-11-29 21:49:15 +00004025 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004026 __FUNCTION__,
4027 GetID(),
4028 StateAsCString(new_state),
4029 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004030 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004031 }
Jim Ingham9575d842011-03-11 03:53:59 +00004032 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004033 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004034 {
4035 // Only push the input handler if we aren't fowarding events,
4036 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004037 // Or don't push it if we are launching since it will come up stopped.
4038 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004039 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004040 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004041 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004042 else if (StateIsStoppedState(new_state, false))
4043 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004044 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004045 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4046 {
4047 // If the lldb_private::Debugger is handling the events, we don't
4048 // want to pop the process IOHandler here, we want to do it when
4049 // we receive the stopped event so we can carefully control when
4050 // the process IOHandler is popped because when we stop we want to
4051 // display some text stating how and why we stopped, then maybe some
4052 // process/thread/frame info, and then we want the "(lldb) " prompt
4053 // to show up. If we pop the process IOHandler here, then we will
4054 // cause the command interpreter to become the top IOHandler after
4055 // the process pops off and it will update its prompt right away...
4056 // See the Debugger.cpp file where it calls the function as
4057 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4058 // Otherwise we end up getting overlapping "(lldb) " prompts and
4059 // garbled output.
4060 //
4061 // If we aren't handling the events in the debugger (which is indicated
4062 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4063 // are hijacked, then we always pop the process IO handler manually.
4064 // Hijacking happens when the internal process state thread is running
4065 // thread plans, or when commands want to run in synchronous mode
4066 // and they call "process->WaitForProcessToStop()". An example of something
4067 // that will hijack the events is a simple expression:
4068 //
4069 // (lldb) expr (int)puts("hello")
4070 //
4071 // This will cause the internal process state thread to resume and halt
4072 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4073 // events) and we do need the IO handler to be pushed and popped
4074 // correctly.
4075
4076 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4077 PopProcessIOHandler ();
4078 }
4079 }
Jim Ingham9575d842011-03-11 03:53:59 +00004080
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004081 BroadcastEvent (event_sp);
4082 }
4083 else
4084 {
4085 if (log)
4086 {
Daniel Malead01b2952012-11-29 21:49:15 +00004087 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004088 __FUNCTION__,
4089 GetID(),
4090 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004091 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092 }
4093 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004094 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004095}
4096
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004097thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098Process::PrivateStateThread (void *arg)
4099{
4100 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004101 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102 return result;
4103}
4104
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004105thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004106Process::RunPrivateStateThread ()
4107{
Jim Ingham076b3042012-04-10 01:21:57 +00004108 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004109 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110
Greg Clayton5160ce52013-03-27 23:08:40 +00004111 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004112 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004113 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4114 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115
4116 bool exit_now = false;
4117 while (!exit_now)
4118 {
4119 EventSP event_sp;
4120 WaitForEventsPrivate (NULL, event_sp, control_only);
4121 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4122 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004123 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004124 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4125 __FUNCTION__, static_cast<void*>(this), GetID(),
4126 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004127
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128 switch (event_sp->GetType())
4129 {
4130 case eBroadcastInternalStateControlStop:
4131 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004132 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004133
4134 case eBroadcastInternalStateControlPause:
4135 control_only = true;
4136 break;
4137
4138 case eBroadcastInternalStateControlResume:
4139 control_only = false;
4140 break;
4141 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004143 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004144 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004146 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4147 {
4148 if (m_public_state.GetValue() == eStateAttaching)
4149 {
4150 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004151 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4152 __FUNCTION__, static_cast<void*>(this),
4153 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004154 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4155 }
4156 else
4157 {
4158 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004159 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4160 __FUNCTION__, static_cast<void*>(this),
4161 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004162 Halt();
4163 }
4164 continue;
4165 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004166
4167 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4168
4169 if (internal_state != eStateInvalid)
4170 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004171 if (m_clear_thread_plans_on_stop &&
4172 StateIsStoppedState(internal_state, true))
4173 {
4174 m_clear_thread_plans_on_stop = false;
4175 m_thread_list.DiscardThreadPlans();
4176 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004177 HandlePrivateEvent (event_sp);
4178 }
4179
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004180 if (internal_state == eStateInvalid ||
4181 internal_state == eStateExited ||
4182 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004183 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004184 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004185 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4186 __FUNCTION__, static_cast<void*>(this), GetID(),
4187 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004188
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004189 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004190 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004191 }
4192
Caroline Tice20ad3c42010-10-29 21:48:37 +00004193 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004194 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004195 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4196 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004197
Ed Maste64fad602013-07-29 20:58:06 +00004198 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004199 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004200 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004201 return NULL;
4202}
4203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004204//------------------------------------------------------------------
4205// Process Event Data
4206//------------------------------------------------------------------
4207
4208Process::ProcessEventData::ProcessEventData () :
4209 EventData (),
4210 m_process_sp (),
4211 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004212 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004213 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004214 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004215{
4216}
4217
4218Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4219 EventData (),
4220 m_process_sp (process_sp),
4221 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004222 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004223 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004224 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225{
4226}
4227
4228Process::ProcessEventData::~ProcessEventData()
4229{
4230}
4231
4232const ConstString &
4233Process::ProcessEventData::GetFlavorString ()
4234{
4235 static ConstString g_flavor ("Process::ProcessEventData");
4236 return g_flavor;
4237}
4238
4239const ConstString &
4240Process::ProcessEventData::GetFlavor () const
4241{
4242 return ProcessEventData::GetFlavorString ();
4243}
4244
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004245void
4246Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4247{
4248 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004249 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4250 // the public event queue, then other times when we're pretending that this is where we stopped at the
4251 // end of expression evaluation. m_update_state is used to distinguish these
4252 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004253 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004254 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004255 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004256
Jim Ingham221d51c2013-05-08 00:35:16 +00004257 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004258
4259 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4260 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4261 // end up restarting the process.
4262 if (m_interrupted)
4263 return;
4264
4265 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004266 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004267 {
4268 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004269 uint32_t num_threads = curr_thread_list.GetSize();
4270 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004271
Jim Ingham4b536182011-08-09 02:12:22 +00004272 // The actions might change one of the thread's stop_info's opinions about whether we should
4273 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004274
4275 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4276 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4277 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4278 // 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
4279 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004280 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004281 for (idx = 0; idx < num_threads; ++idx)
4282 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4283
Jim Inghamc7078c22012-12-13 22:24:15 +00004284 // Use this to track whether we should continue from here. We will only continue the target running if
4285 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4286 // then it doesn't matter what the other threads say...
4287
4288 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004289
Jim Ingham0ad7e052013-04-25 02:04:59 +00004290 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4291 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4292 // thing to do is, and it's better to let the user decide than continue behind their backs.
4293
4294 bool does_anybody_have_an_opinion = false;
4295
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004296 for (idx = 0; idx < num_threads; ++idx)
4297 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004298 curr_thread_list = m_process_sp->GetThreadList();
4299 if (curr_thread_list.GetSize() != num_threads)
4300 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004301 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004302 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004303 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 +00004304 break;
4305 }
4306
4307 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4308
4309 if (thread_sp->GetIndexID() != thread_index_array[idx])
4310 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004311 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004312 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004313 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004314 idx,
4315 thread_index_array[idx],
4316 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004317 break;
4318 }
4319
Jim Inghamb15bfc72010-10-20 00:39:53 +00004320 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004321 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004322 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004323 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004324 bool this_thread_wants_to_stop;
4325 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004326 {
Jim Ingham0161b492013-02-09 01:29:05 +00004327 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4328 }
4329 else
4330 {
4331 stop_info_sp->PerformAction(event_ptr);
4332 // The stop action might restart the target. If it does, then we want to mark that in the
4333 // event so that whoever is receiving it will know to wait for the running event and reflect
4334 // that state appropriately.
4335 // We also need to stop processing actions, since they aren't expecting the target to be running.
4336
4337 // FIXME: we might have run.
4338 if (stop_info_sp->HasTargetRunSinceMe())
4339 {
4340 SetRestarted (true);
4341 break;
4342 }
4343
4344 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004345 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004346
Jim Inghamc7078c22012-12-13 22:24:15 +00004347 if (still_should_stop == false)
4348 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004349 }
4350 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004351
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004352
Jim Inghama8ca6e22013-05-03 23:04:37 +00004353 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004354 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004355 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004356 {
4357 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004358 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004359 // Use the public resume method here, since this is just
4360 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004361 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004362 }
4363 else
4364 {
4365 // If we didn't restart, run the Stop Hooks here:
4366 // They might also restart the target, so watch for that.
4367 m_process_sp->GetTarget().RunStopHooks();
4368 if (m_process_sp->GetPrivateState() == eStateRunning)
4369 SetRestarted(true);
4370 }
Jim Ingham9575d842011-03-11 03:53:59 +00004371 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004372 }
4373}
4374
4375void
4376Process::ProcessEventData::Dump (Stream *s) const
4377{
4378 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004379 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4380 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004381
Greg Clayton8b82f082011-04-12 05:54:46 +00004382 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004383}
4384
4385const Process::ProcessEventData *
4386Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4387{
4388 if (event_ptr)
4389 {
4390 const EventData *event_data = event_ptr->GetData();
4391 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4392 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4393 }
4394 return NULL;
4395}
4396
4397ProcessSP
4398Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4399{
4400 ProcessSP process_sp;
4401 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4402 if (data)
4403 process_sp = data->GetProcessSP();
4404 return process_sp;
4405}
4406
4407StateType
4408Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4409{
4410 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4411 if (data == NULL)
4412 return eStateInvalid;
4413 else
4414 return data->GetState();
4415}
4416
4417bool
4418Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4419{
4420 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4421 if (data == NULL)
4422 return false;
4423 else
4424 return data->GetRestarted();
4425}
4426
4427void
4428Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4429{
4430 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4431 if (data != NULL)
4432 data->SetRestarted(new_value);
4433}
4434
Jim Ingham0161b492013-02-09 01:29:05 +00004435size_t
4436Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4437{
4438 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4439 if (data != NULL)
4440 return data->GetNumRestartedReasons();
4441 else
4442 return 0;
4443}
4444
4445const char *
4446Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4447{
4448 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4449 if (data != NULL)
4450 return data->GetRestartedReasonAtIndex(idx);
4451 else
4452 return NULL;
4453}
4454
4455void
4456Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4457{
4458 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4459 if (data != NULL)
4460 data->AddRestartedReason(reason);
4461}
4462
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004463bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004464Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4465{
4466 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4467 if (data == NULL)
4468 return false;
4469 else
4470 return data->GetInterrupted ();
4471}
4472
4473void
4474Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4475{
4476 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4477 if (data != NULL)
4478 data->SetInterrupted(new_value);
4479}
4480
4481bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004482Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4483{
4484 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4485 if (data)
4486 {
4487 data->SetUpdateStateOnRemoval();
4488 return true;
4489 }
4490 return false;
4491}
4492
Greg Claytond9e416c2012-02-18 05:35:26 +00004493lldb::TargetSP
4494Process::CalculateTarget ()
4495{
4496 return m_target.shared_from_this();
4497}
4498
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004499void
Greg Clayton0603aa92010-10-04 01:05:56 +00004500Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004501{
Greg Claytonc14ee322011-09-22 04:58:26 +00004502 exe_ctx.SetTargetPtr (&m_target);
4503 exe_ctx.SetProcessPtr (this);
4504 exe_ctx.SetThreadPtr(NULL);
4505 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004506}
4507
Greg Claytone996fd32011-03-08 22:40:15 +00004508//uint32_t
4509//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4510//{
4511// return 0;
4512//}
4513//
4514//ArchSpec
4515//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4516//{
4517// return Host::GetArchSpecForExistingProcess (pid);
4518//}
4519//
4520//ArchSpec
4521//Process::GetArchSpecForExistingProcess (const char *process_name)
4522//{
4523// return Host::GetArchSpecForExistingProcess (process_name);
4524//}
4525//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004526void
4527Process::AppendSTDOUT (const char * s, size_t len)
4528{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004529 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004530 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004531 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004532}
4533
4534void
Greg Clayton93e86192011-11-13 04:45:22 +00004535Process::AppendSTDERR (const char * s, size_t len)
4536{
4537 Mutex::Locker locker (m_stdio_communication_mutex);
4538 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004539 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004540}
4541
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004542void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004543Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004544{
4545 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004546 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004547 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4548}
4549
4550size_t
4551Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4552{
4553 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004554 if (m_profile_data.empty())
4555 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004556
4557 std::string &one_profile_data = m_profile_data.front();
4558 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004559 if (bytes_available > 0)
4560 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004561 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004562 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004563 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4564 static_cast<void*>(buf),
4565 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004566 if (bytes_available > buf_size)
4567 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004568 memcpy(buf, one_profile_data.c_str(), buf_size);
4569 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004570 bytes_available = buf_size;
4571 }
4572 else
4573 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004574 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004575 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004576 }
4577 }
4578 return bytes_available;
4579}
4580
4581
Greg Clayton93e86192011-11-13 04:45:22 +00004582//------------------------------------------------------------------
4583// Process STDIO
4584//------------------------------------------------------------------
4585
4586size_t
4587Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4588{
4589 Mutex::Locker locker(m_stdio_communication_mutex);
4590 size_t bytes_available = m_stdout_data.size();
4591 if (bytes_available > 0)
4592 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004593 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004594 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004595 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4596 static_cast<void*>(buf),
4597 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004598 if (bytes_available > buf_size)
4599 {
4600 memcpy(buf, m_stdout_data.c_str(), buf_size);
4601 m_stdout_data.erase(0, buf_size);
4602 bytes_available = buf_size;
4603 }
4604 else
4605 {
4606 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4607 m_stdout_data.clear();
4608 }
4609 }
4610 return bytes_available;
4611}
4612
4613
4614size_t
4615Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4616{
4617 Mutex::Locker locker(m_stdio_communication_mutex);
4618 size_t bytes_available = m_stderr_data.size();
4619 if (bytes_available > 0)
4620 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004621 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004622 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004623 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4624 static_cast<void*>(buf),
4625 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004626 if (bytes_available > buf_size)
4627 {
4628 memcpy(buf, m_stderr_data.c_str(), buf_size);
4629 m_stderr_data.erase(0, buf_size);
4630 bytes_available = buf_size;
4631 }
4632 else
4633 {
4634 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4635 m_stderr_data.clear();
4636 }
4637 }
4638 return bytes_available;
4639}
4640
4641void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004642Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4643{
4644 Process *process = (Process *) baton;
4645 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4646}
4647
Greg Clayton44d93782014-01-27 23:43:24 +00004648class IOHandlerProcessSTDIO :
4649 public IOHandler
4650{
4651public:
4652 IOHandlerProcessSTDIO (Process *process,
4653 int write_fd) :
4654 IOHandler(process->GetTarget().GetDebugger()),
4655 m_process (process),
4656 m_read_file (),
4657 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004658 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004659 {
4660 m_read_file.SetDescriptor(GetInputFD(), false);
4661 }
4662
4663 virtual
4664 ~IOHandlerProcessSTDIO ()
4665 {
4666
4667 }
4668
4669 bool
4670 OpenPipes ()
4671 {
Greg Clayton100eb932014-07-02 21:10:39 +00004672 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004673 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004674 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004675 }
4676
4677 void
4678 ClosePipes()
4679 {
Greg Clayton100eb932014-07-02 21:10:39 +00004680 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004681 }
4682
4683 // Each IOHandler gets to run until it is done. It should read data
4684 // from the "in" and place output into "out" and "err and return
4685 // when done.
4686 virtual void
4687 Run ()
4688 {
4689 if (m_read_file.IsValid() && m_write_file.IsValid())
4690 {
4691 SetIsDone(false);
4692 if (OpenPipes())
4693 {
4694 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004695 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004696 TerminalState terminal_state;
4697 terminal_state.Save (read_fd, false);
4698 Terminal terminal(read_fd);
4699 terminal.SetCanonical(false);
4700 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004701// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004702#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004703 while (!GetIsDone())
4704 {
4705 fd_set read_fdset;
4706 FD_ZERO (&read_fdset);
4707 FD_SET (read_fd, &read_fdset);
4708 FD_SET (pipe_read_fd, &read_fdset);
4709 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4710 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4711 if (num_set_fds < 0)
4712 {
4713 const int select_errno = errno;
4714
4715 if (select_errno != EINTR)
4716 SetIsDone(true);
4717 }
4718 else if (num_set_fds > 0)
4719 {
4720 char ch = 0;
4721 size_t n;
4722 if (FD_ISSET (read_fd, &read_fdset))
4723 {
4724 n = 1;
4725 if (m_read_file.Read(&ch, n).Success() && n == 1)
4726 {
4727 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4728 SetIsDone(true);
4729 }
4730 else
4731 SetIsDone(true);
4732 }
4733 if (FD_ISSET (pipe_read_fd, &read_fdset))
4734 {
4735 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004736 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004737 {
Greg Clayton100eb932014-07-02 21:10:39 +00004738 switch (ch)
4739 {
4740 case 'q':
4741 SetIsDone(true);
4742 break;
4743 case 'i':
4744 if (StateIsRunningState(m_process->GetState()))
4745 m_process->Halt();
4746 break;
4747 }
Greg Clayton19e11352014-02-26 22:47:33 +00004748 }
Greg Clayton44d93782014-01-27 23:43:24 +00004749 }
4750 }
4751 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004752#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004753 terminal_state.Restore();
4754
4755 }
4756 else
4757 SetIsDone(true);
4758 }
4759 else
4760 SetIsDone(true);
4761 }
4762
4763 // Hide any characters that have been displayed so far so async
4764 // output can be displayed. Refresh() will be called after the
4765 // output has been displayed.
4766 virtual void
4767 Hide ()
4768 {
4769
4770 }
4771 // Called when the async output has been received in order to update
4772 // the input reader (refresh the prompt and redisplay any current
4773 // line(s) that are being edited
4774 virtual void
4775 Refresh ()
4776 {
4777
4778 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004779
Greg Clayton44d93782014-01-27 23:43:24 +00004780 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004781 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004782 {
Greg Clayton19e11352014-02-26 22:47:33 +00004783 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004784 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004785 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004786
Greg Claytonf0066ad2014-05-02 00:45:31 +00004787 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004788 Interrupt ()
4789 {
Greg Clayton19e11352014-02-26 22:47:33 +00004790 // Do only things that are safe to do in an interrupt context (like in
4791 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4792 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4793 // that was written to the pipe and then call m_process->Halt() from a
4794 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004795 if (m_active)
4796 {
4797 char ch = 'i'; // Send 'i' for interrupt
4798 return m_pipe.Write (&ch, 1) == 1;
4799 }
4800 else
4801 {
4802 // This IOHandler might be pushed on the stack, but not being run currently
4803 // so do the right thing if we aren't actively watching for STDIN by sending
4804 // the interrupt to the process. Otherwise the write to the pipe above would
4805 // do nothing. This can happen when the command interpreter is running and
4806 // gets a "expression ...". It will be on the IOHandler thread and sending
4807 // the input is complete to the delegate which will cause the expression to
4808 // run, which will push the process IO handler, but not run it.
4809
4810 if (StateIsRunningState(m_process->GetState()))
4811 {
4812 m_process->SendAsyncInterrupt();
4813 return true;
4814 }
4815 }
4816 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004817 }
Greg Clayton44d93782014-01-27 23:43:24 +00004818
4819 virtual void
4820 GotEOF()
4821 {
4822
4823 }
4824
4825protected:
4826 Process *m_process;
4827 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4828 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004829 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004830};
4831
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004832void
Greg Clayton44d93782014-01-27 23:43:24 +00004833Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004834{
4835 // First set up the Read Thread for reading/handling process I/O
4836
Greg Clayton44d93782014-01-27 23:43:24 +00004837 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004838
4839 if (conn_ap.get())
4840 {
4841 m_stdio_communication.SetConnection (conn_ap.release());
4842 if (m_stdio_communication.IsConnected())
4843 {
4844 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4845 m_stdio_communication.StartReadThread();
4846
4847 // Now read thread is set up, set up input reader.
4848
4849 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004850 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004851 }
4852 }
4853}
4854
Greg Claytonb4874f12014-02-28 18:22:24 +00004855bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004856Process::ProcessIOHandlerIsActive ()
4857{
4858 IOHandlerSP io_handler_sp (m_process_input_reader);
4859 if (io_handler_sp)
4860 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4861 return false;
4862}
4863bool
Greg Clayton44d93782014-01-27 23:43:24 +00004864Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004865{
Greg Clayton44d93782014-01-27 23:43:24 +00004866 IOHandlerSP io_handler_sp (m_process_input_reader);
4867 if (io_handler_sp)
4868 {
4869 io_handler_sp->SetIsDone(false);
4870 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004871 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004872 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004873 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004874}
4875
Greg Claytonb4874f12014-02-28 18:22:24 +00004876bool
Greg Clayton44d93782014-01-27 23:43:24 +00004877Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004878{
Greg Clayton44d93782014-01-27 23:43:24 +00004879 IOHandlerSP io_handler_sp (m_process_input_reader);
4880 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004881 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4882 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004883}
4884
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004885// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004886void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004887Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004888{
Greg Clayton6920b522012-08-22 18:39:03 +00004889 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004890}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004891
Greg Clayton99d0faf2010-11-18 23:32:35 +00004892void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004893Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004894{
Greg Clayton6920b522012-08-22 18:39:03 +00004895 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004896}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004897
Jim Ingham1624a2d2014-05-05 02:26:40 +00004898ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004899Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004900 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004901 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004902 Stream &errors)
4903{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004904 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004905
Jim Ingham77787032011-01-20 02:03:18 +00004906 if (thread_plan_sp.get() == NULL)
4907 {
4908 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004909 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004910 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004911
Jim Ingham7d7931d2013-03-28 00:05:34 +00004912 if (!thread_plan_sp->ValidatePlan(NULL))
4913 {
4914 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004915 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004916 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004917
Greg Claytonc14ee322011-09-22 04:58:26 +00004918 if (exe_ctx.GetProcessPtr() != this)
4919 {
4920 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004921 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004922 }
4923
4924 Thread *thread = exe_ctx.GetThreadPtr();
4925 if (thread == NULL)
4926 {
4927 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004928 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004929 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004930
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004931 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4932 // For that to be true the plan can't be private - since private plans suppress themselves in the
4933 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004934
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004935 bool orig_plan_private = thread_plan_sp->GetPrivate();
4936 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004937
Jim Ingham444586b2011-01-24 06:34:17 +00004938 if (m_private_state.GetValue() != eStateStopped)
4939 {
4940 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004941 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004942 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004943
Jim Ingham66243842011-08-13 00:56:10 +00004944 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004945 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004946 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004947 if (!selected_frame_sp)
4948 {
4949 thread->SetSelectedFrame(0);
4950 selected_frame_sp = thread->GetSelectedFrame();
4951 if (!selected_frame_sp)
4952 {
4953 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004954 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004955 }
4956 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004957
Jim Ingham11b0e052013-02-19 23:22:45 +00004958 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004959
4960 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4961 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004962
Greg Claytonc14ee322011-09-22 04:58:26 +00004963 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004964
Jim Ingham66243842011-08-13 00:56:10 +00004965 uint32_t selected_tid;
4966 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004967 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004968 {
4969 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004970 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004971 }
4972 else
4973 {
4974 selected_tid = LLDB_INVALID_THREAD_ID;
4975 }
4976
Zachary Turner39de3112014-09-09 20:54:56 +00004977 HostThread backup_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004978 lldb::StateType old_state;
4979 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004980
Greg Clayton5160ce52013-03-27 23:08:40 +00004981 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00004982 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00004983 {
Jim Ingham076b3042012-04-10 01:21:57 +00004984 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4985 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004986 // 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 +00004987 // we are fielding public events here.
4988 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004989 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 +00004990
Jim Ingham372787f2012-04-07 00:00:41 +00004991 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004992
4993 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4994 // returning control here.
4995 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4996 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4997 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4998 // do just what we want.
4999 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5000 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5001 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5002 old_state = m_public_state.GetValue();
5003 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005004
Jim Ingham076b3042012-04-10 01:21:57 +00005005 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005006 StartPrivateStateThread(true);
5007 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005008
Jim Ingham372787f2012-04-07 00:00:41 +00005009 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005010
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005011 if (options.GetDebug())
5012 {
5013 // In this case, we aren't actually going to run, we just want to stop right away.
5014 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5015 // FIXME: To make this prettier we should invent some stop reason for this, but that
5016 // is only cosmetic, and this functionality is only of use to lldb developers who can
5017 // live with not pretty...
5018 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005019 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005020 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005021
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005022 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005023
Sean Callanana46ec452012-07-11 21:31:24 +00005024 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005025
Jim Ingham77787032011-01-20 02:03:18 +00005026 {
Sean Callanana46ec452012-07-11 21:31:24 +00005027 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5028 // restored on exit to the function.
5029 //
5030 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5031 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005032
Sean Callanana46ec452012-07-11 21:31:24 +00005033 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005034
Jim Inghamf48169b2010-11-30 02:22:11 +00005035 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005036 {
5037 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005038 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005039 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005040 thread->GetIndexID(),
5041 thread->GetID(),
5042 s.GetData());
5043 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005044
Sean Callanana46ec452012-07-11 21:31:24 +00005045 bool got_event;
5046 lldb::EventSP event_sp;
5047 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005048
Sean Callanana46ec452012-07-11 21:31:24 +00005049 TimeValue* timeout_ptr = NULL;
5050 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005051
Jim Ingham0161b492013-02-09 01:29:05 +00005052 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 +00005053 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005054 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005055 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005056
Jim Ingham0161b492013-02-09 01:29:05 +00005057 // This is just for accounting:
5058 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005059
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005060 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005061 uint32_t one_thread_timeout_usec;
5062 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005063
5064 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5065 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5066 // first timeout already.
5067
5068 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005069 {
5070 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005071 one_thread_timeout_usec = 0;
5072 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005073 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005074 else
Jim Ingham0161b492013-02-09 01:29:05 +00005075 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005076 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005077
Jim Ingham914f4e72014-03-28 21:58:28 +00005078 // If the overall wait is forever, then we only need to set the one thread timeout:
5079 if (timeout_usec == 0)
5080 {
Ed Maste801335c2014-03-31 19:28:14 +00005081 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005082 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005083 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005084 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005085 }
Jim Ingham0161b492013-02-09 01:29:05 +00005086 else
5087 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005088 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5089 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5090 uint64_t computed_one_thread_timeout;
5091 if (option_one_thread_timeout != 0)
5092 {
5093 if (timeout_usec < option_one_thread_timeout)
5094 {
5095 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005096 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005097 }
5098 computed_one_thread_timeout = option_one_thread_timeout;
5099 }
5100 else
5101 {
5102 computed_one_thread_timeout = timeout_usec / 2;
5103 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5104 computed_one_thread_timeout = default_one_thread_timeout_usec;
5105 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005106 one_thread_timeout_usec = computed_one_thread_timeout;
5107 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5108
Jim Ingham0161b492013-02-09 01:29:05 +00005109 }
Jim Ingham0161b492013-02-09 01:29:05 +00005110 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005111
5112 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005113 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 +00005114 options.GetStopOthers(),
5115 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005116 before_first_timeout,
5117 one_thread_timeout_usec,
5118 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005119
Jim Ingham1460e4b2014-01-10 23:46:59 +00005120 // This isn't going to work if there are unfetched events on the queue.
5121 // Are there cases where we might want to run the remaining events here, and then try to
5122 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005123
Jim Ingham1460e4b2014-01-10 23:46:59 +00005124 Event *other_events = listener.PeekAtNextEvent();
5125 if (other_events != NULL)
5126 {
5127 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005128 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005129 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005130
Jim Ingham1460e4b2014-01-10 23:46:59 +00005131 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5132 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5133 // event coalescing to cause us to lose OUR running event...
5134 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005135
Jim Ingham8559a352012-11-26 23:52:18 +00005136 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5137 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005138
5139#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5140 // It's pretty much impossible to write test cases for things like:
5141 // One thread timeout expires, I go to halt, but the process already stopped
5142 // on the function call stop breakpoint. Turning on this define will make us not
5143 // fetch the first event till after the halt. So if you run a quick function, it will have
5144 // completed, and the completion event will be waiting, when you interrupt for halt.
5145 // The expression evaluation should still succeed.
5146 bool miss_first_event = true;
5147#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005148 TimeValue one_thread_timeout;
5149 TimeValue final_timeout;
5150
Jim Ingham35878c42014-04-08 21:33:21 +00005151
Sean Callanana46ec452012-07-11 21:31:24 +00005152 while (1)
5153 {
5154 // We usually want to resume the process if we get to the top of the loop.
5155 // The only exception is if we get two running events with no intervening
5156 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005157 if (log)
5158 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5159 do_resume,
5160 handle_running_event,
5161 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005162
Jim Ingham184e9812013-01-15 02:47:48 +00005163 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005164 {
5165 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005166
Jim Ingham184e9812013-01-15 02:47:48 +00005167 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005168 {
Jim Ingham0161b492013-02-09 01:29:05 +00005169 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005170 Error resume_error = PrivateResume ();
5171 if (!resume_error.Success())
5172 {
Jim Ingham0161b492013-02-09 01:29:05 +00005173 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5174 num_resumes,
5175 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005176 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005177 break;
5178 }
Sean Callanana46ec452012-07-11 21:31:24 +00005179 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005180
Jim Ingham0161b492013-02-09 01:29:05 +00005181 TimeValue resume_timeout = TimeValue::Now();
5182 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005183
Jim Ingham0161b492013-02-09 01:29:05 +00005184 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005185 if (!got_event)
5186 {
5187 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005188 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5189 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005190
Jim Ingham0161b492013-02-09 01:29:05 +00005191 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005192 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005193 break;
5194 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005195
Sean Callanana46ec452012-07-11 21:31:24 +00005196 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005197
Sean Callanana46ec452012-07-11 21:31:24 +00005198 if (stop_state != eStateRunning)
5199 {
Jim Ingham0161b492013-02-09 01:29:05 +00005200 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005201
Jim Ingham0161b492013-02-09 01:29:05 +00005202 if (stop_state == eStateStopped)
5203 {
5204 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5205 if (log)
5206 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5207 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5208 num_resumes,
5209 StateAsCString(stop_state),
5210 restarted,
5211 do_resume,
5212 handle_running_event);
5213 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005214
Jim Ingham0161b492013-02-09 01:29:05 +00005215 if (restarted)
5216 {
5217 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5218 // event here. But if I do, the best thing is to Halt and then get out of here.
5219 Halt();
5220 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005221
Jim Ingham35e1bda2012-10-16 21:41:58 +00005222 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5223 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005224 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005225 break;
5226 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005227
Sean Callanana46ec452012-07-11 21:31:24 +00005228 if (log)
5229 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5230 // We need to call the function synchronously, so spin waiting for it to return.
5231 // If we get interrupted while executing, we're going to lose our context, and
5232 // won't be able to gather the result at this point.
5233 // We set the timeout AFTER the resume, since the resume takes some time and we
5234 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005235 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005236 else
5237 {
Sean Callanana46ec452012-07-11 21:31:24 +00005238 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005239 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005240 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005241
Jim Ingham0161b492013-02-09 01:29:05 +00005242 if (before_first_timeout)
5243 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005244 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005245 {
5246 one_thread_timeout = TimeValue::Now();
5247 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005248 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005249 }
Jim Ingham0161b492013-02-09 01:29:05 +00005250 else
5251 {
5252 if (timeout_usec == 0)
5253 timeout_ptr = NULL;
5254 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005255 {
5256 final_timeout = TimeValue::Now();
5257 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005258 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005259 }
Jim Ingham0161b492013-02-09 01:29:05 +00005260 }
5261 }
5262 else
5263 {
5264 if (timeout_usec == 0)
5265 timeout_ptr = NULL;
5266 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005267 {
5268 final_timeout = TimeValue::Now();
5269 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005270 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005271 }
Jim Ingham0161b492013-02-09 01:29:05 +00005272 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005273
Jim Ingham0161b492013-02-09 01:29:05 +00005274 do_resume = true;
5275 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005276
Sean Callanana46ec452012-07-11 21:31:24 +00005277 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005278 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005279
Jim Ingham0f16e732011-02-08 05:20:59 +00005280 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005281 {
Sean Callanana46ec452012-07-11 21:31:24 +00005282 if (timeout_ptr)
5283 {
Matt Kopec676a4872013-02-21 23:55:31 +00005284 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005285 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5286 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005287 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005288 else
Sean Callanana46ec452012-07-11 21:31:24 +00005289 {
5290 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5291 }
5292 }
Jim Ingham35878c42014-04-08 21:33:21 +00005293
5294#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5295 // See comment above...
5296 if (miss_first_event)
5297 {
5298 usleep(1000);
5299 miss_first_event = false;
5300 got_event = false;
5301 }
5302 else
5303#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005304 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005305
Sean Callanana46ec452012-07-11 21:31:24 +00005306 if (got_event)
5307 {
5308 if (event_sp.get())
5309 {
5310 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005311 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005312 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005313 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005314 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005315 errors.Printf ("Execution halted by user interrupt.");
5316 if (log)
5317 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005318 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005319 }
5320 else
5321 {
5322 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5323 if (log)
5324 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005325
Jim Inghamcfc09352012-07-27 23:57:19 +00005326 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005327 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005328 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005329 {
Jim Ingham0161b492013-02-09 01:29:05 +00005330 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005331 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5332 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005333 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005334 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005335 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005336 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005337 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005338 }
5339 else
5340 {
Jim Ingham0161b492013-02-09 01:29:05 +00005341 // If we were restarted, we just need to go back up to fetch another event.
5342 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005343 {
5344 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005345 {
5346 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5347 }
5348 keep_going = true;
5349 do_resume = false;
5350 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005351
Jim Inghamcfc09352012-07-27 23:57:19 +00005352 }
5353 else
5354 {
Jim Ingham0161b492013-02-09 01:29:05 +00005355 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5356 StopReason stop_reason = eStopReasonInvalid;
5357 if (stop_info_sp)
5358 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005359
Jim Ingham0161b492013-02-09 01:29:05 +00005360 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5361 // it is OUR plan that is complete?
5362 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005363 {
5364 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005365 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5366 // Now mark this plan as private so it doesn't get reported as the stop reason
5367 // after this point.
5368 if (thread_plan_sp)
5369 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005370 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005371 }
5372 else
5373 {
Jim Ingham0161b492013-02-09 01:29:05 +00005374 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005375 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005376 {
5377 if (log)
5378 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005379 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005380 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005381 {
5382 event_to_broadcast_sp = event_sp;
5383 }
Jim Ingham0161b492013-02-09 01:29:05 +00005384 }
Jim Ingham184e9812013-01-15 02:47:48 +00005385 else
Jim Ingham0161b492013-02-09 01:29:05 +00005386 {
5387 if (log)
5388 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005389 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005390 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005391 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005392 }
Jim Ingham184e9812013-01-15 02:47:48 +00005393 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005394 }
Sean Callanana46ec452012-07-11 21:31:24 +00005395 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005396 }
5397 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005398
Jim Inghamcfc09352012-07-27 23:57:19 +00005399 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005400 // This shouldn't really happen, but sometimes we do get two running events without an
5401 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005402 do_resume = false;
5403 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005404 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005405 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005406
Jim Inghamcfc09352012-07-27 23:57:19 +00005407 default:
5408 if (log)
5409 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005410
Jim Inghamcfc09352012-07-27 23:57:19 +00005411 if (stop_state == eStateExited)
5412 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005413
Sean Callananbf154da2012-08-08 17:35:10 +00005414 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005415 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005416 break;
5417 }
Sean Callanana46ec452012-07-11 21:31:24 +00005418 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005419
Sean Callanana46ec452012-07-11 21:31:24 +00005420 if (keep_going)
5421 continue;
5422 else
5423 break;
5424 }
5425 else
5426 {
5427 if (log)
5428 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005429 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005430 break;
5431 }
5432 }
5433 else
5434 {
5435 // If we didn't get an event that means we've timed out...
5436 // We will interrupt the process here. Depending on what we were asked to do we will
5437 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005438
Sean Callanana46ec452012-07-11 21:31:24 +00005439 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005440 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005441 {
Jim Ingham0161b492013-02-09 01:29:05 +00005442 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005443 {
5444 if (timeout_usec != 0)
5445 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005446 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005447 "running for %" PRIu32 " usec with all threads enabled.",
5448 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005449 }
5450 else
5451 {
5452 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005453 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005454 }
5455 }
Sean Callanana46ec452012-07-11 21:31:24 +00005456 else
5457 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005458 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005459 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005460 }
5461 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005462 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005463 "abandoning execution.",
5464 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005465 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005466
Jim Ingham0161b492013-02-09 01:29:05 +00005467 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5468 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5469 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5470 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5471 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005472
Jim Ingham0161b492013-02-09 01:29:05 +00005473 bool back_to_top = true;
5474 uint32_t try_halt_again = 0;
5475 bool do_halt = true;
5476 const uint32_t num_retries = 5;
5477 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005478 {
Jim Ingham0161b492013-02-09 01:29:05 +00005479 Error halt_error;
5480 if (do_halt)
5481 {
5482 if (log)
5483 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5484 halt_error = Halt();
5485 }
5486 if (halt_error.Success())
5487 {
5488 if (log)
5489 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005490
Jim Ingham0161b492013-02-09 01:29:05 +00005491 real_timeout = TimeValue::Now();
5492 real_timeout.OffsetWithMicroSeconds(500000);
5493
5494 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005495
Jim Ingham0161b492013-02-09 01:29:05 +00005496 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005497 {
Jim Ingham0161b492013-02-09 01:29:05 +00005498 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5499 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005500 {
Jim Ingham0161b492013-02-09 01:29:05 +00005501 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5502 if (stop_state == lldb::eStateStopped
5503 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5504 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005505 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005506
Jim Ingham0161b492013-02-09 01:29:05 +00005507 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005508 {
Jim Ingham0161b492013-02-09 01:29:05 +00005509 // Between the time we initiated the Halt and the time we delivered it, the process could have
5510 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005511
Jim Ingham0161b492013-02-09 01:29:05 +00005512 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5513 {
5514 if (log)
5515 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5516 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005517 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005518 back_to_top = false;
5519 break;
5520 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005521
Jim Ingham0161b492013-02-09 01:29:05 +00005522 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5523 {
5524 if (log)
5525 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5526 "Exiting wait loop.");
5527 try_halt_again++;
5528 do_halt = false;
5529 continue;
5530 }
Sean Callanana46ec452012-07-11 21:31:24 +00005531
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005532 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005533 {
5534 if (log)
5535 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005536 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005537 back_to_top = false;
5538 break;
5539 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005540
Jim Ingham0161b492013-02-09 01:29:05 +00005541 if (before_first_timeout)
5542 {
5543 // Set all the other threads to run, and return to the top of the loop, which will continue;
5544 before_first_timeout = false;
5545 thread_plan_sp->SetStopOthers (false);
5546 if (log)
5547 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005548
Jim Ingham0161b492013-02-09 01:29:05 +00005549 back_to_top = true;
5550 break;
5551 }
5552 else
5553 {
5554 // Running all threads failed, so return Interrupted.
5555 if (log)
5556 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005557 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005558 back_to_top = false;
5559 break;
5560 }
Sean Callanana46ec452012-07-11 21:31:24 +00005561 }
5562 }
5563 else
Jim Ingham0161b492013-02-09 01:29:05 +00005564 { if (log)
5565 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5566 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005567 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005568 back_to_top = false;
5569 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005570 }
5571 }
Jim Ingham0161b492013-02-09 01:29:05 +00005572 else
5573 {
5574 try_halt_again++;
5575 continue;
5576 }
Sean Callanana46ec452012-07-11 21:31:24 +00005577 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005578
Jim Ingham0161b492013-02-09 01:29:05 +00005579 if (!back_to_top || try_halt_again > num_retries)
5580 break;
5581 else
5582 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005583 }
Sean Callanana46ec452012-07-11 21:31:24 +00005584 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005585
Sean Callanana46ec452012-07-11 21:31:24 +00005586 // 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 +00005587 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005588 {
5589 StopPrivateStateThread();
5590 Error error;
5591 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005592 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005593 {
5594 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5595 }
5596 m_public_state.SetValueNoLock(old_state);
5597
5598 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005599
Jim Ingham184e9812013-01-15 02:47:48 +00005600 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5601 // could happen:
5602 // 1) The execution successfully completed
5603 // 2) We hit a breakpoint, and ignore_breakpoints was true
5604 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005605 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5606 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005607
Jim Ingham8646d3c2014-05-05 02:47:44 +00005608 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005609 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005610 {
5611 thread_plan_sp->RestoreThreadState();
5612 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005613
Sean Callanana46ec452012-07-11 21:31:24 +00005614 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005615 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005616 {
5617 if (log)
5618 {
5619 StreamString s;
5620 if (event_sp)
5621 event_sp->Dump (&s);
5622 else
5623 {
5624 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5625 }
5626
5627 StreamString ts;
5628
5629 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005630
Sean Callanana46ec452012-07-11 21:31:24 +00005631 do
5632 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005633 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005634 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005635 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005636 break;
5637 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005638 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005639 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005640 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005641 break;
5642 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005643 else
Sean Callanana46ec452012-07-11 21:31:24 +00005644 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005645 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5646
5647 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005648 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005649 event_explanation = "<no event data>";
5650 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005651 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005652
Jim Inghamcfc09352012-07-27 23:57:19 +00005653 Process *process = event_data->GetProcessSP().get();
5654
5655 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005656 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005657 event_explanation = "<no process>";
5658 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005659 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005660
Jim Inghamcfc09352012-07-27 23:57:19 +00005661 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005662
Jim Inghamcfc09352012-07-27 23:57:19 +00005663 uint32_t num_threads = thread_list.GetSize();
5664 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005665
Jim Inghamcfc09352012-07-27 23:57:19 +00005666 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005667
Jim Inghamcfc09352012-07-27 23:57:19 +00005668 for (thread_index = 0;
5669 thread_index < num_threads;
5670 ++thread_index)
5671 {
5672 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005673
Jim Inghamcfc09352012-07-27 23:57:19 +00005674 if (!thread)
5675 {
5676 ts.Printf("<?> ");
5677 continue;
5678 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005679
Daniel Malead01b2952012-11-29 21:49:15 +00005680 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005681 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005682
Jim Inghamcfc09352012-07-27 23:57:19 +00005683 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005684 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005685 else
5686 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005687
Jim Inghamcfc09352012-07-27 23:57:19 +00005688 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5689 if (stop_info_sp)
5690 {
5691 const char *stop_desc = stop_info_sp->GetDescription();
5692 if (stop_desc)
5693 ts.PutCString (stop_desc);
5694 }
5695 ts.Printf(">");
5696 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005697
Jim Inghamcfc09352012-07-27 23:57:19 +00005698 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005699 }
Sean Callanana46ec452012-07-11 21:31:24 +00005700 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005701
Jim Inghamcfc09352012-07-27 23:57:19 +00005702 if (event_explanation)
5703 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005704 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005705 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5706 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005707
Jim Inghame4483cf2013-09-27 01:13:01 +00005708 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005709 {
5710 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005711 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5712 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005713 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5714 thread_plan_sp->SetPrivate (orig_plan_private);
5715 }
5716 else
5717 {
5718 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005719 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5720 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005721 }
5722 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005723 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005724 {
5725 if (log)
5726 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005727
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005728 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005729 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005730 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005731 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005732 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005733 }
5734 else
5735 {
Sean Callanana46ec452012-07-11 21:31:24 +00005736 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005737 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005738 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005739 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005740 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005741 }
5742 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5743 {
5744 if (log)
5745 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005746 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005747 }
5748 else
5749 {
5750 if (log)
5751 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005752 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005753 {
5754 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005755 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005756 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5757 thread_plan_sp->SetPrivate (orig_plan_private);
5758 }
5759 }
5760 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005761
Sean Callanana46ec452012-07-11 21:31:24 +00005762 // Thread we ran the function in may have gone away because we ran the target
5763 // Check that it's still there, and if it is put it back in the context. Also restore the
5764 // frame in the context if it is still present.
5765 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5766 if (thread)
5767 {
5768 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5769 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005770
Sean Callanana46ec452012-07-11 21:31:24 +00005771 // Also restore the current process'es selected frame & thread, since this function calling may
5772 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005773
Sean Callanana46ec452012-07-11 21:31:24 +00005774 if (selected_tid != LLDB_INVALID_THREAD_ID)
5775 {
5776 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5777 {
5778 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005779 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005780 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005781 if (old_frame_sp)
5782 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005783 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005784 }
5785 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005786
Sean Callanana46ec452012-07-11 21:31:24 +00005787 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005788
Sean Callanana46ec452012-07-11 21:31:24 +00005789 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005790 {
Sean Callanana46ec452012-07-11 21:31:24 +00005791 if (log)
5792 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5793 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005794 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005795
Jim Inghamf48169b2010-11-30 02:22:11 +00005796 return return_value;
5797}
5798
5799const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005800Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005801{
5802 const char *result_name;
5803
5804 switch (result)
5805 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005806 case eExpressionCompleted:
5807 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005808 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005809 case eExpressionDiscarded:
5810 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005811 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005812 case eExpressionInterrupted:
5813 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005814 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005815 case eExpressionHitBreakpoint:
5816 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005817 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005818 case eExpressionSetupError:
5819 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005820 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005821 case eExpressionParseError:
5822 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005823 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005824 case eExpressionResultUnavailable:
5825 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005826 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005827 case eExpressionTimedOut:
5828 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005829 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005830 case eExpressionStoppedForDebug:
5831 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005832 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005833 }
5834 return result_name;
5835}
5836
Greg Clayton7260f622011-04-18 08:33:37 +00005837void
5838Process::GetStatus (Stream &strm)
5839{
5840 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005841 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005842 {
5843 if (state == eStateExited)
5844 {
5845 int exit_status = GetExitStatus();
5846 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005847 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005848 GetID(),
5849 exit_status,
5850 exit_status,
5851 exit_description ? exit_description : "");
5852 }
5853 else
5854 {
5855 if (state == eStateConnected)
5856 strm.Printf ("Connected to remote target.\n");
5857 else
Daniel Malead01b2952012-11-29 21:49:15 +00005858 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005859 }
5860 }
5861 else
5862 {
Daniel Malead01b2952012-11-29 21:49:15 +00005863 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005864 }
5865}
5866
5867size_t
5868Process::GetThreadStatus (Stream &strm,
5869 bool only_threads_with_stop_reason,
5870 uint32_t start_frame,
5871 uint32_t num_frames,
5872 uint32_t num_frames_with_source)
5873{
5874 size_t num_thread_infos_dumped = 0;
5875
Jim Ingham4a65fb12014-03-07 11:20:03 +00005876 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5877 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5878 // ID's, and look them up one by one:
5879
5880 uint32_t num_threads;
5881 std::vector<uint32_t> thread_index_array;
5882 //Scope for thread list locker;
5883 {
5884 Mutex::Locker locker (GetThreadList().GetMutex());
5885 ThreadList &curr_thread_list = GetThreadList();
5886 num_threads = curr_thread_list.GetSize();
5887 uint32_t idx;
5888 thread_index_array.resize(num_threads);
5889 for (idx = 0; idx < num_threads; ++idx)
5890 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5891 }
5892
Greg Clayton7260f622011-04-18 08:33:37 +00005893 for (uint32_t i = 0; i < num_threads; i++)
5894 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005895 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5896 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005897 {
5898 if (only_threads_with_stop_reason)
5899 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005900 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005901 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005902 continue;
5903 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005904 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005905 start_frame,
5906 num_frames,
5907 num_frames_with_source);
5908 ++num_thread_infos_dumped;
5909 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005910 else
5911 {
5912 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5913 if (log)
5914 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5915
5916 }
Greg Clayton7260f622011-04-18 08:33:37 +00005917 }
5918 return num_thread_infos_dumped;
5919}
5920
Greg Claytona9f40ad2012-02-22 04:37:26 +00005921void
5922Process::AddInvalidMemoryRegion (const LoadRange &region)
5923{
5924 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5925}
5926
5927bool
5928Process::RemoveInvalidMemoryRange (const LoadRange &region)
5929{
5930 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5931}
5932
Jim Ingham372787f2012-04-07 00:00:41 +00005933void
5934Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5935{
5936 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5937}
5938
5939bool
5940Process::RunPreResumeActions ()
5941{
5942 bool result = true;
5943 while (!m_pre_resume_actions.empty())
5944 {
5945 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5946 m_pre_resume_actions.pop_back();
5947 bool this_result = action.callback (action.baton);
5948 if (result == true) result = this_result;
5949 }
5950 return result;
5951}
5952
5953void
5954Process::ClearPreResumeActions ()
5955{
5956 m_pre_resume_actions.clear();
5957}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005958
Greg Claytonfa559e52012-05-18 02:38:05 +00005959void
5960Process::Flush ()
5961{
5962 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005963 m_extended_thread_list.Flush();
5964 m_extended_thread_stop_id = 0;
5965 m_queue_list.Clear();
5966 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005967}
Greg Clayton90ba8112012-12-05 00:16:59 +00005968
5969void
5970Process::DidExec ()
5971{
Todd Fiala76e0fc92014-08-27 22:58:26 +00005972 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5973 if (log)
5974 log->Printf ("Process::%s()", __FUNCTION__);
5975
Greg Clayton90ba8112012-12-05 00:16:59 +00005976 Target &target = GetTarget();
5977 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005978 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005979 m_dynamic_checkers_ap.reset();
5980 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005981 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005982 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005983 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005984 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005985 m_image_tokens.clear();
5986 m_allocated_memory_cache.Clear();
5987 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00005988 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005989 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005990 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005991 DoDidExec();
5992 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005993 // Flush the process (threads and all stack frames) after running CompleteAttach()
5994 // in case the dynamic loader loaded things in new locations.
5995 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005996
5997 // After we figure out what was loaded/unloaded in CompleteAttach,
5998 // we need to let the target know so it can do any cleanup it needs to.
5999 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006000}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006001
Jim Ingham1460e4b2014-01-10 23:46:59 +00006002addr_t
6003Process::ResolveIndirectFunction(const Address *address, Error &error)
6004{
6005 if (address == nullptr)
6006 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006007 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006008 return LLDB_INVALID_ADDRESS;
6009 }
6010
6011 addr_t function_addr = LLDB_INVALID_ADDRESS;
6012
6013 addr_t addr = address->GetLoadAddress(&GetTarget());
6014 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6015 if (iter != m_resolved_indirect_addresses.end())
6016 {
6017 function_addr = (*iter).second;
6018 }
6019 else
6020 {
6021 if (!InferiorCall(this, address, function_addr))
6022 {
6023 Symbol *symbol = address->CalculateSymbolContextSymbol();
6024 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6025 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6026 function_addr = LLDB_INVALID_ADDRESS;
6027 }
6028 else
6029 {
6030 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6031 }
6032 }
6033 return function_addr;
6034}
6035
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006036void
6037Process::ModulesDidLoad (ModuleList &module_list)
6038{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006039 SystemRuntime *sys_runtime = GetSystemRuntime();
6040 if (sys_runtime)
6041 {
6042 sys_runtime->ModulesDidLoad (module_list);
6043 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006044
Kuba Breckaafdf8422014-10-10 23:43:03 +00006045 GetJITLoaders().ModulesDidLoad (module_list);
6046
6047 // Give runtimes a chance to be created.
6048 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6049
6050 // Tell runtimes about new modules.
6051 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6052 {
6053 InstrumentationRuntimeSP runtime = pos->second;
6054 runtime->ModulesDidLoad(module_list);
6055 }
6056
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006057}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006058
6059ThreadCollectionSP
6060Process::GetHistoryThreads(lldb::addr_t addr)
6061{
6062 ThreadCollectionSP threads;
6063
6064 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6065
6066 if (! memory_history.get()) {
6067 return threads;
6068 }
6069
6070 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6071
6072 return threads;
6073}