blob: 81ed8b540bd6322b8364cb5e9f1b51321c347483 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:241//===-- 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
Chris Lattner30fdc8d2010-06-08 16:52:2410#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:2411#include "lldb/Breakpoint/StoppointCallbackContext.h"
12#include "lldb/Breakpoint/BreakpointLocation.h"
13#include "lldb/Core/Event.h"
Chris Lattner30fdc8d2010-06-08 16:52:2414#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:2415#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:0616#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:2317#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:2418#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:2420#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:3521#include "lldb/Expression/ClangUserExpression.h"
Zachary Turner93749ab2015-03-03 21:51:2522#include "lldb/Expression/IRDynamicChecks.h"
Zachary Turner93a66fc2014-10-06 21:22:3623#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:2424#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:5625#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:3926#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:2427#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:5628#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:3629#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:0130#include "lldb/Interpreter/OptionValueProperties.h"
Zachary Turner93a66fc2014-10-06 21:22:3631#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:2432#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:2933#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:2534#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:4335#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:2536#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:1337#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:2538#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:3939#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:1940#include "lldb/Target/LanguageRuntime.h"
41#include "lldb/Target/CPPLanguageRuntime.h"
42#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:1543#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:2444#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:3545#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:1946#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:2447#include "lldb/Target/Target.h"
48#include "lldb/Target/TargetList.h"
49#include "lldb/Target/Thread.h"
50#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:5751#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:2552#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:4553#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:5954#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:2455
Chris Lattner30fdc8d2010-06-08 16:52:2456using namespace lldb;
57using namespace lldb_private;
58
Greg Clayton67cc0632012-08-22 17:17:0959
60// Comment out line below to disable memory caching, overriding the process setting
61// target.process.disable-memory-cache
62#define ENABLE_MEMORY_CACHING
63
64#ifdef ENABLE_MEMORY_CACHING
65#define DISABLE_MEM_CACHE_DEFAULT false
66#else
67#define DISABLE_MEM_CACHE_DEFAULT true
68#endif
69
70class ProcessOptionValueProperties : public OptionValueProperties
71{
72public:
73 ProcessOptionValueProperties (const ConstString &name) :
74 OptionValueProperties (name)
75 {
76 }
77
78 // This constructor is used when creating ProcessOptionValueProperties when it
79 // is part of a new lldb_private::Process instance. It will copy all current
80 // global property values as needed
81 ProcessOptionValueProperties (ProcessProperties *global_properties) :
82 OptionValueProperties(*global_properties->GetValueProperties())
83 {
84 }
85
86 virtual const Property *
87 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
88 {
Bruce Mitchenerd93c4a32014-07-01 21:22:1189 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:0990 // try and grab the setting from the current process if there is one. Else we just
91 // use the one from this instance.
92 if (exe_ctx)
93 {
94 Process *process = exe_ctx->GetProcessPtr();
95 if (process)
96 {
97 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
98 if (this != instance_properties)
99 return instance_properties->ProtectedGetPropertyAtIndex (idx);
100 }
101 }
102 return ProtectedGetPropertyAtIndex (idx);
103 }
104};
105
106static PropertyDefinition
107g_properties[] =
108{
109 { "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:12110 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
111 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57112 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
113 { "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:47114 { "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:28115 { "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:30116 { "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:54117 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Greg Clayton67cc0632012-08-22 17:17:09118 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
119};
120
121enum {
122 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37123 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48124 ePropertyIgnoreBreakpointsInExpressions,
125 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28126 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30127 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54128 ePropertyDetachKeepsStopped,
129 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09130};
131
Greg Clayton332e8b12015-01-13 21:13:08132ProcessProperties::ProcessProperties (lldb_private::Process *process) :
133 Properties (),
134 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09135{
Greg Clayton332e8b12015-01-13 21:13:08136 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09137 {
Greg Clayton332e8b12015-01-13 21:13:08138 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09139 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
140 m_collection_sp->Initialize(g_properties);
141 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28142 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09143 true,
144 Thread::GetGlobalProperties()->GetValueProperties());
145 }
146 else
Greg Clayton332e8b12015-01-13 21:13:08147 {
Greg Clayton67cc0632012-08-22 17:17:09148 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08149 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
150 }
Greg Clayton67cc0632012-08-22 17:17:09151}
152
153ProcessProperties::~ProcessProperties()
154{
155}
156
Greg Clayton332e8b12015-01-13 21:13:08157void
158ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
159{
160 ProcessProperties *properties = (ProcessProperties *)baton;
161 if (properties->m_process)
162 properties->m_process->LoadOperatingSystemPlugin(true);
163}
164
Greg Clayton67cc0632012-08-22 17:17:09165bool
166ProcessProperties::GetDisableMemoryCache() const
167{
168 const uint32_t idx = ePropertyDisableMemCache;
169 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
170}
171
Jason Molendaf0340c92014-09-03 22:30:54172uint64_t
173ProcessProperties::GetMemoryCacheLineSize() const
174{
175 const uint32_t idx = ePropertyMemCacheLineSize;
176 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
177}
178
Greg Clayton67cc0632012-08-22 17:17:09179Args
180ProcessProperties::GetExtraStartupCommands () const
181{
182 Args args;
183 const uint32_t idx = ePropertyExtraStartCommand;
184 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
185 return args;
186}
187
188void
189ProcessProperties::SetExtraStartupCommands (const Args &args)
190{
191 const uint32_t idx = ePropertyExtraStartCommand;
192 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
193}
194
Greg Claytonc9d645d2012-10-18 22:40:37195FileSpec
196ProcessProperties::GetPythonOSPluginPath () const
197{
198 const uint32_t idx = ePropertyPythonOSPluginPath;
199 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
200}
201
202void
203ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
204{
205 const uint32_t idx = ePropertyPythonOSPluginPath;
206 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
207}
208
Jim Ingham184e9812013-01-15 02:47:48209
210bool
211ProcessProperties::GetIgnoreBreakpointsInExpressions () const
212{
213 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
214 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
215}
216
217void
218ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
219{
220 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
221 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
222}
223
224bool
225ProcessProperties::GetUnwindOnErrorInExpressions () const
226{
227 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
228 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
229}
230
231void
232ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
233{
234 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
235 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
236}
237
Jim Ingham29950772013-01-26 02:19:28238bool
239ProcessProperties::GetStopOnSharedLibraryEvents () const
240{
241 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
243}
244
245void
246ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
247{
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
249 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
250}
251
Jim Inghamacff8952013-05-02 00:27:30252bool
253ProcessProperties::GetDetachKeepsStopped () const
254{
255 const uint32_t idx = ePropertyDetachKeepsStopped;
256 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
257}
258
259void
260ProcessProperties::SetDetachKeepsStopped (bool stop)
261{
262 const uint32_t idx = ePropertyDetachKeepsStopped;
263 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
264}
265
Greg Clayton32e0a752011-03-30 18:16:51266void
Greg Clayton8b82f082011-04-12 05:54:46267ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51268{
269 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43270 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15271 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43272
273 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15274 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43275
276 if (m_executable)
277 {
278 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
279 s.PutCString (" file = ");
280 m_executable.Dump(&s);
281 s.EOL();
282 }
Greg Clayton8b82f082011-04-12 05:54:46283 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43284 if (argc > 0)
285 {
286 for (uint32_t i=0; i<argc; i++)
287 {
Greg Clayton8b82f082011-04-12 05:54:46288 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43289 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46290 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43291 else
Greg Clayton8b82f082011-04-12 05:54:46292 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43293 }
294 }
Greg Clayton8b82f082011-04-12 05:54:46295
296 const uint32_t envc = m_environment.GetArgumentCount();
297 if (envc > 0)
298 {
299 for (uint32_t i=0; i<envc; i++)
300 {
301 const char *env = m_environment.GetArgumentAtIndex(i);
302 if (i < 10)
303 s.Printf (" env[%u] = %s\n", i, env);
304 else
305 s.Printf ("env[%u] = %s\n", i, env);
306 }
307 }
308
Greg Clayton95bf0fd2011-04-01 00:29:43309 if (m_arch.IsValid())
310 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
311
Greg Clayton8b82f082011-04-12 05:54:46312 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51313 {
Greg Clayton8b82f082011-04-12 05:54:46314 cstr = platform->GetUserName (m_uid);
315 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51316 }
Greg Clayton8b82f082011-04-12 05:54:46317 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51318 {
Greg Clayton8b82f082011-04-12 05:54:46319 cstr = platform->GetGroupName (m_gid);
320 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51321 }
Greg Clayton8b82f082011-04-12 05:54:46322 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51323 {
Greg Clayton8b82f082011-04-12 05:54:46324 cstr = platform->GetUserName (m_euid);
325 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51326 }
Greg Clayton8b82f082011-04-12 05:54:46327 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51328 {
Greg Clayton8b82f082011-04-12 05:54:46329 cstr = platform->GetGroupName (m_egid);
330 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51331 }
332}
333
334void
Greg Clayton8b82f082011-04-12 05:54:46335ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51336{
Greg Clayton8b82f082011-04-12 05:54:46337 const char *label;
338 if (show_args || verbose)
339 label = "ARGUMENTS";
340 else
341 label = "NAME";
342
Greg Clayton95bf0fd2011-04-01 00:29:43343 if (verbose)
344 {
Greg Clayton8b82f082011-04-12 05:54:46345 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43346 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
347 }
348 else
349 {
Jim Ingham368ac222014-08-15 17:05:27350 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
351 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43352 }
Greg Clayton32e0a752011-03-30 18:16:51353}
354
355void
Greg Clayton8b82f082011-04-12 05:54:46356ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51357{
358 if (m_pid != LLDB_INVALID_PROCESS_ID)
359 {
360 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15361 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51362
Greg Clayton32e0a752011-03-30 18:16:51363
Greg Clayton95bf0fd2011-04-01 00:29:43364 if (verbose)
365 {
Greg Clayton8b82f082011-04-12 05:54:46366 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43367 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
368 s.Printf ("%-10s ", cstr);
369 else
Greg Clayton8b82f082011-04-12 05:54:46370 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51371
Greg Clayton8b82f082011-04-12 05:54:46372 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43373 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
374 s.Printf ("%-10s ", cstr);
375 else
Greg Clayton8b82f082011-04-12 05:54:46376 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51377
Greg Clayton8b82f082011-04-12 05:54:46378 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43379 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
380 s.Printf ("%-10s ", cstr);
381 else
Greg Clayton8b82f082011-04-12 05:54:46382 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43383
Greg Clayton8b82f082011-04-12 05:54:46384 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43385 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
386 s.Printf ("%-10s ", cstr);
387 else
Greg Clayton8b82f082011-04-12 05:54:46388 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43389 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
390 }
391 else
392 {
Jim Ingham368ac222014-08-15 17:05:27393 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46394 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27395 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43396 }
397
Greg Clayton8b82f082011-04-12 05:54:46398 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43399 {
Greg Clayton8b82f082011-04-12 05:54:46400 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43401 if (argc > 0)
402 {
403 for (uint32_t i=0; i<argc; i++)
404 {
405 if (i > 0)
406 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46407 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43408 }
409 }
410 }
411 else
412 {
413 s.PutCString (GetName());
414 }
415
416 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51417 }
418}
419
Greg Clayton8b82f082011-04-12 05:54:46420Error
Greg Claytonf6b8b582011-04-13 00:18:08421ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46422{
423 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51424 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46425
426 switch (short_option)
427 {
428 case 's': // Stop at program entry point
429 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
430 break;
431
Greg Clayton8b82f082011-04-12 05:54:46432 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21433 {
434 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29435 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21436 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46437 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21438 }
Greg Clayton8b82f082011-04-12 05:54:46439
440 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21441 {
442 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29443 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21444 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04445 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21446 }
Greg Clayton9845a8d2012-03-06 04:01:04447
448 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21449 {
450 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29451 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21452 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46453 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21454 }
Greg Clayton9845a8d2012-03-06 04:01:04455
Greg Clayton8b82f082011-04-12 05:54:46456 case 'p': // Process plug-in name
457 launch_info.SetProcessPluginName (option_arg);
458 break;
459
460 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21461 {
462 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29463 const FileSpec dev_null{"/dev/null", false};
464 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21465 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29466 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21467 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29468 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21469 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46470 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21471 }
Greg Clayton8b82f082011-04-12 05:54:46472
473 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29474 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46475 break;
476
477 case 't': // Open process in new terminal window
478 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
479 break;
480
481 case 'a':
Greg Clayton70512312012-05-08 01:45:38482 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
483 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46484 break;
485
Todd Fiala51637922014-08-19 17:40:43486 case 'A': // Disable ASLR.
487 {
488 bool success;
489 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
490 if (success)
491 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
492 else
493 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46494 break;
Todd Fiala51637922014-08-19 17:40:43495 }
496
Enrico Granatab38ef8c2015-02-20 22:20:30497 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24498 {
499 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30500 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24501 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30502 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24503 else
Enrico Granatab38ef8c2015-02-20 22:20:30504 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24505 break;
506 }
507
Todd Fiala51637922014-08-19 17:40:43508 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30509 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43510 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30511 else
Zachary Turner10687b02014-10-20 17:46:43512 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33513 break;
514
Greg Clayton8b82f082011-04-12 05:54:46515 case 'v':
516 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
517 break;
518
519 default:
Greg Clayton86edbf42011-10-26 00:56:27520 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46521 break;
Greg Clayton8b82f082011-04-12 05:54:46522 }
523 return error;
524}
525
526OptionDefinition
527ProcessLaunchCommandOptions::g_option_table[] =
528{
Zachary Turnerd37221d2014-07-09 16:31:49529{ 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:43530{ 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:49531{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
532{ 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."},
533{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
534{ 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."},
Enrico Granatad7a83a92015-02-10 03:06:24535{ LLDB_OPT_SET_1|LLDB_OPT_SET_2|LLDB_OPT_SET_3, 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:46536
Zachary Turnerd37221d2014-07-09 16:31:49537{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
538{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
539{ 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:46540
Zachary Turnerd37221d2014-07-09 16:31:49541{ 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:46542
Zachary Turnerd37221d2014-07-09 16:31:49543{ 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."},
Enrico Granatab38ef8c2015-02-20 22:20:30544{ LLDB_OPT_SET_4, false, "shell-expand-args", 'X', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to shell expand arguments to the process when launching."},
Zachary Turnerd37221d2014-07-09 16:31:49545{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46546};
547
548
549
550bool
551ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51552{
553 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
554 return true;
555 const char *match_name = m_match_info.GetName();
556 if (!match_name)
557 return true;
558
559 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
560}
561
562bool
Greg Clayton8b82f082011-04-12 05:54:46563ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51564{
565 if (!NameMatches (proc_info.GetName()))
566 return false;
567
568 if (m_match_info.ProcessIDIsValid() &&
569 m_match_info.GetProcessID() != proc_info.GetProcessID())
570 return false;
571
572 if (m_match_info.ParentProcessIDIsValid() &&
573 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
574 return false;
575
Greg Clayton8b82f082011-04-12 05:54:46576 if (m_match_info.UserIDIsValid () &&
577 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51578 return false;
579
Greg Clayton8b82f082011-04-12 05:54:46580 if (m_match_info.GroupIDIsValid () &&
581 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51582 return false;
583
584 if (m_match_info.EffectiveUserIDIsValid () &&
585 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
586 return false;
587
588 if (m_match_info.EffectiveGroupIDIsValid () &&
589 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
590 return false;
591
592 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14593 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51594 return false;
595 return true;
596}
597
598bool
Greg Clayton8b82f082011-04-12 05:54:46599ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51600{
601 if (m_name_match_type != eNameMatchIgnore)
602 return false;
603
604 if (m_match_info.ProcessIDIsValid())
605 return false;
606
607 if (m_match_info.ParentProcessIDIsValid())
608 return false;
609
Greg Clayton8b82f082011-04-12 05:54:46610 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51611 return false;
612
Greg Clayton8b82f082011-04-12 05:54:46613 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51614 return false;
615
616 if (m_match_info.EffectiveUserIDIsValid ())
617 return false;
618
619 if (m_match_info.EffectiveGroupIDIsValid ())
620 return false;
621
622 if (m_match_info.GetArchitecture().IsValid())
623 return false;
624
625 if (m_match_all_users)
626 return false;
627
628 return true;
629
630}
631
632void
Greg Clayton8b82f082011-04-12 05:54:46633ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51634{
635 m_match_info.Clear();
636 m_name_match_type = eNameMatchIgnore;
637 m_match_all_users = false;
638}
Greg Clayton58be07b2011-01-07 06:08:19639
Greg Claytonc3776bf2012-02-09 06:16:32640ProcessSP
641Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24642{
Greg Clayton949e8222013-01-16 17:29:04643 static uint32_t g_process_unique_id = 0;
644
Greg Claytonc3776bf2012-02-09 06:16:32645 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24646 ProcessCreateInstance create_callback = NULL;
647 if (plugin_name)
648 {
Greg Clayton57abc5d2013-05-10 21:47:16649 ConstString const_plugin_name(plugin_name);
650 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24651 if (create_callback)
652 {
Greg Claytonc3776bf2012-02-09 06:16:32653 process_sp = create_callback(target, listener, crash_file_path);
654 if (process_sp)
655 {
Greg Clayton949e8222013-01-16 17:29:04656 if (process_sp->CanDebug(target, true))
657 {
658 process_sp->m_process_unique_id = ++g_process_unique_id;
659 }
660 else
Greg Claytonc3776bf2012-02-09 06:16:32661 process_sp.reset();
662 }
Chris Lattner30fdc8d2010-06-08 16:52:24663 }
664 }
665 else
666 {
Greg Claytonc982c762010-07-09 20:39:50667 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24668 {
Greg Claytonc3776bf2012-02-09 06:16:32669 process_sp = create_callback(target, listener, crash_file_path);
670 if (process_sp)
671 {
Greg Clayton949e8222013-01-16 17:29:04672 if (process_sp->CanDebug(target, false))
673 {
674 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32675 break;
Greg Clayton949e8222013-01-16 17:29:04676 }
677 else
678 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32679 }
Chris Lattner30fdc8d2010-06-08 16:52:24680 }
681 }
Greg Claytonc3776bf2012-02-09 06:16:32682 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24683}
684
Jim Ingham4bddaeb2012-02-16 06:50:00685ConstString &
686Process::GetStaticBroadcasterClass ()
687{
688 static ConstString class_name ("lldb.process");
689 return class_name;
690}
Chris Lattner30fdc8d2010-06-08 16:52:24691
692//----------------------------------------------------------------------
693// Process constructor
694//----------------------------------------------------------------------
695Process::Process(Target &target, Listener &listener) :
Chaoren Lin98d0a4b2015-07-14 01:09:28696 Process(target, listener, UnixSignals::Create(HostInfo::GetArchitecture()))
Todd Fiala4ceced32014-08-29 17:35:57697{
698 // This constructor just delegates to the full Process constructor,
699 // defaulting to using the Host's UnixSignals.
700}
701
702Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08703 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24704 UserID (LLDB_INVALID_PROCESS_ID),
Ilia K8a00a562015-03-17 16:54:52705 Broadcaster (&(target.GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
Chris Lattner30fdc8d2010-06-08 16:52:24706 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24707 m_public_state (eStateUnloaded),
708 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00709 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
710 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24711 m_private_state_listener ("lldb.process.internal_state_listener"),
712 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22713 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04714 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24715 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01716 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24717 m_exit_status (-1),
718 m_exit_string (),
Todd Fiala7b0917a02014-09-15 20:07:33719 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34720 m_thread_mutex (Mutex::eMutexTypeRecursive),
721 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24722 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44723 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38724 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16725 m_queue_list (this),
726 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24727 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03728 m_image_tokens (),
729 m_listener (listener),
730 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03731 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57732 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03733 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41734 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35735 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03736 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04737 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19738 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22739 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04740 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
741 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32742 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42743 m_memory_cache (*this),
744 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02745 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51746 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27747 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27748 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30749 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02750 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58751 m_finalizing (false),
752 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10753 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58754 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05755 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59756 m_destroy_in_process (false),
757 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24758{
Jim Ingham4bddaeb2012-02-16 06:50:00759 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10760
Greg Clayton5160ce52013-03-27 23:08:40761 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24762 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10763 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24764
Todd Fiala4ceced32014-08-29 17:35:57765 if (!m_unix_signals_sp)
Chaoren Lin98d0a4b2015-07-14 01:09:28766 m_unix_signals_sp = std::make_shared<UnixSignals>();
Todd Fiala4ceced32014-08-29 17:35:57767
Greg Claytoncfd1ace2010-10-31 03:01:06768 SetEventName (eBroadcastBitStateChanged, "state-changed");
769 SetEventName (eBroadcastBitInterrupt, "interrupt");
770 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
771 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04772 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Chaoren Lin98d0a4b2015-07-14 01:09:28773
Greg Clayton35a4cc52012-10-29 20:52:08774 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
775 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
776 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
777
Chris Lattner30fdc8d2010-06-08 16:52:24778 listener.StartListeningForEvents (this,
779 eBroadcastBitStateChanged |
780 eBroadcastBitInterrupt |
781 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04782 eBroadcastBitSTDERR |
783 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24784
785 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19786 eBroadcastBitStateChanged |
787 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24788
789 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
790 eBroadcastInternalStateControlStop |
791 eBroadcastInternalStateControlPause |
792 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57793 // We need something valid here, even if just the default UnixSignalsSP.
794 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24795}
796
797//----------------------------------------------------------------------
798// Destructor
799//----------------------------------------------------------------------
800Process::~Process()
801{
Greg Clayton5160ce52013-03-27 23:08:40802 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24803 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10804 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24805 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56806
807 // ThreadList::Clear() will try to acquire this process's mutex, so
808 // explicitly clear the thread list here to ensure that the mutex
809 // is not destroyed before the thread list.
810 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24811}
812
Greg Clayton67cc0632012-08-22 17:17:09813const ProcessPropertiesSP &
814Process::GetGlobalProperties()
815{
816 static ProcessPropertiesSP g_settings_sp;
817 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08818 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09819 return g_settings_sp;
820}
821
Chris Lattner30fdc8d2010-06-08 16:52:24822void
823Process::Finalize()
824{
Greg Claytonc00ca312015-04-02 18:44:58825 m_finalizing = true;
826
Ilia Kc7efd562015-03-26 07:40:40827 // Destroy this process if needed
828 switch (GetPrivateState())
829 {
830 case eStateConnected:
831 case eStateAttaching:
832 case eStateLaunching:
833 case eStateStopped:
834 case eStateRunning:
835 case eStateStepping:
836 case eStateCrashed:
837 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58838 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40839 break;
840
841 case eStateInvalid:
842 case eStateUnloaded:
843 case eStateDetached:
844 case eStateExited:
845 break;
846 }
Greg Claytone24c4ac2011-11-17 04:46:02847
Greg Clayton1ed54f52011-10-01 00:45:15848 // Clear our broadcaster before we proceed with destroying
849 Broadcaster::Clear();
850
Chris Lattner30fdc8d2010-06-08 16:52:24851 // Do any cleanup needed prior to being destructed... Subclasses
852 // that override this method should call this superclass method as well.
Jim Inghamd0a3e12b2011-02-16 17:54:55853
854 // We need to destroy the loader before the derived Process class gets destroyed
855 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34856 m_dynamic_checkers_ap.reset();
857 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39858 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19859 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34860 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43861 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34862 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30863 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44864 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16865 m_queue_list.Clear();
866 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34867 std::vector<Notifications> empty_notifications;
868 m_notifications.swap(empty_notifications);
869 m_image_tokens.clear();
870 m_memory_cache.Clear();
871 m_allocated_memory_cache.Clear();
872 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03873 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34874 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02875 m_stop_info_override_callback = NULL;
Greg Clayton08765fa2015-05-28 03:24:30876 // Clear the last natural stop ID since it has a strong
877 // reference to this process
878 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08879//#ifdef LLDB_CONFIGURATION_DEBUG
880// StreamFile s(stdout, false);
881// EventSP event_sp;
882// while (m_private_state_listener.GetNextEvent(event_sp))
883// {
884// event_sp->Dump (&s);
885// s.EOL();
886// }
887//#endif
888 // We have to be very careful here as the m_private_state_listener might
889 // contain events that have ProcessSP values in them which can keep this
890 // process around forever. These events need to be cleared out.
891 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06892 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
893 m_public_run_lock.SetStopped();
894 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
895 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33896 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24897}
898
899void
900Process::RegisterNotificationCallbacks (const Notifications& callbacks)
901{
902 m_notifications.push_back(callbacks);
903 if (callbacks.initialize != NULL)
904 callbacks.initialize (callbacks.baton, this);
905}
906
907bool
908Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
909{
910 std::vector<Notifications>::iterator pos, end = m_notifications.end();
911 for (pos = m_notifications.begin(); pos != end; ++pos)
912 {
913 if (pos->baton == callbacks.baton &&
914 pos->initialize == callbacks.initialize &&
915 pos->process_state_changed == callbacks.process_state_changed)
916 {
917 m_notifications.erase(pos);
918 return true;
919 }
920 }
921 return false;
922}
923
924void
925Process::SynchronouslyNotifyStateChanged (StateType state)
926{
927 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
928 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
929 {
930 if (notification_pos->process_state_changed)
931 notification_pos->process_state_changed (notification_pos->baton, this, state);
932 }
933}
934
935// FIXME: We need to do some work on events before the general Listener sees them.
936// For instance if we are continuing from a breakpoint, we need to ensure that we do
937// the little "insert real insn, step & stop" trick. But we can't do that when the
938// event is delivered by the broadcaster - since that is done on the thread that is
939// waiting for new events, so if we needed more than one event for our handling, we would
940// stall. So instead we do it when we fetch the event off of the queue.
941//
942
943StateType
944Process::GetNextEvent (EventSP &event_sp)
945{
946 StateType state = eStateInvalid;
947
948 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
949 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
950
951 return state;
952}
953
Pavel Labath44464872015-05-27 12:40:32954void
955Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19956{
Todd Fialaa3b89e22014-08-12 14:33:19957 // don't sync (potentially context switch) in case where there is no process IO
Pavel Labath44464872015-05-27 12:40:32958 if (! m_process_input_reader)
959 return;
Todd Fialaa3b89e22014-08-12 14:33:19960
Pavel Labath44464872015-05-27 12:40:32961 TimeValue timeout = TimeValue::Now();
962 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
963 uint32_t new_iohandler_id = 0;
964 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19965
Pavel Labath44464872015-05-27 12:40:32966 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
967 if (log)
968 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, new value is %u", __FUNCTION__, iohandler_id, new_iohandler_id);
Todd Fialaa3b89e22014-08-12 14:33:19969}
Chris Lattner30fdc8d2010-06-08 16:52:24970
971StateType
Greg Claytondc6224e2014-10-21 01:00:42972Process::WaitForProcessToStop (const TimeValue *timeout,
973 EventSP *event_sp_ptr,
974 bool wait_always,
975 Listener *hijack_listener,
976 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24977{
Jim Ingham4b536182011-08-09 02:12:22978 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
979 // We have to actually check each event, and in the case of a stopped event check the restarted flag
980 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37981 if (event_sp_ptr)
982 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22983 StateType state = GetState();
984 // If we are exited or detached, we won't ever get back to any
985 // other valid state...
986 if (state == eStateDetached || state == eStateExited)
987 return state;
988
Daniel Malea9e9919f2013-10-09 16:56:28989 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
990 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10991 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
992 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28993
994 if (!wait_always &&
995 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24996 StateIsStoppedState(GetPrivateState(), true))
997 {
Daniel Malea9e9919f2013-10-09 16:56:28998 if (log)
999 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1000 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:471001 // We need to toggle the run lock as this won't get done in
1002 // SetPublicState() if the process is hijacked.
1003 if (hijack_listener)
1004 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:281005 return state;
1006 }
1007
Jim Ingham4b536182011-08-09 02:12:221008 while (state != eStateInvalid)
1009 {
Greg Clayton85fb1b92012-09-11 02:33:371010 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:241011 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:371012 if (event_sp_ptr && event_sp)
1013 *event_sp_ptr = event_sp;
1014
Greg Claytondc6224e2014-10-21 01:00:421015 bool pop_process_io_handler = hijack_listener != NULL;
1016 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1017
Jim Ingham4b536182011-08-09 02:12:221018 switch (state)
1019 {
1020 case eStateCrashed:
1021 case eStateDetached:
1022 case eStateExited:
1023 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:241024 // We need to toggle the run lock as this won't get done in
1025 // SetPublicState() if the process is hijacked.
1026 if (hijack_listener)
1027 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:221028 return state;
1029 case eStateStopped:
1030 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1031 continue;
1032 else
Greg Clayton44d93782014-01-27 23:43:241033 {
1034 // We need to toggle the run lock as this won't get done in
1035 // SetPublicState() if the process is hijacked.
1036 if (hijack_listener)
1037 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:221038 return state;
Greg Clayton44d93782014-01-27 23:43:241039 }
Jim Ingham4b536182011-08-09 02:12:221040 default:
1041 continue;
1042 }
1043 }
1044 return state;
Chris Lattner30fdc8d2010-06-08 16:52:241045}
1046
Greg Claytondc6224e2014-10-21 01:00:421047bool
1048Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1049 Stream *stream,
1050 bool &pop_process_io_handler)
1051{
1052 const bool handle_pop = pop_process_io_handler == true;
1053
1054 pop_process_io_handler = false;
1055 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1056
1057 if (!process_sp)
1058 return false;
1059
1060 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1061 if (event_state == eStateInvalid)
1062 return false;
1063
1064 switch (event_state)
1065 {
1066 case eStateInvalid:
1067 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:421068 case eStateAttaching:
1069 case eStateLaunching:
1070 case eStateStepping:
1071 case eStateDetached:
1072 {
1073 if (stream)
1074 stream->Printf ("Process %" PRIu64 " %s\n",
1075 process_sp->GetID(),
1076 StateAsCString (event_state));
1077
1078 if (event_state == eStateDetached)
1079 pop_process_io_handler = true;
1080 }
1081 break;
1082
Stephane Sezerf2ef94e2014-12-13 05:23:511083 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:421084 case eStateRunning:
1085 // Don't be chatty when we run...
1086 break;
1087
1088 case eStateExited:
1089 if (stream)
1090 process_sp->GetStatus(*stream);
1091 pop_process_io_handler = true;
1092 break;
1093
1094 case eStateStopped:
1095 case eStateCrashed:
1096 case eStateSuspended:
1097 // Make sure the program hasn't been auto-restarted:
1098 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1099 {
1100 if (stream)
1101 {
1102 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1103 if (num_reasons > 0)
1104 {
1105 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1106 if (num_reasons == 1)
1107 {
1108 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1109 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1110 process_sp->GetID(),
1111 reason ? reason : "<UNKNOWN REASON>");
1112 }
1113 else
1114 {
1115 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1116 process_sp->GetID());
1117
1118
1119 for (size_t i = 0; i < num_reasons; i++)
1120 {
1121 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1122 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1123 }
1124 }
1125 }
1126 }
1127 }
1128 else
1129 {
1130 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1131 {
1132 ThreadList &thread_list = process_sp->GetThreadList();
1133 Mutex::Locker locker (thread_list.GetMutex());
1134
1135 ThreadSP curr_thread (thread_list.GetSelectedThread());
1136 ThreadSP thread;
1137 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1138 if (curr_thread)
1139 curr_thread_stop_reason = curr_thread->GetStopReason();
1140 if (!curr_thread ||
1141 !curr_thread->IsValid() ||
1142 curr_thread_stop_reason == eStopReasonInvalid ||
1143 curr_thread_stop_reason == eStopReasonNone)
1144 {
1145 // Prefer a thread that has just completed its plan over another thread as current thread.
1146 ThreadSP plan_thread;
1147 ThreadSP other_thread;
Jim Inghamce400d92015-07-08 00:06:301148
Greg Claytondc6224e2014-10-21 01:00:421149 const size_t num_threads = thread_list.GetSize();
1150 size_t i;
1151 for (i = 0; i < num_threads; ++i)
1152 {
1153 thread = thread_list.GetThreadAtIndex(i);
1154 StopReason thread_stop_reason = thread->GetStopReason();
1155 switch (thread_stop_reason)
1156 {
1157 case eStopReasonInvalid:
1158 case eStopReasonNone:
1159 break;
1160
Jim Inghamce400d92015-07-08 00:06:301161 case eStopReasonSignal:
1162 {
1163 // Don't select a signal thread if we weren't going to stop at that
1164 // signal. We have to have had another reason for stopping here, and
1165 // the user doesn't want to see this thread.
1166 uint64_t signo = thread->GetStopInfo()->GetValue();
Chaoren Lin98d0a4b2015-07-14 01:09:281167 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
Jim Inghamce400d92015-07-08 00:06:301168 {
1169 if (!other_thread)
1170 other_thread = thread;
1171 }
1172 break;
1173 }
Greg Claytondc6224e2014-10-21 01:00:421174 case eStopReasonTrace:
1175 case eStopReasonBreakpoint:
1176 case eStopReasonWatchpoint:
Greg Claytondc6224e2014-10-21 01:00:421177 case eStopReasonException:
1178 case eStopReasonExec:
1179 case eStopReasonThreadExiting:
1180 case eStopReasonInstrumentation:
1181 if (!other_thread)
1182 other_thread = thread;
1183 break;
1184 case eStopReasonPlanComplete:
1185 if (!plan_thread)
1186 plan_thread = thread;
1187 break;
1188 }
1189 }
1190 if (plan_thread)
1191 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1192 else if (other_thread)
1193 thread_list.SetSelectedThreadByID (other_thread->GetID());
1194 else
1195 {
1196 if (curr_thread && curr_thread->IsValid())
1197 thread = curr_thread;
1198 else
1199 thread = thread_list.GetThreadAtIndex(0);
1200
1201 if (thread)
1202 thread_list.SetSelectedThreadByID (thread->GetID());
1203 }
1204 }
1205 }
1206 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1207 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1208 // have a hard time restarting the process.
1209 if (stream)
1210 {
1211 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1212 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1213 {
1214 const bool only_threads_with_stop_reason = true;
1215 const uint32_t start_frame = 0;
1216 const uint32_t num_frames = 1;
1217 const uint32_t num_frames_with_source = 1;
1218 process_sp->GetStatus(*stream);
1219 process_sp->GetThreadStatus (*stream,
1220 only_threads_with_stop_reason,
1221 start_frame,
1222 num_frames,
1223 num_frames_with_source);
1224 }
1225 else
1226 {
1227 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1228 if (target_idx != UINT32_MAX)
1229 stream->Printf ("Target %d: (", target_idx);
1230 else
1231 stream->Printf ("Target <unknown index>: (");
1232 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1233 stream->Printf (") stopped.\n");
1234 }
1235 }
1236
1237 // Pop the process IO handler
1238 pop_process_io_handler = true;
1239 }
1240 break;
1241 }
1242
1243 if (handle_pop && pop_process_io_handler)
1244 process_sp->PopProcessIOHandler();
1245
1246 return true;
1247}
1248
Chris Lattner30fdc8d2010-06-08 16:52:241249
1250StateType
1251Process::WaitForState
1252(
1253 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:241254 const StateType *match_states,
1255 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:241256)
1257{
1258 EventSP event_sp;
1259 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:011260 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:241261 while (state != eStateInvalid)
1262 {
Greg Clayton05faeb72010-10-07 04:19:011263 // If we are exited or detached, we won't ever get back to any
1264 // other valid state...
1265 if (state == eStateDetached || state == eStateExited)
1266 return state;
1267
Greg Clayton44d93782014-01-27 23:43:241268 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:241269
1270 for (i=0; i<num_match_states; ++i)
1271 {
1272 if (match_states[i] == state)
1273 return state;
1274 }
1275 }
1276 return state;
1277}
1278
Jim Ingham30f9b212010-10-11 23:53:141279bool
1280Process::HijackProcessEvents (Listener *listener)
1281{
1282 if (listener != NULL)
1283 {
Jim Inghamcfc09352012-07-27 23:57:191284 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:141285 }
1286 else
1287 return false;
1288}
1289
1290void
1291Process::RestoreProcessEvents ()
1292{
1293 RestoreBroadcaster();
1294}
1295
Jim Ingham0f16e732011-02-08 05:20:591296bool
1297Process::HijackPrivateProcessEvents (Listener *listener)
1298{
1299 if (listener != NULL)
1300 {
Jim Inghamcfc09352012-07-27 23:57:191301 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:591302 }
1303 else
1304 return false;
1305}
1306
1307void
1308Process::RestorePrivateProcessEvents ()
1309{
1310 m_private_state_broadcaster.RestoreBroadcaster();
1311}
1312
Chris Lattner30fdc8d2010-06-08 16:52:241313StateType
Greg Clayton44d93782014-01-27 23:43:241314Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:241315{
Greg Clayton5160ce52013-03-27 23:08:401316 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:241317
1318 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:101319 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1320 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:241321
Greg Clayton44d93782014-01-27 23:43:241322 Listener *listener = hijack_listener;
1323 if (listener == NULL)
1324 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:101325
Chris Lattner30fdc8d2010-06-08 16:52:241326 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:241327 if (listener->WaitForEventForBroadcasterWithType (timeout,
1328 this,
1329 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1330 event_sp))
Jim Inghamcfc09352012-07-27 23:57:191331 {
1332 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1333 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1334 else if (log)
1335 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1336 }
Chris Lattner30fdc8d2010-06-08 16:52:241337
1338 if (log)
1339 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:101340 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:241341 StateAsCString(state));
1342 return state;
1343}
1344
1345Event *
1346Process::PeekAtStateChangedEvents ()
1347{
Greg Clayton5160ce52013-03-27 23:08:401348 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:241349
1350 if (log)
1351 log->Printf ("Process::%s...", __FUNCTION__);
1352
1353 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:401354 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1355 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:241356 if (log)
1357 {
1358 if (event_ptr)
1359 {
1360 log->Printf ("Process::%s (event_ptr) => %s",
1361 __FUNCTION__,
1362 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1363 }
1364 else
1365 {
1366 log->Printf ("Process::%s no events found",
1367 __FUNCTION__);
1368 }
1369 }
1370 return event_ptr;
1371}
1372
1373StateType
1374Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1375{
Greg Clayton5160ce52013-03-27 23:08:401376 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:241377
1378 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:101379 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1380 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:241381
1382 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:181383 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1384 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:191385 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:181386 event_sp))
Jim Inghamcfc09352012-07-27 23:57:191387 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1388 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:241389
1390 // This is a bit of a hack, but when we wait here we could very well return
1391 // to the command-line, and that could disable the log, which would render the
1392 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:241393 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:101394 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1395 __FUNCTION__, static_cast<const void *>(timeout),
1396 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:241397 return state;
1398}
1399
1400bool
1401Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1402{
Greg Clayton5160ce52013-03-27 23:08:401403 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:241404
1405 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:101406 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1407 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:241408
1409 if (control_only)
1410 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1411 else
1412 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1413}
1414
1415bool
1416Process::IsRunning () const
1417{
1418 return StateIsRunningState (m_public_state.GetValue());
1419}
1420
1421int
1422Process::GetExitStatus ()
1423{
Todd Fiala7b0917a02014-09-15 20:07:331424 Mutex::Locker locker (m_exit_status_mutex);
1425
Chris Lattner30fdc8d2010-06-08 16:52:241426 if (m_public_state.GetValue() == eStateExited)
1427 return m_exit_status;
1428 return -1;
1429}
1430
Greg Clayton85851dd2010-12-04 00:10:171431
Chris Lattner30fdc8d2010-06-08 16:52:241432const char *
1433Process::GetExitDescription ()
1434{
Todd Fiala7b0917a02014-09-15 20:07:331435 Mutex::Locker locker (m_exit_status_mutex);
1436
Chris Lattner30fdc8d2010-06-08 16:52:241437 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1438 return m_exit_string.c_str();
1439 return NULL;
1440}
1441
Greg Clayton6779606a2011-01-22 23:43:181442bool
Chris Lattner30fdc8d2010-06-08 16:52:241443Process::SetExitStatus (int status, const char *cstr)
1444{
Greg Clayton81e2b6b2015-06-01 23:14:091445 // Use a mutex to protect setting the exit status.
1446 Mutex::Locker locker (m_exit_status_mutex);
1447
Greg Clayton5160ce52013-03-27 23:08:401448 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:481449 if (log)
1450 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1451 status, status,
1452 cstr ? "\"" : "",
1453 cstr ? cstr : "NULL",
1454 cstr ? "\"" : "");
1455
Greg Clayton6779606a2011-01-22 23:43:181456 // We were already in the exited state
1457 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:481458 {
Greg Clayton385d6032011-01-26 23:47:291459 if (log)
1460 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:181461 return false;
Greg Clayton414f5d32011-01-25 02:58:481462 }
Todd Fiala7b0917a02014-09-15 20:07:331463
Greg Clayton81e2b6b2015-06-01 23:14:091464 m_exit_status = status;
1465 if (cstr)
1466 m_exit_string = cstr;
1467 else
1468 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:241469
Greg Clayton5df78fa2015-05-23 03:54:531470 // When we exit, we no longer need to the communication channel
Greg Clayton5df78fa2015-05-23 03:54:531471 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:011472 m_stdio_communication.StopReadThread();
Greg Clayton5df78fa2015-05-23 03:54:531473 m_stdin_forward = false;
1474
1475 // And we don't need the input reader anymore as well
1476 if (m_process_input_reader)
1477 {
1478 m_process_input_reader->SetIsDone(true);
1479 m_process_input_reader->Cancel();
1480 m_process_input_reader.reset();
1481 }
Greg Clayton10177aa2010-12-08 05:08:211482
Greg Clayton08765fa2015-05-28 03:24:301483 // Clear the last natural stop ID since it has a strong
1484 // reference to this process
1485 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1486
Greg Clayton6779606a2011-01-22 23:43:181487 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:531488
1489 // Allow subclasses to do some cleanup
1490 DidExit ();
1491
Greg Clayton6779606a2011-01-22 23:43:181492 return true;
Chris Lattner30fdc8d2010-06-08 16:52:241493}
1494
1495// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:111496// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:241497// found in the global target list (we want to be completely sure that the
1498// lldb_private::Process doesn't go away before we can deliver the signal.
1499bool
Greg Claytone4e45922011-11-16 05:37:561500Process::SetProcessExitStatus (void *callback_baton,
1501 lldb::pid_t pid,
1502 bool exited,
1503 int signo, // Zero for no signal
1504 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:241505)
1506{
Greg Clayton5160ce52013-03-27 23:08:401507 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:561508 if (log)
Daniel Malead01b2952012-11-29 21:49:151509 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:561510 callback_baton,
1511 pid,
1512 exited,
1513 signo,
1514 exit_status);
1515
1516 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:241517 {
Greg Clayton66111032010-06-23 01:19:291518 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:241519 if (target_sp)
1520 {
1521 ProcessSP process_sp (target_sp->GetProcessSP());
1522 if (process_sp)
1523 {
1524 const char *signal_cstr = NULL;
1525 if (signo)
Chaoren Lin98d0a4b2015-07-14 01:09:281526 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
Chris Lattner30fdc8d2010-06-08 16:52:241527
1528 process_sp->SetExitStatus (exit_status, signal_cstr);
1529 }
1530 }
1531 return true;
1532 }
1533 return false;
1534}
1535
1536
Greg Clayton56d9a1b2011-08-22 02:49:391537void
1538Process::UpdateThreadListIfNeeded ()
1539{
1540 const uint32_t stop_id = GetStopID();
1541 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1542 {
Greg Clayton2637f822011-11-17 01:23:071543 const StateType state = GetPrivateState();
1544 if (StateIsStoppedState (state, true))
1545 {
1546 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:021547 // m_thread_list does have its own mutex, but we need to
1548 // hold onto the mutex between the call to UpdateThreadList(...)
1549 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:341550 ThreadList &old_thread_list = m_thread_list;
1551 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:071552 ThreadList new_thread_list(this);
1553 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:591554 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:341555 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:591556 {
Jim Ingham09437922013-03-01 20:04:251557 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1558 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1559 // shutting us down, causing a deadlock.
1560 if (!m_destroy_in_process)
1561 {
1562 OperatingSystem *os = GetOperatingSystem ();
1563 if (os)
Greg Claytonb3ae8762013-04-12 20:07:461564 {
1565 // Clear any old backing threads where memory threads might have been
1566 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:341567 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:461568 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:341569 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:461570
Greg Clayton15484402015-05-15 18:40:241571 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1572 // can run an expression to determine if a SBValue is a dynamic type or not
1573 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1574 // that require running code...
1575
1576 Target &target = GetTarget();
1577 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1578 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1579 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1580
Greg Claytonb3ae8762013-04-12 20:07:461581 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:241582
Andrew Kaylorba4e61d2013-05-07 18:35:341583 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1584 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1585 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Clayton15484402015-05-15 18:40:241586
1587 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1588 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:461589 }
Andrew Kaylorba4e61d2013-05-07 18:35:341590 else
1591 {
1592 // No OS plug-in, the new thread list is the same as the real thread list
1593 new_thread_list = real_thread_list;
1594 }
Jim Ingham09437922013-03-01 20:04:251595 }
Jim Ingham02ff8e02013-06-22 00:55:021596
1597 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:341598 m_thread_list.Update (new_thread_list);
1599 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:411600
Jason Molenda4ff13262013-11-20 00:31:381601 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1602 {
1603 // Clear any extended threads that we may have accumulated previously
1604 m_extended_thread_list.Clear();
1605 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:161606
1607 m_queue_list.Clear();
1608 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:381609 }
Greg Clayton9fc13552012-04-10 00:18:591610 }
Greg Clayton2637f822011-11-17 01:23:071611 }
Greg Clayton56d9a1b2011-08-22 02:49:391612 }
1613}
1614
Jason Molenda5e8dce42013-12-13 00:29:161615void
1616Process::UpdateQueueListIfNeeded ()
1617{
1618 if (m_system_runtime_ap.get())
1619 {
1620 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1621 {
1622 const StateType state = GetPrivateState();
1623 if (StateIsStoppedState (state, true))
1624 {
1625 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1626 m_queue_list_stop_id = GetLastNaturalStopID();
1627 }
1628 }
1629 }
1630}
1631
Greg Claytona4d87472013-01-18 23:41:081632ThreadSP
1633Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1634{
1635 OperatingSystem *os = GetOperatingSystem ();
1636 if (os)
1637 return os->CreateThread(tid, context);
1638 return ThreadSP();
1639}
1640
Han Ming Ongc2c423e2013-01-08 22:10:011641uint32_t
1642Process::GetNextThreadIndexID (uint64_t thread_id)
1643{
1644 return AssignIndexIDToThread(thread_id);
1645}
1646
1647bool
1648Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1649{
1650 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1651 if (iterator == m_thread_id_to_index_id_map.end())
1652 {
1653 return false;
1654 }
1655 else
1656 {
1657 return true;
1658 }
1659}
1660
1661uint32_t
1662Process::AssignIndexIDToThread(uint64_t thread_id)
1663{
1664 uint32_t result = 0;
1665 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1666 if (iterator == m_thread_id_to_index_id_map.end())
1667 {
1668 result = ++m_thread_index_id;
1669 m_thread_id_to_index_id_map[thread_id] = result;
1670 }
1671 else
1672 {
1673 result = iterator->second;
1674 }
1675
1676 return result;
1677}
1678
Chris Lattner30fdc8d2010-06-08 16:52:241679StateType
1680Process::GetState()
1681{
1682 // If any other threads access this we will need a mutex for it
1683 return m_public_state.GetValue ();
1684}
1685
Greg Claytondc6224e2014-10-21 01:00:421686bool
1687Process::StateChangedIsExternallyHijacked()
1688{
1689 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1690 {
1691 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1692 return true;
1693 }
1694 return false;
1695}
1696
Chris Lattner30fdc8d2010-06-08 16:52:241697void
Jim Ingham221d51c2013-05-08 00:35:161698Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:241699{
Greg Clayton5160ce52013-03-27 23:08:401700 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:241701 if (log)
Jim Ingham221d51c2013-05-08 00:35:161702 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:351703 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:241704 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:331705
1706 // On the transition from Run to Stopped, we unlock the writer end of the
1707 // run lock. The lock gets locked in Resume, which is the public API
1708 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:421709 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:351710 {
Sean Callanan8b0737f2012-06-02 01:16:201711 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:351712 {
Sean Callanan8b0737f2012-06-02 01:16:201713 if (log)
1714 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:061715 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:201716 }
1717 else
1718 {
1719 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1720 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:161721 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:351722 {
Jim Ingham221d51c2013-05-08 00:35:161723 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:201724 {
1725 if (log)
1726 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:061727 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:201728 }
Greg Clayton7fdf9ef2012-04-05 16:12:351729 }
Greg Clayton7fdf9ef2012-04-05 16:12:351730 }
1731 }
Chris Lattner30fdc8d2010-06-08 16:52:241732}
1733
Jim Ingham3b8285d2012-04-19 01:40:331734Error
1735Process::Resume ()
1736{
Greg Clayton5160ce52013-03-27 23:08:401737 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:331738 if (log)
1739 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:061740 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:331741 {
1742 Error error("Resume request failed - process still running.");
1743 if (log)
Ed Maste64fad602013-07-29 20:58:061744 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:331745 return error;
1746 }
1747 return PrivateResume();
1748}
1749
Greg Claytondc6224e2014-10-21 01:00:421750Error
1751Process::ResumeSynchronous (Stream *stream)
1752{
1753 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1754 if (log)
1755 log->Printf("Process::ResumeSynchronous -- locking run lock");
1756 if (!m_public_run_lock.TrySetRunning())
1757 {
1758 Error error("Resume request failed - process still running.");
1759 if (log)
1760 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1761 return error;
1762 }
1763
1764 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1765 HijackProcessEvents(listener_sp.get());
1766
1767 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:321768 if (error.Success())
1769 {
1770 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1771 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1772 if (!StateIsStoppedState(state, must_be_alive))
1773 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1774 }
Greg Claytondc6224e2014-10-21 01:00:421775
1776 // Undo the hijacking of process events...
1777 RestoreProcessEvents();
1778
Greg Claytondc6224e2014-10-21 01:00:421779 return error;
1780}
1781
Chris Lattner30fdc8d2010-06-08 16:52:241782StateType
1783Process::GetPrivateState ()
1784{
1785 return m_private_state.GetValue();
1786}
1787
1788void
1789Process::SetPrivateState (StateType new_state)
1790{
Greg Claytonfb8b37a2014-07-14 23:09:291791 if (m_finalize_called)
1792 return;
1793
Greg Clayton5160ce52013-03-27 23:08:401794 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:241795 bool state_changed = false;
1796
1797 if (log)
1798 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1799
Andrew Kaylor29d65742013-05-10 17:19:041800 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:241801 Mutex::Locker locker(m_private_state.GetMutex());
1802
1803 const StateType old_state = m_private_state.GetValueNoLock ();
1804 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:471805
Greg Claytonaa49c832013-05-03 22:25:561806 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1807 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1808 if (old_state_is_stopped != new_state_is_stopped)
1809 {
1810 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:061811 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:561812 else
Ed Maste64fad602013-07-29 20:58:061813 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:561814 }
Andrew Kaylor93132f52013-05-28 23:04:251815
Chris Lattner30fdc8d2010-06-08 16:52:241816 if (state_changed)
1817 {
1818 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:471819 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:071820 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:241821 {
Andrew Kaylor29d65742013-05-10 17:19:041822 // Note, this currently assumes that all threads in the list
1823 // stop when the process stops. In the future we will want to
1824 // support a debugging model where some threads continue to run
1825 // while others are stopped. When that happens we will either need
1826 // a way for the thread list to identify which threads are stopping
1827 // or create a special thread list containing only threads which
1828 // actually stopped.
1829 //
1830 // The process plugin is responsible for managing the actual
1831 // behavior of the threads and should have stopped any threads
1832 // that are going to stop before we get here.
1833 m_thread_list.DidStop();
1834
Jim Ingham4b536182011-08-09 02:12:221835 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:471836 if (!m_mod_id.IsLastResumeForUserExpression())
1837 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:191838 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:241839 if (log)
Jim Ingham4b536182011-08-09 02:12:221840 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:241841 }
Ilia K38810f42015-05-20 10:15:471842
Chris Lattner30fdc8d2010-06-08 16:52:241843 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:081844 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:471845 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:081846 else
Ilia K38810f42015-05-20 10:15:471847 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:241848 }
1849 else
1850 {
1851 if (log)
Jason Molendafd54b362011-09-20 21:44:101852 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:241853 }
1854}
1855
Jim Ingham0faa43f2011-11-08 03:00:111856void
1857Process::SetRunningUserExpression (bool on)
1858{
1859 m_mod_id.SetRunningUserExpression (on);
1860}
1861
Chris Lattner30fdc8d2010-06-08 16:52:241862addr_t
1863Process::GetImageInfoAddress()
1864{
1865 return LLDB_INVALID_ADDRESS;
1866}
1867
Greg Clayton8f343b02010-11-04 01:54:291868//----------------------------------------------------------------------
1869// LoadImage
1870//
1871// This function provides a default implementation that works for most
1872// unix variants. Any Process subclasses that need to do shared library
1873// loading differently should override LoadImage and UnloadImage and
1874// do what is needed.
1875//----------------------------------------------------------------------
1876uint32_t
1877Process::LoadImage (const FileSpec &image_spec, Error &error)
1878{
Greg Claytonc00ca312015-04-02 18:44:581879 if (m_finalizing)
1880 {
1881 error.SetErrorString("process is tearing itself down");
1882 return LLDB_INVALID_IMAGE_TOKEN;
1883 }
1884
Greg Claytonac7a3db2012-04-18 00:05:191885 char path[PATH_MAX];
1886 image_spec.GetPath(path, sizeof(path));
1887
Greg Clayton8f343b02010-11-04 01:54:291888 DynamicLoader *loader = GetDynamicLoader();
1889 if (loader)
1890 {
1891 error = loader->CanLoadImage();
1892 if (error.Fail())
1893 return LLDB_INVALID_IMAGE_TOKEN;
1894 }
1895
1896 if (error.Success())
1897 {
1898 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:291899
1900 if (thread_sp)
1901 {
Jason Molendab57e4a1b2013-11-04 09:33:301902 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:291903
1904 if (frame_sp)
1905 {
1906 ExecutionContext exe_ctx;
1907 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:171908 EvaluateExpressionOptions expr_options;
1909 expr_options.SetUnwindOnError(true);
1910 expr_options.SetIgnoreBreakpoints(true);
1911 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:161912 expr_options.SetResultIsInternal(true);
1913
Greg Clayton8f343b02010-11-04 01:54:291914 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:061915 expr.Printf(R"(
1916 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1917 the_result.image_ptr = dlopen ("%s", 2);
1918 if (the_result.image_ptr == (void *) 0x0)
1919 {
1920 the_result.error_str = dlerror();
1921 }
1922 else
1923 {
1924 the_result.error_str = (const char *) 0x0;
1925 }
1926 the_result;
1927 )",
1928 path);
1929 const char *prefix = R"(
1930 extern "C" void* dlopen (const char *path, int mode);
1931 extern "C" const char *dlerror (void);
1932 )";
Jim Inghamf48169b2010-11-30 02:22:111933 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:171934 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:041935 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:171936 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:041937 expr.GetData(),
1938 prefix,
1939 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:171940 expr_error);
1941 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:291942 {
Greg Clayton62afb9f2013-11-04 19:35:171943 error = result_valobj_sp->GetError();
1944 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:291945 {
Greg Clayton62afb9f2013-11-04 19:35:171946 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:061947 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1948 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:291949 {
Greg Clayton62afb9f2013-11-04 19:35:171950 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1951 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1952 {
1953 uint32_t image_token = m_image_tokens.size();
1954 m_image_tokens.push_back (image_ptr);
1955 return image_token;
1956 }
Jim Ingham3ac7cf32014-07-17 18:55:251957 else if (image_ptr == 0)
1958 {
Jim Ingham6971b862014-07-19 00:37:061959 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1960 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:251961 {
Jim Ingham6971b862014-07-19 00:37:061962 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:251963 {
Enrico Granata2206b482014-10-30 18:27:311964 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1965 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:251966 if (error.Success() && num_chars > 0)
1967 {
1968 error.Clear();
Enrico Granata2206b482014-10-30 18:27:311969 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1970 }
1971 else
1972 {
1973 error.Clear();
1974 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:251975 }
1976 }
1977 }
1978 }
Greg Clayton8f343b02010-11-04 01:54:291979 }
1980 }
1981 }
Jim Ingham6c9ed912014-04-03 01:26:141982 else
1983 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:291984 }
1985 }
1986 }
Greg Claytonac7a3db2012-04-18 00:05:191987 if (!error.AsCString())
1988 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:291989 return LLDB_INVALID_IMAGE_TOKEN;
1990}
1991
1992//----------------------------------------------------------------------
1993// UnloadImage
1994//
1995// This function provides a default implementation that works for most
1996// unix variants. Any Process subclasses that need to do shared library
1997// loading differently should override LoadImage and UnloadImage and
1998// do what is needed.
1999//----------------------------------------------------------------------
2000Error
2001Process::UnloadImage (uint32_t image_token)
2002{
2003 Error error;
Greg Claytonc00ca312015-04-02 18:44:582004
2005 if (m_finalizing)
2006 {
2007 error.SetErrorString("process is tearing itself down");
2008 return error;
2009 }
2010
Greg Clayton8f343b02010-11-04 01:54:292011 if (image_token < m_image_tokens.size())
2012 {
2013 const addr_t image_addr = m_image_tokens[image_token];
2014 if (image_addr == LLDB_INVALID_ADDRESS)
2015 {
2016 error.SetErrorString("image already unloaded");
2017 }
2018 else
2019 {
2020 DynamicLoader *loader = GetDynamicLoader();
2021 if (loader)
2022 error = loader->CanLoadImage();
2023
2024 if (error.Success())
2025 {
2026 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:292027
2028 if (thread_sp)
2029 {
Jason Molendab57e4a1b2013-11-04 09:33:302030 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:292031
2032 if (frame_sp)
2033 {
2034 ExecutionContext exe_ctx;
2035 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:172036 EvaluateExpressionOptions expr_options;
2037 expr_options.SetUnwindOnError(true);
2038 expr_options.SetIgnoreBreakpoints(true);
2039 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:292040 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:152041 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:292042 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:112043 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:172044 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:042045 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:172046 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:042047 expr.GetData(),
2048 prefix,
2049 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:172050 expr_error);
Greg Clayton8f343b02010-11-04 01:54:292051 if (result_valobj_sp->GetError().Success())
2052 {
2053 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:252054 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:292055 {
2056 if (scalar.UInt(1))
2057 {
2058 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2059 }
2060 else
2061 {
2062 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2063 }
2064 }
2065 }
2066 else
2067 {
2068 error = result_valobj_sp->GetError();
2069 }
2070 }
2071 }
2072 }
2073 }
2074 }
2075 else
2076 {
2077 error.SetErrorString("invalid image token");
2078 }
2079 return error;
2080}
2081
Greg Clayton31f1d2f2011-05-11 18:39:182082const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:242083Process::GetABI()
2084{
Greg Clayton31f1d2f2011-05-11 18:39:182085 if (!m_abi_sp)
2086 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2087 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:242088}
2089
Jim Ingham22777012010-09-23 02:01:192090LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:192091Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:192092{
Greg Claytonc00ca312015-04-02 18:44:582093 if (m_finalizing)
2094 return nullptr;
2095
Jim Ingham22777012010-09-23 02:01:192096 LanguageRuntimeCollection::iterator pos;
2097 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:192098 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:192099 {
Jim Inghamab175242012-03-10 00:22:192100 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:192101
Jim Inghamab175242012-03-10 00:22:192102 m_language_runtimes[language] = runtime_sp;
2103 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:192104 }
2105 else
2106 return (*pos).second.get();
2107}
2108
2109CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:192110Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:192111{
Jim Inghamab175242012-03-10 00:22:192112 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:192113 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2114 return static_cast<CPPLanguageRuntime *> (runtime);
2115 return NULL;
2116}
2117
2118ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:192119Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:192120{
Jim Inghamab175242012-03-10 00:22:192121 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:192122 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2123 return static_cast<ObjCLanguageRuntime *> (runtime);
2124 return NULL;
2125}
2126
Enrico Granatafd4c84e2012-05-21 16:51:352127bool
2128Process::IsPossibleDynamicValue (ValueObject& in_value)
2129{
Greg Claytonc00ca312015-04-02 18:44:582130 if (m_finalizing)
2131 return false;
2132
Enrico Granatafd4c84e2012-05-21 16:51:352133 if (in_value.IsDynamic())
2134 return false;
2135 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2136
2137 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2138 {
2139 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2140 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2141 }
2142
2143 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2144 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2145 return true;
2146
2147 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2148 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2149}
2150
Zachary Turner93749ab2015-03-03 21:51:252151void
2152Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2153{
2154 m_dynamic_checkers_ap.reset(dynamic_checkers);
2155}
2156
Chris Lattner30fdc8d2010-06-08 16:52:242157BreakpointSiteList &
2158Process::GetBreakpointSiteList()
2159{
2160 return m_breakpoint_site_list;
2161}
2162
2163const BreakpointSiteList &
2164Process::GetBreakpointSiteList() const
2165{
2166 return m_breakpoint_site_list;
2167}
2168
2169
2170void
2171Process::DisableAllBreakpointSites ()
2172{
Greg Claytond8cf1a12013-06-12 00:46:382173 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2174// bp_site->SetEnabled(true);
2175 DisableBreakpointSite(bp_site);
2176 });
Chris Lattner30fdc8d2010-06-08 16:52:242177}
2178
2179Error
2180Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2181{
2182 Error error (DisableBreakpointSiteByID (break_id));
2183
2184 if (error.Success())
2185 m_breakpoint_site_list.Remove(break_id);
2186
2187 return error;
2188}
2189
2190Error
2191Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2192{
2193 Error error;
2194 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2195 if (bp_site_sp)
2196 {
2197 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:302198 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:242199 }
2200 else
2201 {
Daniel Malead01b2952012-11-29 21:49:152202 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:242203 }
2204
2205 return error;
2206}
2207
2208Error
2209Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2210{
2211 Error error;
2212 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2213 if (bp_site_sp)
2214 {
2215 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:302216 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:242217 }
2218 else
2219 {
Daniel Malead01b2952012-11-29 21:49:152220 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:242221 }
2222 return error;
2223}
2224
Stephen Wilson50bd94f2010-07-17 00:56:132225lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:302226Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:242227{
Jim Ingham1460e4b2014-01-10 23:46:592228 addr_t load_addr = LLDB_INVALID_ADDRESS;
2229
2230 bool show_error = true;
2231 switch (GetState())
2232 {
2233 case eStateInvalid:
2234 case eStateUnloaded:
2235 case eStateConnected:
2236 case eStateAttaching:
2237 case eStateLaunching:
2238 case eStateDetached:
2239 case eStateExited:
2240 show_error = false;
2241 break;
2242
2243 case eStateStopped:
2244 case eStateRunning:
2245 case eStateStepping:
2246 case eStateCrashed:
2247 case eStateSuspended:
2248 show_error = IsAlive();
2249 break;
2250 }
2251
2252 // Reset the IsIndirect flag here, in case the location changes from
2253 // pointing to a indirect symbol to a regular symbol.
2254 owner->SetIsIndirect (false);
2255
2256 if (owner->ShouldResolveIndirectFunctions())
2257 {
2258 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2259 if (symbol && symbol->IsIndirect())
2260 {
2261 Error error;
Greg Clayton358cf1e2015-06-25 21:46:342262 Address symbol_address = symbol->GetAddress();
2263 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:592264 if (!error.Success() && show_error)
2265 {
Greg Clayton44d93782014-01-27 23:43:242266 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
Greg Clayton358cf1e2015-06-25 21:46:342267 symbol->GetLoadAddress(&m_target),
Greg Clayton44d93782014-01-27 23:43:242268 owner->GetBreakpoint().GetID(),
2269 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:282270 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:592271 return LLDB_INVALID_BREAK_ID;
2272 }
2273 Address resolved_address(load_addr);
2274 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2275 owner->SetIsIndirect(true);
2276 }
2277 else
2278 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2279 }
2280 else
2281 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2282
Chris Lattner30fdc8d2010-06-08 16:52:242283 if (load_addr != LLDB_INVALID_ADDRESS)
2284 {
2285 BreakpointSiteSP bp_site_sp;
2286
2287 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2288 // create a new breakpoint site and add it.
2289
2290 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2291
2292 if (bp_site_sp)
2293 {
2294 bp_site_sp->AddOwner (owner);
2295 owner->SetBreakpointSite (bp_site_sp);
2296 return bp_site_sp->GetID();
2297 }
2298 else
2299 {
Greg Claytonc7bece562013-01-25 18:06:212300 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:242301 if (bp_site_sp)
2302 {
Greg Claytoneb023e72013-10-11 19:48:252303 Error error = EnableBreakpointSite (bp_site_sp.get());
2304 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:242305 {
2306 owner->SetBreakpointSite (bp_site_sp);
2307 return m_breakpoint_site_list.Add (bp_site_sp);
2308 }
Greg Claytoneb023e72013-10-11 19:48:252309 else
2310 {
Greg Claytonfbb76342013-11-20 21:07:012311 if (show_error)
2312 {
2313 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:242314 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2315 load_addr,
2316 owner->GetBreakpoint().GetID(),
2317 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:282318 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:012319 }
Greg Claytoneb023e72013-10-11 19:48:252320 }
Chris Lattner30fdc8d2010-06-08 16:52:242321 }
2322 }
2323 }
2324 // We failed to enable the breakpoint
2325 return LLDB_INVALID_BREAK_ID;
2326
2327}
2328
2329void
2330Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2331{
2332 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2333 if (num_owners == 0)
2334 {
Jim Inghamf1ff3bb2013-04-06 00:16:392335 // Don't try to disable the site if we don't have a live process anymore.
2336 if (IsAlive())
2337 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:242338 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2339 }
2340}
2341
2342
2343size_t
2344Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2345{
2346 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:282347 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:242348
Jim Ingham20c77192011-06-29 19:42:282349 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:242350 {
Greg Claytond8cf1a12013-06-12 00:46:382351 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2352 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:242353 {
Greg Claytond8cf1a12013-06-12 00:46:382354 addr_t intersect_addr;
2355 size_t intersect_size;
2356 size_t opcode_offset;
2357 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:282358 {
2359 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2360 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:382361 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:282362 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:382363 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:282364 }
Chris Lattner30fdc8d2010-06-08 16:52:242365 }
Greg Claytond8cf1a12013-06-12 00:46:382366 });
Chris Lattner30fdc8d2010-06-08 16:52:242367 }
2368 return bytes_removed;
2369}
2370
2371
Greg Claytonded470d2011-03-19 01:12:212372
2373size_t
2374Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2375{
2376 PlatformSP platform_sp (m_target.GetPlatform());
2377 if (platform_sp)
2378 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2379 return 0;
2380}
2381
Chris Lattner30fdc8d2010-06-08 16:52:242382Error
2383Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2384{
2385 Error error;
2386 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:402387 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:242388 const addr_t bp_addr = bp_site->GetLoadAddress();
2389 if (log)
Daniel Malead01b2952012-11-29 21:49:152390 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:242391 if (bp_site->IsEnabled())
2392 {
2393 if (log)
Daniel Malead01b2952012-11-29 21:49:152394 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:242395 return error;
2396 }
2397
2398 if (bp_addr == LLDB_INVALID_ADDRESS)
2399 {
2400 error.SetErrorString("BreakpointSite contains an invalid load address.");
2401 return error;
2402 }
2403 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2404 // trap for the breakpoint site
2405 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2406
2407 if (bp_opcode_size == 0)
2408 {
Daniel Malead01b2952012-11-29 21:49:152409 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:242410 }
2411 else
2412 {
2413 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2414
2415 if (bp_opcode_bytes == NULL)
2416 {
2417 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2418 return error;
2419 }
2420
2421 // Save the original opcode by reading it
2422 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2423 {
2424 // Write a software breakpoint in place of the original opcode
2425 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2426 {
2427 uint8_t verify_bp_opcode_bytes[64];
2428 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2429 {
2430 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2431 {
2432 bp_site->SetEnabled(true);
2433 bp_site->SetType (BreakpointSite::eSoftware);
2434 if (log)
Daniel Malead01b2952012-11-29 21:49:152435 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:242436 bp_site->GetID(),
2437 (uint64_t)bp_addr);
2438 }
2439 else
Greg Clayton86edbf42011-10-26 00:56:272440 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:242441 }
2442 else
2443 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2444 }
2445 else
2446 error.SetErrorString("Unable to write breakpoint trap to memory.");
2447 }
2448 else
2449 error.SetErrorString("Unable to read memory at breakpoint address.");
2450 }
Stephen Wilson78a4feb2011-01-12 04:20:032451 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:152452 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:242453 bp_site->GetID(),
2454 (uint64_t)bp_addr,
2455 error.AsCString());
2456 return error;
2457}
2458
2459Error
2460Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2461{
2462 Error error;
2463 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:402464 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:242465 addr_t bp_addr = bp_site->GetLoadAddress();
2466 lldb::user_id_t breakID = bp_site->GetID();
2467 if (log)
Jim Ingham299c0c12013-02-15 02:06:302468 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:242469
2470 if (bp_site->IsHardware())
2471 {
2472 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2473 }
2474 else if (bp_site->IsEnabled())
2475 {
2476 const size_t break_op_size = bp_site->GetByteSize();
2477 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2478 if (break_op_size > 0)
2479 {
Bruce Mitchenerd93c4a32014-07-01 21:22:112480 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:502481 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:112482 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:242483 bool break_op_found = false;
2484
2485 // Read the breakpoint opcode
2486 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2487 {
2488 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:052489 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:242490 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2491 {
2492 break_op_found = true;
2493 // We found a valid breakpoint opcode at this address, now restore
2494 // the saved opcode.
2495 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2496 {
2497 verify = true;
2498 }
2499 else
2500 error.SetErrorString("Memory write failed when restoring original opcode.");
2501 }
2502 else
2503 {
2504 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2505 // Set verify to true and so we can check if the original opcode has already been restored
2506 verify = true;
2507 }
2508
2509 if (verify)
2510 {
Greg Claytonc982c762010-07-09 20:39:502511 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:112512 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:242513 // Verify that our original opcode made it back to the inferior
2514 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2515 {
2516 // compare the memory we just read with the original opcode
2517 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2518 {
2519 // SUCCESS
2520 bp_site->SetEnabled(false);
2521 if (log)
Daniel Malead01b2952012-11-29 21:49:152522 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:242523 return error;
2524 }
2525 else
2526 {
2527 if (break_op_found)
2528 error.SetErrorString("Failed to restore original opcode.");
2529 }
2530 }
2531 else
2532 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2533 }
2534 }
2535 else
2536 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2537 }
2538 }
2539 else
2540 {
2541 if (log)
Daniel Malead01b2952012-11-29 21:49:152542 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:242543 return error;
2544 }
2545
2546 if (log)
Daniel Malead01b2952012-11-29 21:49:152547 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:242548 bp_site->GetID(),
2549 (uint64_t)bp_addr,
2550 error.AsCString());
2551 return error;
2552
2553}
2554
Greg Clayton58be07b2011-01-07 06:08:192555// Uncomment to verify memory caching works after making changes to caching code
2556//#define VERIFY_MEMORY_READS
2557
Sean Callanan64c0cf22012-06-07 22:26:422558size_t
2559Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2560{
Jason Molendaa7b5afa2013-11-15 00:17:322561 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:422562 if (!GetDisableMemoryCache())
2563 {
Greg Clayton58be07b2011-01-07 06:08:192564#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:422565 // Memory caching is enabled, with debug verification
2566
2567 if (buf && size)
2568 {
2569 // Uncomment the line below to make sure memory caching is working.
2570 // I ran this through the test suite and got no assertions, so I am
2571 // pretty confident this is working well. If any changes are made to
2572 // memory caching, uncomment the line below and test your changes!
2573
2574 // Verify all memory reads by using the cache first, then redundantly
2575 // reading the same memory from the inferior and comparing to make sure
2576 // everything is exactly the same.
2577 std::string verify_buf (size, '\0');
2578 assert (verify_buf.size() == size);
2579 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2580 Error verify_error;
2581 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2582 assert (cache_bytes_read == verify_bytes_read);
2583 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2584 assert (verify_error.Success() == error.Success());
2585 return cache_bytes_read;
2586 }
2587 return 0;
2588#else // !defined(VERIFY_MEMORY_READS)
2589 // Memory caching is enabled, without debug verification
2590
2591 return m_memory_cache.Read (addr, buf, size, error);
2592#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:192593 }
Sean Callanan64c0cf22012-06-07 22:26:422594 else
2595 {
2596 // Memory caching is disabled
2597
2598 return ReadMemoryFromInferior (addr, buf, size, error);
2599 }
Greg Clayton58be07b2011-01-07 06:08:192600}
Greg Clayton58be07b2011-01-07 06:08:192601
Greg Clayton4c82d422012-05-18 23:20:012602size_t
2603Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2604{
Greg Claytonde87c0f2012-05-19 00:18:002605 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:012606 out_str.clear();
2607 addr_t curr_addr = addr;
2608 while (1)
2609 {
2610 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2611 if (length == 0)
2612 break;
2613 out_str.append(buf, length);
2614 // If we got "length - 1" bytes, we didn't get the whole C string, we
2615 // need to read some more characters
2616 if (length == sizeof(buf) - 1)
2617 curr_addr += length;
2618 else
2619 break;
2620 }
2621 return out_str.size();
2622}
2623
Greg Clayton58be07b2011-01-07 06:08:192624
2625size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:382626Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2627 size_t type_width)
2628{
2629 size_t total_bytes_read = 0;
2630 if (dst && max_bytes && type_width && max_bytes >= type_width)
2631 {
2632 // Ensure a null terminator independent of the number of bytes that is read.
2633 memset (dst, 0, max_bytes);
2634 size_t bytes_left = max_bytes - type_width;
2635
2636 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2637 assert(sizeof(terminator) >= type_width &&
2638 "Attempting to validate a string with more than 4 bytes per character!");
2639
2640 addr_t curr_addr = addr;
2641 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2642 char *curr_dst = dst;
2643
2644 error.Clear();
2645 while (bytes_left > 0 && error.Success())
2646 {
2647 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2648 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2649 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2650
2651 if (bytes_read == 0)
2652 break;
2653
2654 // Search for a null terminator of correct size and alignment in bytes_read
2655 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2656 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2657 if (::strncmp(&dst[i], terminator, type_width) == 0)
2658 {
2659 error.Clear();
2660 return i;
2661 }
2662
2663 total_bytes_read += bytes_read;
2664 curr_dst += bytes_read;
2665 curr_addr += bytes_read;
2666 bytes_left -= bytes_read;
2667 }
2668 }
2669 else
2670 {
2671 if (max_bytes)
2672 error.SetErrorString("invalid arguments");
2673 }
2674 return total_bytes_read;
2675}
2676
2677// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2678// null terminators.
2679size_t
Greg Claytone91b7952011-12-15 03:14:232680Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:462681{
2682 size_t total_cstr_len = 0;
2683 if (dst && dst_max_len)
2684 {
Greg Claytone91b7952011-12-15 03:14:232685 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:462686 // NULL out everything just to be safe
2687 memset (dst, 0, dst_max_len);
2688 Error error;
2689 addr_t curr_addr = addr;
2690 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2691 size_t bytes_left = dst_max_len - 1;
2692 char *curr_dst = dst;
2693
2694 while (bytes_left > 0)
2695 {
2696 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2697 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2698 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2699
2700 if (bytes_read == 0)
2701 {
Greg Claytone91b7952011-12-15 03:14:232702 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:462703 dst[total_cstr_len] = '\0';
2704 break;
2705 }
2706 const size_t len = strlen(curr_dst);
2707
2708 total_cstr_len += len;
2709
2710 if (len < bytes_to_read)
2711 break;
2712
2713 curr_dst += bytes_read;
2714 curr_addr += bytes_read;
2715 bytes_left -= bytes_read;
2716 }
2717 }
Greg Claytone91b7952011-12-15 03:14:232718 else
2719 {
2720 if (dst == NULL)
2721 result_error.SetErrorString("invalid arguments");
2722 else
2723 result_error.Clear();
2724 }
Greg Clayton8b82f082011-04-12 05:54:462725 return total_cstr_len;
2726}
2727
2728size_t
Greg Clayton58be07b2011-01-07 06:08:192729Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2730{
Chris Lattner30fdc8d2010-06-08 16:52:242731 if (buf == NULL || size == 0)
2732 return 0;
2733
2734 size_t bytes_read = 0;
2735 uint8_t *bytes = (uint8_t *)buf;
2736
2737 while (bytes_read < size)
2738 {
2739 const size_t curr_size = size - bytes_read;
2740 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2741 bytes + bytes_read,
2742 curr_size,
2743 error);
2744 bytes_read += curr_bytes_read;
2745 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2746 break;
2747 }
2748
2749 // Replace any software breakpoint opcodes that fall into this range back
2750 // into "buf" before we return
2751 if (bytes_read > 0)
2752 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2753 return bytes_read;
2754}
2755
Greg Clayton58a4c462010-12-16 20:01:202756uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:532757Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:202758{
Greg Claytonf3ef3d22011-05-22 22:46:532759 Scalar scalar;
2760 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2761 return scalar.ULongLong(fail_value);
2762 return fail_value;
2763}
2764
2765addr_t
2766Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2767{
2768 Scalar scalar;
2769 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2770 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2771 return LLDB_INVALID_ADDRESS;
2772}
2773
2774
2775bool
2776Process::WritePointerToMemory (lldb::addr_t vm_addr,
2777 lldb::addr_t ptr_value,
2778 Error &error)
2779{
2780 Scalar scalar;
2781 const uint32_t addr_byte_size = GetAddressByteSize();
2782 if (addr_byte_size <= 4)
2783 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:202784 else
Greg Claytonf3ef3d22011-05-22 22:46:532785 scalar = ptr_value;
2786 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:202787}
2788
Chris Lattner30fdc8d2010-06-08 16:52:242789size_t
2790Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2791{
2792 size_t bytes_written = 0;
2793 const uint8_t *bytes = (const uint8_t *)buf;
2794
2795 while (bytes_written < size)
2796 {
2797 const size_t curr_size = size - bytes_written;
2798 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2799 bytes + bytes_written,
2800 curr_size,
2801 error);
2802 bytes_written += curr_bytes_written;
2803 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2804 break;
2805 }
2806 return bytes_written;
2807}
2808
2809size_t
2810Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2811{
Greg Clayton58be07b2011-01-07 06:08:192812#if defined (ENABLE_MEMORY_CACHING)
2813 m_memory_cache.Flush (addr, size);
2814#endif
2815
Chris Lattner30fdc8d2010-06-08 16:52:242816 if (buf == NULL || size == 0)
2817 return 0;
Jim Ingham78a685a2011-04-16 00:01:132818
Jim Ingham4b536182011-08-09 02:12:222819 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:132820
Chris Lattner30fdc8d2010-06-08 16:52:242821 // We need to write any data that would go where any current software traps
2822 // (enabled software breakpoints) any software traps (breakpoints) that we
2823 // may have placed in our tasks memory.
2824
Greg Claytond8cf1a12013-06-12 00:46:382825 BreakpointSiteList bp_sites_in_range;
2826
2827 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:242828 {
Greg Claytond8cf1a12013-06-12 00:46:382829 // No breakpoint sites overlap
2830 if (bp_sites_in_range.IsEmpty())
2831 return WriteMemoryPrivate (addr, buf, size, error);
2832 else
Chris Lattner30fdc8d2010-06-08 16:52:242833 {
Greg Claytond8cf1a12013-06-12 00:46:382834 const uint8_t *ubuf = (const uint8_t *)buf;
2835 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:242836
Greg Claytond8cf1a12013-06-12 00:46:382837 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2838
2839 if (error.Success())
2840 {
2841 addr_t intersect_addr;
2842 size_t intersect_size;
2843 size_t opcode_offset;
2844 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2845 assert(intersects);
2846 assert(addr <= intersect_addr && intersect_addr < addr + size);
2847 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2848 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2849
2850 // Check for bytes before this breakpoint
2851 const addr_t curr_addr = addr + bytes_written;
2852 if (intersect_addr > curr_addr)
2853 {
2854 // There are some bytes before this breakpoint that we need to
2855 // just write to memory
2856 size_t curr_size = intersect_addr - curr_addr;
2857 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2858 ubuf + bytes_written,
2859 curr_size,
2860 error);
2861 bytes_written += curr_bytes_written;
2862 if (curr_bytes_written != curr_size)
2863 {
2864 // We weren't able to write all of the requested bytes, we
2865 // are done looping and will return the number of bytes that
2866 // we have written so far.
2867 if (error.Success())
2868 error.SetErrorToGenericError();
2869 }
2870 }
2871 // Now write any bytes that would cover up any software breakpoints
2872 // directly into the breakpoint opcode buffer
2873 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2874 bytes_written += intersect_size;
2875 }
2876 });
2877
2878 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:272879 WriteMemoryPrivate (addr + bytes_written,
2880 ubuf + bytes_written,
2881 size - bytes_written,
2882 error);
Greg Claytond8cf1a12013-06-12 00:46:382883 }
2884 }
2885 else
2886 {
2887 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:242888 }
2889
2890 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:382891 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:242892}
Greg Claytonf3ef3d22011-05-22 22:46:532893
2894size_t
Greg Claytonc7bece562013-01-25 18:06:212895Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:532896{
2897 if (byte_size == UINT32_MAX)
2898 byte_size = scalar.GetByteSize();
2899 if (byte_size > 0)
2900 {
2901 uint8_t buf[32];
2902 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2903 if (mem_size > 0)
2904 return WriteMemory(addr, buf, mem_size, error);
2905 else
2906 error.SetErrorString ("failed to get scalar as memory data");
2907 }
2908 else
2909 {
2910 error.SetErrorString ("invalid scalar value");
2911 }
2912 return 0;
2913}
2914
2915size_t
2916Process::ReadScalarIntegerFromMemory (addr_t addr,
2917 uint32_t byte_size,
2918 bool is_signed,
2919 Scalar &scalar,
2920 Error &error)
2921{
Greg Clayton7060f892013-05-01 23:41:302922 uint64_t uval = 0;
2923 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:532924 {
Greg Clayton7060f892013-05-01 23:41:302925 error.SetErrorString ("byte size is zero");
2926 }
2927 else if (byte_size & (byte_size - 1))
2928 {
2929 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2930 }
2931 else if (byte_size <= sizeof(uval))
2932 {
2933 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:532934 if (bytes_read == byte_size)
2935 {
2936 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:212937 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:302938 if (byte_size <= 4)
2939 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:532940 else
Greg Clayton7060f892013-05-01 23:41:302941 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:532942 if (is_signed)
2943 scalar.SignExtend(byte_size * 8);
2944 return bytes_read;
2945 }
2946 }
2947 else
2948 {
2949 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2950 }
2951 return 0;
2952}
2953
Greg Claytond495c532011-05-17 03:37:422954#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:242955addr_t
2956Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2957{
Jim Inghamf72ce3a2011-06-20 17:32:442958 if (GetPrivateState() != eStateStopped)
2959 return LLDB_INVALID_ADDRESS;
2960
Greg Claytond495c532011-05-17 03:37:422961#if defined (USE_ALLOCATE_MEMORY_CACHE)
2962 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2963#else
Greg Claytonb2daec92011-01-23 19:58:492964 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:402965 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:492966 if (log)
Greg Clayton45989072013-10-23 18:24:302967 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:432968 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:422969 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:492970 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:222971 m_mod_id.GetStopID(),
2972 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:492973 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:422974#endif
Chris Lattner30fdc8d2010-06-08 16:52:242975}
2976
Sean Callanan90539452011-09-20 23:01:512977bool
2978Process::CanJIT ()
2979{
Sean Callanana7b443a2012-02-14 22:50:382980 if (m_can_jit == eCanJITDontKnow)
2981 {
Todd Fialaaf245d12014-06-30 21:05:182982 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:382983 Error err;
2984
2985 uint64_t allocated_memory = AllocateMemory(8,
2986 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2987 err);
2988
2989 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:182990 {
Sean Callanana7b443a2012-02-14 22:50:382991 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:182992 if (log)
2993 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2994 }
Sean Callanana7b443a2012-02-14 22:50:382995 else
Todd Fialaaf245d12014-06-30 21:05:182996 {
Sean Callanana7b443a2012-02-14 22:50:382997 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:182998 if (log)
2999 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
3000 }
Sean Callanana7b443a2012-02-14 22:50:383001
3002 DeallocateMemory (allocated_memory);
3003 }
3004
Sean Callanan90539452011-09-20 23:01:513005 return m_can_jit == eCanJITYes;
3006}
3007
3008void
3009Process::SetCanJIT (bool can_jit)
3010{
3011 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
3012}
3013
Chris Lattner30fdc8d2010-06-08 16:52:243014Error
3015Process::DeallocateMemory (addr_t ptr)
3016{
Greg Claytond495c532011-05-17 03:37:423017 Error error;
3018#if defined (USE_ALLOCATE_MEMORY_CACHE)
3019 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
3020 {
Daniel Malead01b2952012-11-29 21:49:153021 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:423022 }
3023#else
3024 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:493025
Greg Clayton5160ce52013-03-27 23:08:403026 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:493027 if (log)
Daniel Malead01b2952012-11-29 21:49:153028 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:493029 ptr,
3030 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:223031 m_mod_id.GetStopID(),
3032 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:423033#endif
Greg Claytonb2daec92011-01-23 19:58:493034 return error;
Chris Lattner30fdc8d2010-06-08 16:52:243035}
3036
Han Ming Ongc811d382012-11-17 00:33:143037
Greg Claytonc9660542012-02-05 02:38:543038ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:393039Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:433040 lldb::addr_t header_addr,
3041 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:543042{
Greg Claytonc7f09cc2012-02-24 21:55:593043 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:543044 if (module_sp)
3045 {
Greg Claytonc7f09cc2012-02-24 21:55:593046 Error error;
Andrew MacPherson17220c12014-03-05 10:12:433047 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:593048 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:593049 return module_sp;
Greg Claytonc9660542012-02-05 02:38:543050 }
Greg Claytonc7f09cc2012-02-24 21:55:593051 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:543052}
Chris Lattner30fdc8d2010-06-08 16:52:243053
Zachary Turner93749ab2015-03-03 21:51:253054bool
3055Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3056{
3057 MemoryRegionInfo range_info;
3058 permissions = 0;
3059 Error error (GetMemoryRegionInfo (load_addr, range_info));
3060 if (!error.Success())
3061 return false;
3062 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3063 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3064 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3065 {
3066 return false;
3067 }
3068
3069 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3070 permissions |= lldb::ePermissionsReadable;
3071
3072 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3073 permissions |= lldb::ePermissionsWritable;
3074
3075 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3076 permissions |= lldb::ePermissionsExecutable;
3077
3078 return true;
3079}
3080
Chris Lattner30fdc8d2010-06-08 16:52:243081Error
Jim Ingham1b5792e2012-12-18 02:03:493082Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:243083{
3084 Error error;
3085 error.SetErrorString("watchpoints are not supported");
3086 return error;
3087}
3088
3089Error
Jim Ingham1b5792e2012-12-18 02:03:493090Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:243091{
3092 Error error;
3093 error.SetErrorString("watchpoints are not supported");
3094 return error;
3095}
3096
3097StateType
3098Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3099{
3100 StateType state;
3101 // Now wait for the process to launch and return control to us, and then
3102 // call DidLaunch:
3103 while (1)
3104 {
Greg Clayton6779606a2011-01-22 23:43:183105 event_sp.reset();
3106 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3107
Greg Clayton2637f822011-11-17 01:23:073108 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:243109 break;
Greg Clayton6779606a2011-01-22 23:43:183110
3111 // If state is invalid, then we timed out
3112 if (state == eStateInvalid)
3113 break;
3114
3115 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:243116 HandlePrivateEvent (event_sp);
3117 }
3118 return state;
3119}
3120
Greg Clayton332e8b12015-01-13 21:13:083121void
3122Process::LoadOperatingSystemPlugin(bool flush)
3123{
3124 if (flush)
3125 m_thread_list.Clear();
3126 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3127 if (flush)
3128 Flush();
3129}
3130
Chris Lattner30fdc8d2010-06-08 16:52:243131Error
Greg Claytonfbb76342013-11-20 21:07:013132Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:243133{
3134 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:243135 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:073136 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:433137 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:193138 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:393139 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:413140 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:023141 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:243142
Greg Claytonaa149cb2011-08-11 02:48:453143 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:243144 if (exe_module)
3145 {
Greg Clayton2289fa42011-04-30 01:09:133146 char local_exec_file_path[PATH_MAX];
3147 char platform_exec_file_path[PATH_MAX];
3148 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3149 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:243150 if (exe_module->GetFileSpec().Exists())
3151 {
Greg Claytonfbb76342013-11-20 21:07:013152 // Install anything that might need to be installed prior to launching.
3153 // For host systems, this will do nothing, but if we are connected to a
3154 // remote platform it will install any needed binaries
3155 error = GetTarget().Install(&launch_info);
3156 if (error.Fail())
3157 return error;
3158
Greg Clayton71337622011-02-24 22:24:293159 if (PrivateStateThreadIsValid ())
3160 PausePrivateStateThread ();
3161
Chris Lattner30fdc8d2010-06-08 16:52:243162 error = WillLaunch (exe_module);
3163 if (error.Success())
3164 {
Jim Ingham221d51c2013-05-08 00:35:163165 const bool restarted = false;
3166 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:023167 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:243168
Ed Maste64fad602013-07-29 20:58:063169 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:053170 {
3171 // Now launch using these arguments.
3172 error = DoLaunch (exe_module, launch_info);
3173 }
3174 else
3175 {
3176 // This shouldn't happen
3177 error.SetErrorString("failed to acquire process run lock");
3178 }
Chris Lattner30fdc8d2010-06-08 16:52:243179
3180 if (error.Fail())
3181 {
3182 if (GetID() != LLDB_INVALID_PROCESS_ID)
3183 {
3184 SetID (LLDB_INVALID_PROCESS_ID);
3185 const char *error_string = error.AsCString();
3186 if (error_string == NULL)
3187 error_string = "launch failed";
3188 SetExitStatus (-1, error_string);
3189 }
3190 }
3191 else
3192 {
3193 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:173194 TimeValue timeout_time;
3195 timeout_time = TimeValue::Now();
3196 timeout_time.OffsetWithSeconds(10);
3197 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:243198
Greg Clayton1a38ea72011-06-22 01:42:173199 if (state == eStateInvalid || event_sp.get() == NULL)
3200 {
3201 // We were able to launch the process, but we failed to
3202 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:543203 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:173204 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:583205 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:173206 }
3207 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:243208 {
Greg Clayton93d3c8332011-02-16 04:46:073209
Chris Lattner30fdc8d2010-06-08 16:52:243210 DidLaunch ();
3211
Greg Claytonc859e2d2012-02-13 23:10:393212 DynamicLoader *dyld = GetDynamicLoader ();
3213 if (dyld)
3214 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:073215
Andrew MacPhersoneb4d0602014-03-13 09:37:023216 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:433217
Jason Molendaeef51062013-11-05 03:57:193218 SystemRuntime *system_runtime = GetSystemRuntime ();
3219 if (system_runtime)
3220 system_runtime->DidLaunch();
3221
Greg Clayton332e8b12015-01-13 21:13:083222 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:213223
3224 // Note, the stop event was consumed above, but not handled. This was done
3225 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3226 // Directly set the state. This is done to prevent a stop message with a bunch
3227 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3228 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:293229
3230 if (PrivateStateThreadIsValid ())
3231 ResumePrivateStateThread ();
3232 else
3233 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:023234
3235 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:053236
3237 // Target was stopped at entry as was intended. Need to notify the listeners
3238 // about it.
Ilia K333fc182015-02-11 11:24:203239 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:053240 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:243241 }
3242 else if (state == eStateExited)
3243 {
3244 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3245 // not likely to work, and return an invalid pid.
3246 HandlePrivateEvent (event_sp);
3247 }
3248 }
3249 }
3250 }
3251 else
3252 {
Greg Clayton86edbf42011-10-26 00:56:273253 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:243254 }
3255 }
3256 return error;
3257}
3258
Greg Claytonc3776bf2012-02-09 06:16:323259
3260Error
3261Process::LoadCore ()
3262{
3263 Error error = DoLoadCore();
3264 if (error.Success())
3265 {
Greg Clayton35824e32015-02-20 20:59:473266 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:063267 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:473268
Greg Claytonc3776bf2012-02-09 06:16:323269 if (PrivateStateThreadIsValid ())
3270 ResumePrivateStateThread ();
3271 else
3272 StartPrivateStateThread ();
3273
Greg Claytonc859e2d2012-02-13 23:10:393274 DynamicLoader *dyld = GetDynamicLoader ();
3275 if (dyld)
3276 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:433277
Andrew MacPhersoneb4d0602014-03-13 09:37:023278 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:393279
Jason Molendaeef51062013-11-05 03:57:193280 SystemRuntime *system_runtime = GetSystemRuntime ();
3281 if (system_runtime)
3282 system_runtime->DidAttach();
3283
Greg Claytonc859e2d2012-02-13 23:10:393284 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:323285 // We successfully loaded a core file, now pretend we stopped so we can
3286 // show all of the threads in the core file and explore the crashed
3287 // state.
3288 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:473289
3290 // Wait indefinitely for a stopped event since we just posted one above...
3291 lldb::EventSP event_sp;
3292 listener.WaitForEvent (NULL, event_sp);
3293 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3294
3295 if (!StateIsStoppedState (state, false))
3296 {
3297 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3298 if (log)
3299 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3300 error.SetErrorString ("Did not get stopped event after loading the core file.");
3301 }
Greg Clayton338d0bd2015-02-20 21:51:063302 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:323303 }
3304 return error;
3305}
3306
Greg Claytonc859e2d2012-02-13 23:10:393307DynamicLoader *
3308Process::GetDynamicLoader ()
3309{
3310 if (m_dyld_ap.get() == NULL)
3311 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3312 return m_dyld_ap.get();
3313}
Greg Claytonc3776bf2012-02-09 06:16:323314
Todd Fialaaf245d12014-06-30 21:05:183315const lldb::DataBufferSP
3316Process::GetAuxvData()
3317{
3318 return DataBufferSP ();
3319}
3320
Andrew MacPherson17220c12014-03-05 10:12:433321JITLoaderList &
3322Process::GetJITLoaders ()
3323{
3324 if (!m_jit_loaders_ap)
3325 {
3326 m_jit_loaders_ap.reset(new JITLoaderList());
3327 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3328 }
3329 return *m_jit_loaders_ap;
3330}
3331
Jason Molendaeef51062013-11-05 03:57:193332SystemRuntime *
3333Process::GetSystemRuntime ()
3334{
3335 if (m_system_runtime_ap.get() == NULL)
3336 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3337 return m_system_runtime_ap.get();
3338}
3339
Todd Fiala76e0fc92014-08-27 22:58:263340Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3341 NextEventAction (process),
3342 m_exec_count (exec_count)
3343{
3344 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3345 if (log)
3346 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3347}
Greg Claytonc3776bf2012-02-09 06:16:323348
Jim Inghambb3a2832011-01-29 01:49:253349Process::NextEventAction::EventActionResult
3350Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:243351{
Todd Fiala76e0fc92014-08-27 22:58:263352 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3353
Jim Inghambb3a2832011-01-29 01:49:253354 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:263355 if (log)
3356 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3357
3358 switch (state)
Greg Clayton19388cf2010-10-18 01:45:303359 {
Zachary Turnerc62733b2015-05-20 18:31:173360 case eStateAttaching:
3361 return eEventActionSuccess;
3362
Greg Clayton513c26c2011-01-29 07:10:553363 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:293364 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:553365 return eEventActionRetry;
3366
3367 case eStateStopped:
3368 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:563369 {
3370 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:313371 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:563372 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:163373 // We don't want these events to be reported, so go set the ShouldReportStop here:
3374 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3375
Greg Claytonc9ed4782011-11-12 02:10:563376 if (m_exec_count > 0)
3377 {
3378 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:263379
3380 if (log)
3381 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3382
Jim Ingham221d51c2013-05-08 00:35:163383 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:563384 return eEventActionRetry;
3385 }
3386 else
3387 {
Todd Fiala76e0fc92014-08-27 22:58:263388 if (log)
3389 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3390
Greg Claytonc9ed4782011-11-12 02:10:563391 m_process->CompleteAttach ();
3392 return eEventActionSuccess;
3393 }
3394 }
Greg Clayton513c26c2011-01-29 07:10:553395 break;
Greg Claytonc9ed4782011-11-12 02:10:563396
Greg Clayton513c26c2011-01-29 07:10:553397 default:
3398 case eStateExited:
3399 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:553400 break;
Jim Inghambb3a2832011-01-29 01:49:253401 }
Greg Claytonc9ed4782011-11-12 02:10:563402
3403 m_exit_string.assign ("No valid Process");
3404 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:253405}
Chris Lattner30fdc8d2010-06-08 16:52:243406
Jim Inghambb3a2832011-01-29 01:49:253407Process::NextEventAction::EventActionResult
3408Process::AttachCompletionHandler::HandleBeingInterrupted()
3409{
3410 return eEventActionSuccess;
3411}
3412
3413const char *
3414Process::AttachCompletionHandler::GetExitString ()
3415{
3416 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:243417}
3418
Greg Clayton8012cad2014-11-17 19:39:203419Listener &
3420ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3421{
3422 if (m_listener_sp)
3423 return *m_listener_sp;
3424 else
3425 return debugger.GetListener();
3426}
3427
Chris Lattner30fdc8d2010-06-08 16:52:243428Error
Greg Clayton144f3a92011-11-15 03:53:303429Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:243430{
Chris Lattner30fdc8d2010-06-08 16:52:243431 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:413432 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:073433 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:433434 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:193435 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:393436 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:023437 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:023438
Greg Clayton144f3a92011-11-15 03:53:303439 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:153440 Error error;
Greg Clayton144f3a92011-11-15 03:53:303441 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:023442 {
Greg Clayton144f3a92011-11-15 03:53:303443 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:173444
Greg Clayton144f3a92011-11-15 03:53:303445 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:193446 {
Greg Clayton144f3a92011-11-15 03:53:303447 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3448
3449 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:243450 {
Greg Clayton144f3a92011-11-15 03:53:303451 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3452 if (error.Success())
3453 {
Ed Maste64fad602013-07-29 20:58:063454 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:123455 {
3456 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:163457 const bool restarted = false;
3458 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:123459 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:543460 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:123461 }
3462 else
3463 {
3464 // This shouldn't happen
3465 error.SetErrorString("failed to acquire process run lock");
3466 }
Greg Claytone24c4ac2011-11-17 04:46:023467
Greg Clayton144f3a92011-11-15 03:53:303468 if (error.Fail())
3469 {
3470 if (GetID() != LLDB_INVALID_PROCESS_ID)
3471 {
3472 SetID (LLDB_INVALID_PROCESS_ID);
3473 if (error.AsCString() == NULL)
3474 error.SetErrorString("attach failed");
3475
3476 SetExitStatus(-1, error.AsCString());
3477 }
3478 }
3479 else
3480 {
3481 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3482 StartPrivateStateThread();
3483 }
3484 return error;
3485 }
Greg Claytone996fd32011-03-08 22:40:153486 }
Greg Clayton144f3a92011-11-15 03:53:303487 else
Greg Claytone996fd32011-03-08 22:40:153488 {
Greg Clayton144f3a92011-11-15 03:53:303489 ProcessInstanceInfoList process_infos;
3490 PlatformSP platform_sp (m_target.GetPlatform ());
3491
3492 if (platform_sp)
3493 {
3494 ProcessInstanceInfoMatch match_info;
3495 match_info.GetProcessInfo() = attach_info;
3496 match_info.SetNameMatchType (eNameMatchEquals);
3497 platform_sp->FindProcesses (match_info, process_infos);
3498 const uint32_t num_matches = process_infos.GetSize();
3499 if (num_matches == 1)
3500 {
3501 attach_pid = process_infos.GetProcessIDAtIndex(0);
3502 // Fall through and attach using the above process ID
3503 }
3504 else
3505 {
3506 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3507 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:273508 {
3509 StreamString s;
3510 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3511 for (size_t i = 0; i < num_matches; i++)
3512 {
3513 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3514 }
3515 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3516 process_name,
3517 s.GetData());
3518 }
Greg Clayton144f3a92011-11-15 03:53:303519 else
3520 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3521 }
3522 }
3523 else
3524 {
3525 error.SetErrorString ("invalid platform, can't find processes by name");
3526 return error;
3527 }
Greg Claytone996fd32011-03-08 22:40:153528 }
Chris Lattner30fdc8d2010-06-08 16:52:243529 }
3530 else
Greg Clayton144f3a92011-11-15 03:53:303531 {
3532 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:153533 }
3534 }
Greg Clayton144f3a92011-11-15 03:53:303535
3536 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:153537 {
Greg Clayton144f3a92011-11-15 03:53:303538 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:153539 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:243540 {
Greg Clayton144f3a92011-11-15 03:53:303541
Ed Maste64fad602013-07-29 20:58:063542 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:123543 {
3544 // Now attach using these arguments.
3545 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:163546 const bool restarted = false;
3547 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:123548 error = DoAttachToProcessWithID (attach_pid, attach_info);
3549 }
3550 else
3551 {
3552 // This shouldn't happen
3553 error.SetErrorString("failed to acquire process run lock");
3554 }
3555
Greg Clayton144f3a92011-11-15 03:53:303556 if (error.Success())
3557 {
3558
3559 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3560 StartPrivateStateThread();
3561 }
3562 else
Greg Claytone996fd32011-03-08 22:40:153563 {
3564 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:153565 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:153566
Oleksiy Vyalov5d064742014-11-19 18:27:453567 const char *error_string = error.AsCString();
3568 if (error_string == NULL)
3569 error_string = "attach failed";
3570
3571 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:153572 }
Chris Lattner30fdc8d2010-06-08 16:52:243573 }
3574 }
3575 return error;
3576}
3577
Greg Clayton93d3c8332011-02-16 04:46:073578void
3579Process::CompleteAttach ()
3580{
Todd Fiala76e0fc92014-08-27 22:58:263581 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3582 if (log)
3583 log->Printf ("Process::%s()", __FUNCTION__);
3584
Greg Clayton93d3c8332011-02-16 04:46:073585 // Let the process subclass figure out at much as it can about the process
3586 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce22014-08-02 00:33:353587 ArchSpec process_arch;
3588 DidAttach(process_arch);
3589
3590 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:263591 {
Jim Inghambb006ce22014-08-02 00:33:353592 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:263593 if (log)
3594 {
3595 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3596 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3597 __FUNCTION__,
3598 triple_str ? triple_str : "<null>");
3599 }
3600 }
Greg Clayton93d3c8332011-02-16 04:46:073601
Jim Ingham4299fdb2011-09-15 01:10:173602 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3603 // the same as the one we've already set, switch architectures.
3604 PlatformSP platform_sp (m_target.GetPlatform ());
3605 assert (platform_sp.get());
3606 if (platform_sp)
3607 {
Greg Clayton70512312012-05-08 01:45:383608 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:543609 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:383610 {
3611 ArchSpec platform_arch;
3612 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3613 if (platform_sp)
3614 {
3615 m_target.SetPlatform (platform_sp);
3616 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:263617 if (log)
3618 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:383619 }
3620 }
Jim Inghambb006ce22014-08-02 00:33:353621 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:383622 {
3623 ProcessInstanceInfo process_info;
3624 platform_sp->GetProcessInfo (GetID(), process_info);
3625 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:143626 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:263627 {
Greg Clayton70512312012-05-08 01:45:383628 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:263629 if (log)
3630 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 ());
3631 }
Greg Clayton70512312012-05-08 01:45:383632 }
Jim Ingham4299fdb2011-09-15 01:10:173633 }
3634
3635 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:073636 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:393637 DynamicLoader *dyld = GetDynamicLoader ();
3638 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:263639 {
Greg Claytonc859e2d2012-02-13 23:10:393640 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:263641 if (log)
3642 {
3643 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3644 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3645 __FUNCTION__,
3646 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3647 dyld->GetPluginName().AsCString ("<unnamed>"));
3648 }
3649 }
Greg Clayton93d3c8332011-02-16 04:46:073650
Andrew MacPhersoneb4d0602014-03-13 09:37:023651 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:433652
Jason Molendaeef51062013-11-05 03:57:193653 SystemRuntime *system_runtime = GetSystemRuntime ();
3654 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:263655 {
Jason Molendaeef51062013-11-05 03:57:193656 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:263657 if (log)
3658 {
3659 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3660 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3661 __FUNCTION__,
3662 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3663 system_runtime->GetPluginName().AsCString("<unnamed>"));
3664 }
3665 }
Jason Molendaeef51062013-11-05 03:57:193666
Greg Clayton56d9a1b2011-08-22 02:49:393667 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:073668 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:023669 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:253670 Mutex::Locker modules_locker(target_modules.GetMutex());
3671 size_t num_modules = target_modules.GetSize();
3672 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:073673
Andy Gibbsa297a972013-06-19 19:04:533674 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:073675 {
Jim Ingham3ee12ef2012-05-30 02:19:253676 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:463677 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:073678 {
Greg Claytonaa149cb2011-08-11 02:48:453679 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:253680 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:073681 break;
3682 }
3683 }
Jim Ingham3ee12ef2012-05-30 02:19:253684 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:263685 {
Jim Ingham3ee12ef2012-05-30 02:19:253686 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:263687 if (log)
3688 {
3689 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3690 log->Printf ("Process::%s after looping through modules, target executable is %s",
3691 __FUNCTION__,
3692 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3693 }
3694 }
Greg Claytona97c4d22014-12-09 23:31:023695
3696 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:073697}
3698
Chris Lattner30fdc8d2010-06-08 16:52:243699Error
Jason Molenda4bd4e7e2012-09-29 04:02:013700Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:073701{
Greg Claytonb766a732011-02-04 01:58:073702 m_abi_sp.reset();
3703 m_process_input_reader.reset();
3704
3705 // Find the process and its architecture. Make sure it matches the architecture
3706 // of the current Target, and if not adjust it.
3707
Jason Molenda4bd4e7e2012-09-29 04:02:013708 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:073709 if (error.Success())
3710 {
Greg Clayton71337622011-02-24 22:24:293711 if (GetID() != LLDB_INVALID_PROCESS_ID)
3712 {
Greg Clayton32e0a752011-03-30 18:16:513713 EventSP event_sp;
3714 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3715
3716 if (state == eStateStopped || state == eStateCrashed)
3717 {
3718 // If we attached and actually have a process on the other end, then
3719 // this ended up being the equivalent of an attach.
3720 CompleteAttach ();
3721
3722 // This delays passing the stopped event to listeners till
3723 // CompleteAttach gets a chance to complete...
3724 HandlePrivateEvent (event_sp);
3725
3726 }
Greg Clayton71337622011-02-24 22:24:293727 }
Greg Clayton32e0a752011-03-30 18:16:513728
3729 if (PrivateStateThreadIsValid ())
3730 ResumePrivateStateThread ();
3731 else
3732 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:073733 }
3734 return error;
3735}
3736
3737
3738Error
Jim Ingham3b8285d2012-04-19 01:40:333739Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:243740{
Greg Clayton5160ce52013-03-27 23:08:403741 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:243742 if (log)
Jim Ingham0161b492013-02-09 01:29:053743 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:223744 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:173745 StateAsCString(m_public_state.GetValue()),
3746 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:243747
3748 Error error (WillResume());
3749 // Tell the process it is about to resume before the thread list
3750 if (error.Success())
3751 {
Johnny Chenc4221e42010-12-02 20:53:053752 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:243753 // can let all of our threads know that they are about to be
3754 // resumed. Threads will each be called with
3755 // Thread::WillResume(StateType) where StateType contains the state
3756 // that they are supposed to have when the process is resumed
3757 // (suspended/running/stepping). Threads should also check
3758 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:163759 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:243760 if (m_thread_list.WillResume())
3761 {
Jim Ingham372787f2012-04-07 00:00:413762 // Last thing, do the PreResumeActions.
3763 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:243764 {
Jim Ingham0161b492013-02-09 01:29:053765 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:413766 }
3767 else
3768 {
3769 m_mod_id.BumpResumeID();
3770 error = DoResume();
3771 if (error.Success())
3772 {
3773 DidResume();
3774 m_thread_list.DidResume();
3775 if (log)
3776 log->Printf ("Process thinks the process has resumed.");
3777 }
Chris Lattner30fdc8d2010-06-08 16:52:243778 }
3779 }
3780 else
3781 {
Jim Inghamd5ac1ab2015-01-19 23:51:513782 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3783 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:413784 // and let the world handle them.
3785 if (log)
3786 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3787
3788 SetPrivateState(eStateRunning);
3789 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:243790 }
3791 }
Jim Ingham444586b2011-01-24 06:34:173792 else if (log)
Jim Ingham0161b492013-02-09 01:29:053793 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:243794 return error;
3795}
3796
3797Error
Greg Claytonf9b57b92013-05-10 23:48:103798Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:243799{
Greg Claytonf9b57b92013-05-10 23:48:103800 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3801 // in case it was already set and some thread plan logic calls halt on its
3802 // own.
3803 m_clear_thread_plans_on_stop |= clear_thread_plans;
3804
Jim Inghamaacc3182012-06-06 00:29:303805 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3806 // we could just straightaway get another event. It just narrows the window...
3807 m_currently_handling_event.WaitForValueEqualTo(false);
3808
3809
Jim Inghambb3a2832011-01-29 01:49:253810 // Pause our private state thread so we can ensure no one else eats
3811 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:593812 Listener halt_listener ("lldb.process.halt_listener");
3813 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:033814
Jim Inghambb3a2832011-01-29 01:49:253815 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:553816 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:253817
Greg Clayton06357c92014-07-30 17:38:473818 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:553819 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:253820 {
Jim Inghambb3a2832011-01-29 01:49:253821
Greg Clayton513c26c2011-01-29 07:10:553822 bool caused_stop = false;
3823
3824 // Ask the process subclass to actually halt our process
3825 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:243826 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:003827 {
Greg Clayton513c26c2011-01-29 07:10:553828 if (m_public_state.GetValue() == eStateAttaching)
3829 {
Greg Clayton06357c92014-07-30 17:38:473830 // Don't hijack and eat the eStateExited as the code that was doing
3831 // the attach will be waiting for this event...
3832 RestorePrivateProcessEvents();
3833 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:553834 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:583835 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:553836 }
3837 else
Jim Ingham0d8bcc72010-11-17 02:32:003838 {
Jim Inghambb3a2832011-01-29 01:49:253839 // If "caused_stop" is true, then DoHalt stopped the process. If
3840 // "caused_stop" is false, the process was already stopped.
3841 // If the DoHalt caused the process to stop, then we want to catch
3842 // this event and set the interrupted bool to true before we pass
3843 // this along so clients know that the process was interrupted by
3844 // a halt command.
3845 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:033846 {
Jim Ingham0f16e732011-02-08 05:20:593847 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:253848 TimeValue timeout_time;
3849 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:433850 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:593851 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3852 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:253853
Jim Ingham0f16e732011-02-08 05:20:593854 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:033855 {
Jim Inghambb3a2832011-01-29 01:49:253856 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:593857 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:033858 }
3859 else
3860 {
Greg Clayton2637f822011-11-17 01:23:073861 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:253862 {
3863 // We caused the process to interrupt itself, so mark this
3864 // as such in the stop event so clients can tell an interrupted
3865 // process from a natural stop
3866 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3867 }
3868 else
3869 {
Greg Clayton5160ce52013-03-27 23:08:403870 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:253871 if (log)
3872 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3873 error.SetErrorString ("Did not get stopped event after halt.");
3874 }
Greg Clayton3af9ea52010-11-18 05:57:033875 }
3876 }
Jim Inghambb3a2832011-01-29 01:49:253877 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:003878 }
3879 }
Chris Lattner30fdc8d2010-06-08 16:52:243880 }
Jim Inghambb3a2832011-01-29 01:49:253881 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:473882 if (!restored_process_events)
3883 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:253884
3885 // Post any event we might have consumed. If all goes well, we will have
3886 // stopped the process, intercepted the event and set the interrupted
3887 // bool in the event. Post it to the private event queue and that will end up
3888 // correctly setting the state.
3889 if (event_sp)
3890 m_private_state_broadcaster.BroadcastEvent(event_sp);
3891
Chris Lattner30fdc8d2010-06-08 16:52:243892 return error;
3893}
3894
3895Error
Jim Ingham8af3b9c2013-03-29 01:18:123896Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3897{
3898 Error error;
3899 if (m_public_state.GetValue() == eStateRunning)
3900 {
3901 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3902 if (log)
3903 log->Printf("Process::Destroy() About to halt.");
3904 error = Halt();
3905 if (error.Success())
3906 {
3907 // Consume the halt event.
3908 TimeValue timeout (TimeValue::Now());
3909 timeout.OffsetWithSeconds(1);
3910 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3911
3912 // If the process exited while we were waiting for it to stop, put the exited event into
3913 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3914 // they don't have a process anymore...
3915
3916 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3917 {
3918 if (log)
3919 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3920 return error;
3921 }
3922 else
3923 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3924
3925 if (state != eStateStopped)
3926 {
3927 if (log)
3928 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3929 // If we really couldn't stop the process then we should just error out here, but if the
3930 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3931 StateType private_state = m_private_state.GetValue();
3932 if (private_state != eStateStopped)
3933 {
3934 return error;
3935 }
3936 }
3937 }
3938 else
3939 {
3940 if (log)
3941 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3942 }
3943 }
3944 return error;
3945}
3946
3947Error
Jim Inghamacff8952013-05-02 00:27:303948Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:243949{
Jim Ingham8af3b9c2013-03-29 01:18:123950 EventSP exit_event_sp;
3951 Error error;
3952 m_destroy_in_process = true;
3953
3954 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:243955
3956 if (error.Success())
3957 {
Jim Ingham8af3b9c2013-03-29 01:18:123958 if (DetachRequiresHalt())
3959 {
3960 error = HaltForDestroyOrDetach (exit_event_sp);
3961 if (!error.Success())
3962 {
3963 m_destroy_in_process = false;
3964 return error;
3965 }
3966 else if (exit_event_sp)
3967 {
3968 // We shouldn't need to do anything else here. There's no process left to detach from...
3969 StopPrivateStateThread();
3970 m_destroy_in_process = false;
3971 return error;
3972 }
3973 }
3974
Andrew MacPhersonc3826b52014-03-25 19:59:363975 m_thread_list.DiscardThreadPlans();
3976 DisableAllBreakpointSites();
3977
Jim Inghamacff8952013-05-02 00:27:303978 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:243979 if (error.Success())
3980 {
3981 DidDetach();
3982 StopPrivateStateThread();
3983 }
Jim Inghamacff8952013-05-02 00:27:303984 else
3985 {
3986 return error;
3987 }
Chris Lattner30fdc8d2010-06-08 16:52:243988 }
Jim Ingham8af3b9c2013-03-29 01:18:123989 m_destroy_in_process = false;
3990
3991 // If we exited when we were waiting for a process to stop, then
3992 // forward the event here so we don't lose the event
3993 if (exit_event_sp)
3994 {
3995 // Directly broadcast our exited event because we shut down our
3996 // private state thread above
3997 BroadcastEvent(exit_event_sp);
3998 }
3999
4000 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4001 // the last events through the event system, in which case we might strand the write lock. Unlock
4002 // it here so when we do to tear down the process we don't get an error destroying the lock.
4003
Ed Maste64fad602013-07-29 20:58:064004 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:244005 return error;
4006}
4007
4008Error
Jason Molendaede31932015-04-17 05:01:584009Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:244010{
Jim Ingham09437922013-03-01 20:04:254011
4012 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
4013 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
4014 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:584015
4016 if (force_kill)
4017 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:254018
Ilia Kfcc89a02015-03-26 07:08:474019 if (GetShouldDetach())
4020 {
4021 // FIXME: This will have to be a process setting:
4022 bool keep_stopped = false;
4023 Detach(keep_stopped);
4024 }
4025
Jim Ingham09437922013-03-01 20:04:254026 m_destroy_in_process = true;
4027
Chris Lattner30fdc8d2010-06-08 16:52:244028 Error error (WillDestroy());
4029 if (error.Success())
4030 {
Greg Clayton85fb1b92012-09-11 02:33:374031 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:124032 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:314033 {
Jim Ingham8af3b9c2013-03-29 01:18:124034 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:314035 }
Jim Ingham8af3b9c2013-03-29 01:18:124036
Jim Inghamaacc3182012-06-06 00:29:304037 if (m_public_state.GetValue() != eStateRunning)
4038 {
4039 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4040 // kill it, we don't want it hitting a breakpoint...
4041 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4042 // we're not going to have much luck doing this now.
4043 m_thread_list.DiscardThreadPlans();
4044 DisableAllBreakpointSites();
4045 }
Jim Ingham8af3b9c2013-03-29 01:18:124046
Chris Lattner30fdc8d2010-06-08 16:52:244047 error = DoDestroy();
4048 if (error.Success())
4049 {
4050 DidDestroy();
4051 StopPrivateStateThread();
4052 }
Caroline Ticeef5c6d02010-11-16 05:07:414053 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:014054 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:044055 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:244056
Caroline Ticeef5c6d02010-11-16 05:07:414057 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:244058 {
4059 m_process_input_reader->SetIsDone(true);
4060 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:414061 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:244062 }
4063
Greg Clayton85fb1b92012-09-11 02:33:374064 // If we exited when we were waiting for a process to stop, then
4065 // forward the event here so we don't lose the event
4066 if (exit_event_sp)
4067 {
4068 // Directly broadcast our exited event because we shut down our
4069 // private state thread above
4070 BroadcastEvent(exit_event_sp);
4071 }
4072
Jim Inghamb1e2e842012-04-12 18:49:314073 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4074 // the last events through the event system, in which case we might strand the write lock. Unlock
4075 // 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:064076 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:244077 }
Jim Ingham09437922013-03-01 20:04:254078
4079 m_destroy_in_process = false;
4080
Chris Lattner30fdc8d2010-06-08 16:52:244081 return error;
4082}
4083
4084Error
4085Process::Signal (int signal)
4086{
4087 Error error (WillSignal());
4088 if (error.Success())
4089 {
4090 error = DoSignal(signal);
4091 if (error.Success())
4092 DidSignal();
4093 }
4094 return error;
4095}
4096
Zachary Turner93749ab2015-03-03 21:51:254097void
4098Process::SetUnixSignals (const UnixSignalsSP &signals_sp)
4099{
4100 assert (signals_sp && "null signals_sp");
4101 m_unix_signals_sp = signals_sp;
4102}
4103
Chaoren Lin98d0a4b2015-07-14 01:09:284104const lldb::UnixSignalsSP &
Zachary Turner93749ab2015-03-03 21:51:254105Process::GetUnixSignals ()
4106{
4107 assert (m_unix_signals_sp && "null m_unix_signals_sp");
Chaoren Lin98d0a4b2015-07-14 01:09:284108 return m_unix_signals_sp;
Zachary Turner93749ab2015-03-03 21:51:254109}
4110
Greg Clayton514487e2011-02-15 21:59:324111lldb::ByteOrder
4112Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:244113{
Greg Clayton514487e2011-02-15 21:59:324114 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:244115}
4116
4117uint32_t
Greg Clayton514487e2011-02-15 21:59:324118Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:244119{
Greg Clayton514487e2011-02-15 21:59:324120 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:244121}
4122
Greg Clayton514487e2011-02-15 21:59:324123
Chris Lattner30fdc8d2010-06-08 16:52:244124bool
4125Process::ShouldBroadcastEvent (Event *event_ptr)
4126{
4127 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4128 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:404129 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:054130
Chris Lattner30fdc8d2010-06-08 16:52:244131 switch (state)
4132 {
Chris Lattner30fdc8d2010-06-08 16:52:244133 case eStateDetached:
4134 case eStateExited:
4135 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:414136 m_stdio_communication.SynchronizeWithReadThread();
4137 // fall-through
4138 case eStateConnected:
4139 case eStateAttaching:
4140 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:244141 // These events indicate changes in the state of the debugging session, always report them.
4142 return_value = true;
4143 break;
4144 case eStateInvalid:
4145 // We stopped for no apparent reason, don't report it.
4146 return_value = false;
4147 break;
4148 case eStateRunning:
4149 case eStateStepping:
4150 // If we've started the target running, we handle the cases where we
4151 // are already running and where there is a transition from stopped to
4152 // running differently.
4153 // running -> running: Automatically suppress extra running events
4154 // stopped -> running: Report except when there is one or more no votes
4155 // and no yes votes.
4156 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:594157 if (m_force_next_event_delivery)
4158 return_value = true;
4159 else
Chris Lattner30fdc8d2010-06-08 16:52:244160 {
Jim Ingham1460e4b2014-01-10 23:46:594161 switch (m_last_broadcast_state)
4162 {
4163 case eStateRunning:
4164 case eStateStepping:
4165 // We always suppress multiple runnings with no PUBLIC stop in between.
4166 return_value = false;
4167 break;
4168 default:
4169 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:114170 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:594171 // events. If I run the lldb/test/thread/a.out file and
4172 // break at main.cpp:58, run and hit the breakpoints on
4173 // multiple threads, then somehow during the stepping over
4174 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:244175
Jim Ingham1460e4b2014-01-10 23:46:594176 // This is a transition from stop to run.
4177 switch (m_thread_list.ShouldReportRun (event_ptr))
4178 {
4179 case eVoteYes:
4180 case eVoteNoOpinion:
4181 return_value = true;
4182 break;
4183 case eVoteNo:
4184 return_value = false;
4185 break;
4186 }
4187 break;
4188 }
Chris Lattner30fdc8d2010-06-08 16:52:244189 }
4190 break;
4191 case eStateStopped:
4192 case eStateCrashed:
4193 case eStateSuspended:
4194 {
4195 // We've stopped. First see if we're going to restart the target.
4196 // If we are going to stop, then we always broadcast the event.
4197 // 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:324198 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:164199
Pavel Labath3f5df532015-03-12 10:12:414200 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:144201 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:004202 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:244203 {
Greg Clayton3af9ea52010-11-18 05:57:034204 if (log)
Jim Ingham0161b492013-02-09 01:29:054205 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:104206 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:054207 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:214208 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4209 // so they can properly set their state.
4210 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:054211 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:004212 }
4213 else
4214 {
Jim Ingham221d51c2013-05-08 00:35:164215 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4216 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:104217
Jim Ingham0161b492013-02-09 01:29:054218 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4219 // Asking the thread list is also not likely to go well, since we are running again.
4220 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:104221
Jim Ingham0161b492013-02-09 01:29:054222 if (!was_restarted)
4223 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:104224
Jim Ingham221d51c2013-05-08 00:35:164225 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:244226 {
Jim Ingham0161b492013-02-09 01:29:054227 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4228 if (log)
4229 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:104230 should_resume, StateAsCString(state),
4231 was_restarted, stop_vote);
4232
Jim Ingham0161b492013-02-09 01:29:054233 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:244234 {
4235 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:054236 return_value = true;
4237 break;
Chris Lattner30fdc8d2010-06-08 16:52:244238 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:244239 case eVoteNo:
4240 return_value = false;
4241 break;
4242 }
Saleem Abdulrasool324a1032014-04-04 04:06:104243
Jim Inghamcb95f342012-09-05 21:13:564244 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:054245 {
4246 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104247 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4248 static_cast<void*>(event_ptr),
4249 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:054250 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:564251 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:054252 }
Saleem Abdulrasool324a1032014-04-04 04:06:104253
Chris Lattner30fdc8d2010-06-08 16:52:244254 }
4255 else
4256 {
4257 return_value = true;
4258 SynchronouslyNotifyStateChanged (state);
4259 }
4260 }
4261 }
Jim Ingham0161b492013-02-09 01:29:054262 break;
Chris Lattner30fdc8d2010-06-08 16:52:244263 }
Saleem Abdulrasool324a1032014-04-04 04:06:104264
Jim Ingham1460e4b2014-01-10 23:46:594265 // Forcing the next event delivery is a one shot deal. So reset it here.
4266 m_force_next_event_delivery = false;
4267
Jim Ingham0161b492013-02-09 01:29:054268 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4269 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4270 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4271 // because the PublicState reflects the last event pulled off the queue, and there may be several
4272 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4273 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:104274
Jim Ingham0161b492013-02-09 01:29:054275 if (return_value)
4276 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:104277
Chris Lattner30fdc8d2010-06-08 16:52:244278 if (log)
Jim Ingham0161b492013-02-09 01:29:054279 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:104280 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:054281 StateAsCString(m_last_broadcast_state),
4282 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:244283 return return_value;
4284}
4285
Chris Lattner30fdc8d2010-06-08 16:52:244286
4287bool
Jim Ingham60c915e2015-06-23 21:02:454288Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:244289{
Greg Clayton5160ce52013-03-27 23:08:404290 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:244291
Greg Clayton8b82f082011-04-12 05:54:464292 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:244293 if (log)
Greg Clayton8b82f082011-04-12 05:54:464294 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4295
Jim Ingham60c915e2015-06-23 21:02:454296 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:464297 return true;
Chris Lattner30fdc8d2010-06-08 16:52:244298
4299 // Create a thread that watches our internal state and controls which
4300 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:354301 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:164302
Zachary Turner39de3112014-09-09 20:54:564303 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:164304 {
Zachary Turner39de3112014-09-09 20:54:564305 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4306 if (already_running)
4307 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4308 else
4309 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:164310 }
Jim Ingham372787f2012-04-07 00:00:414311 else
Todd Fiala17096d72014-07-16 19:03:164312 {
4313 if (already_running)
Zachary Turner39de3112014-09-09 20:54:564314 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:164315 else
Zachary Turner39de3112014-09-09 20:54:564316 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:164317 }
4318
Jim Ingham076b3042012-04-10 01:21:574319 // Create the private state thread, and start it running.
Jim Ingham60c915e2015-06-23 21:02:454320 PrivateStateThreadArgs args = {this, is_secondary_thread};
4321 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) &args, NULL);
Zachary Turneracee96a2014-09-23 18:32:094322 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:574323 {
4324 ResumePrivateStateThread();
4325 return true;
4326 }
4327 else
4328 return false;
Chris Lattner30fdc8d2010-06-08 16:52:244329}
4330
4331void
4332Process::PausePrivateStateThread ()
4333{
4334 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4335}
4336
4337void
4338Process::ResumePrivateStateThread ()
4339{
4340 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4341}
4342
4343void
4344Process::StopPrivateStateThread ()
4345{
Greg Clayton8b82f082011-04-12 05:54:464346 if (PrivateStateThreadIsValid ())
4347 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:314348 else
4349 {
Greg Clayton5160ce52013-03-27 23:08:404350 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:314351 if (log)
Jim Ingham0161b492013-02-09 01:29:054352 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:314353 }
Chris Lattner30fdc8d2010-06-08 16:52:244354}
4355
4356void
4357Process::ControlPrivateStateThread (uint32_t signal)
4358{
Greg Clayton5160ce52013-03-27 23:08:404359 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:244360
4361 assert (signal == eBroadcastInternalStateControlStop ||
4362 signal == eBroadcastInternalStateControlPause ||
4363 signal == eBroadcastInternalStateControlResume);
4364
4365 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:174366 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:244367
Greg Clayton7ecb3a02011-01-22 17:43:174368 // Signal the private state thread. First we should copy this is case the
4369 // thread starts exiting since the private state thread will NULL this out
4370 // when it exits
Zachary Turner39de3112014-09-09 20:54:564371 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:094372 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:244373 {
4374 TimeValue timeout_time;
4375 bool timed_out;
4376
4377 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4378
4379 timeout_time = TimeValue::Now();
4380 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:314381 if (log)
4382 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:244383 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4384 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4385
4386 if (signal == eBroadcastInternalStateControlStop)
4387 {
4388 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:314389 {
Zachary Turner39de3112014-09-09 20:54:564390 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:314391 if (log)
4392 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4393 }
4394 else
4395 {
4396 if (log)
4397 log->Printf ("The control event killed the private state thread without having to cancel.");
4398 }
Chris Lattner30fdc8d2010-06-08 16:52:244399
4400 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:564401 private_state_thread.Join(&result);
4402 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:244403 }
4404 }
Jim Inghamb1e2e842012-04-12 18:49:314405 else
4406 {
4407 if (log)
4408 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4409 }
Chris Lattner30fdc8d2010-06-08 16:52:244410}
4411
4412void
Jim Inghamcfc09352012-07-27 23:57:194413Process::SendAsyncInterrupt ()
4414{
4415 if (PrivateStateThreadIsValid())
4416 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4417 else
4418 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4419}
4420
4421void
Chris Lattner30fdc8d2010-06-08 16:52:244422Process::HandlePrivateEvent (EventSP &event_sp)
4423{
Greg Clayton5160ce52013-03-27 23:08:404424 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:164425 m_resume_requested = false;
4426
Jim Inghamaacc3182012-06-06 00:29:304427 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:254428
Greg Clayton414f5d32011-01-25 02:58:484429 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:254430
4431 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:414432 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:254433 {
Jim Ingham754ab982011-01-29 04:05:414434 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:054435 if (log)
4436 log->Printf ("Ran next event action, result was %d.", action_result);
4437
Jim Inghambb3a2832011-01-29 01:49:254438 switch (action_result)
4439 {
4440 case NextEventAction::eEventActionSuccess:
4441 SetNextEventAction(NULL);
4442 break;
Greg Claytonc9ed4782011-11-12 02:10:564443
Jim Inghambb3a2832011-01-29 01:49:254444 case NextEventAction::eEventActionRetry:
4445 break;
Greg Claytonc9ed4782011-11-12 02:10:564446
Jim Inghambb3a2832011-01-29 01:49:254447 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:314448 // Handle Exiting Here. If we already got an exited event,
4449 // we should just propagate it. Otherwise, swallow this event,
4450 // and set our state to exit so the next event will kill us.
4451 if (new_state != eStateExited)
4452 {
4453 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:414454 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:164455 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:314456 SetNextEventAction(NULL);
4457 return;
4458 }
4459 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:254460 break;
4461 }
4462 }
4463
Chris Lattner30fdc8d2010-06-08 16:52:244464 // See if we should broadcast this state to external clients?
4465 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:244466
4467 if (should_broadcast)
4468 {
Greg Claytonb4874f12014-02-28 18:22:244469 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:244470 if (log)
4471 {
Daniel Malead01b2952012-11-29 21:49:154472 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:484473 __FUNCTION__,
4474 GetID(),
4475 StateAsCString(new_state),
4476 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:244477 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:244478 }
Jim Ingham9575d842011-03-11 03:53:594479 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:484480 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:244481 {
4482 // Only push the input handler if we aren't fowarding events,
4483 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:214484 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:174485 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4486 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:324487 {
Greg Clayton44d93782014-01-27 23:43:244488 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:324489 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4490 if (log)
4491 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4492 }
Greg Clayton44d93782014-01-27 23:43:244493 }
Greg Claytonb4874f12014-02-28 18:22:244494 else if (StateIsStoppedState(new_state, false))
4495 {
Greg Claytonb4874f12014-02-28 18:22:244496 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4497 {
4498 // If the lldb_private::Debugger is handling the events, we don't
4499 // want to pop the process IOHandler here, we want to do it when
4500 // we receive the stopped event so we can carefully control when
4501 // the process IOHandler is popped because when we stop we want to
4502 // display some text stating how and why we stopped, then maybe some
4503 // process/thread/frame info, and then we want the "(lldb) " prompt
4504 // to show up. If we pop the process IOHandler here, then we will
4505 // cause the command interpreter to become the top IOHandler after
4506 // the process pops off and it will update its prompt right away...
4507 // See the Debugger.cpp file where it calls the function as
4508 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4509 // Otherwise we end up getting overlapping "(lldb) " prompts and
4510 // garbled output.
4511 //
4512 // If we aren't handling the events in the debugger (which is indicated
4513 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4514 // are hijacked, then we always pop the process IO handler manually.
4515 // Hijacking happens when the internal process state thread is running
4516 // thread plans, or when commands want to run in synchronous mode
4517 // and they call "process->WaitForProcessToStop()". An example of something
4518 // that will hijack the events is a simple expression:
4519 //
4520 // (lldb) expr (int)puts("hello")
4521 //
4522 // This will cause the internal process state thread to resume and halt
4523 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4524 // events) and we do need the IO handler to be pushed and popped
4525 // correctly.
4526
4527 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4528 PopProcessIOHandler ();
4529 }
4530 }
Jim Ingham9575d842011-03-11 03:53:594531
Chris Lattner30fdc8d2010-06-08 16:52:244532 BroadcastEvent (event_sp);
4533 }
4534 else
4535 {
4536 if (log)
4537 {
Daniel Malead01b2952012-11-29 21:49:154538 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:484539 __FUNCTION__,
4540 GetID(),
4541 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:104542 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:244543 }
4544 }
Jim Inghamaacc3182012-06-06 00:29:304545 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:244546}
4547
Virgile Bellob2f1fb22013-08-23 12:44:054548thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:244549Process::PrivateStateThread (void *arg)
4550{
Jim Ingham60c915e2015-06-23 21:02:454551 PrivateStateThreadArgs *real_args = static_cast<PrivateStateThreadArgs *> (arg);
4552 thread_result_t result = real_args->process->RunPrivateStateThread(real_args->is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:244553 return result;
4554}
4555
Virgile Bellob2f1fb22013-08-23 12:44:054556thread_result_t
Jim Ingham60c915e2015-06-23 21:02:454557Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:244558{
Jim Ingham076b3042012-04-10 01:21:574559 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:314560 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:244561
Greg Clayton5160ce52013-03-27 23:08:404562 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:244563 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104564 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4565 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:244566
4567 bool exit_now = false;
4568 while (!exit_now)
4569 {
4570 EventSP event_sp;
4571 WaitForEventsPrivate (NULL, event_sp, control_only);
4572 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4573 {
Jim Inghamb1e2e842012-04-12 18:49:314574 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104575 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4576 __FUNCTION__, static_cast<void*>(this), GetID(),
4577 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:314578
Chris Lattner30fdc8d2010-06-08 16:52:244579 switch (event_sp->GetType())
4580 {
4581 case eBroadcastInternalStateControlStop:
4582 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:114583 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:244584
4585 case eBroadcastInternalStateControlPause:
4586 control_only = true;
4587 break;
4588
4589 case eBroadcastInternalStateControlResume:
4590 control_only = false;
4591 break;
4592 }
Saleem Abdulrasool324a1032014-04-04 04:06:104593
Chris Lattner30fdc8d2010-06-08 16:52:244594 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:004595 continue;
Chris Lattner30fdc8d2010-06-08 16:52:244596 }
Jim Inghamcfc09352012-07-27 23:57:194597 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4598 {
4599 if (m_public_state.GetValue() == eStateAttaching)
4600 {
4601 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104602 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4603 __FUNCTION__, static_cast<void*>(this),
4604 GetID());
Jim Inghamcfc09352012-07-27 23:57:194605 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4606 }
4607 else
4608 {
4609 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104610 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4611 __FUNCTION__, static_cast<void*>(this),
4612 GetID());
Jim Inghamcfc09352012-07-27 23:57:194613 Halt();
4614 }
4615 continue;
4616 }
Chris Lattner30fdc8d2010-06-08 16:52:244617
4618 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4619
4620 if (internal_state != eStateInvalid)
4621 {
Greg Claytonf9b57b92013-05-10 23:48:104622 if (m_clear_thread_plans_on_stop &&
4623 StateIsStoppedState(internal_state, true))
4624 {
4625 m_clear_thread_plans_on_stop = false;
4626 m_thread_list.DiscardThreadPlans();
4627 }
Chris Lattner30fdc8d2010-06-08 16:52:244628 HandlePrivateEvent (event_sp);
4629 }
4630
Greg Clayton58d1c9a2010-10-18 04:14:234631 if (internal_state == eStateInvalid ||
4632 internal_state == eStateExited ||
4633 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:004634 {
Jim Ingham0d8bcc72010-11-17 02:32:004635 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104636 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4637 __FUNCTION__, static_cast<void*>(this), GetID(),
4638 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:004639
Chris Lattner30fdc8d2010-06-08 16:52:244640 break;
Jim Ingham0d8bcc72010-11-17 02:32:004641 }
Chris Lattner30fdc8d2010-06-08 16:52:244642 }
4643
Caroline Tice20ad3c42010-10-29 21:48:374644 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:244645 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:104646 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4647 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:244648
Jim Ingham60c915e2015-06-23 21:02:454649 // If we are a secondary thread, then the primary thread we are working for will have already
4650 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4651 // try to change it on the way out.
4652 if (!is_secondary_thread)
4653 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:454654 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:564655 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:244656 return NULL;
4657}
4658
Chris Lattner30fdc8d2010-06-08 16:52:244659//------------------------------------------------------------------
4660// Process Event Data
4661//------------------------------------------------------------------
4662
4663Process::ProcessEventData::ProcessEventData () :
4664 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:374665 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:244666 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:504667 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:014668 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:004669 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:244670{
4671}
4672
4673Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4674 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:374675 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:244676 m_state (state),
Greg Claytonc982c762010-07-09 20:39:504677 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:014678 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:004679 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:244680{
Greg Claytonaeb3b8b2015-05-29 03:20:374681 if (process_sp)
4682 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:244683}
4684
4685Process::ProcessEventData::~ProcessEventData()
4686{
4687}
4688
4689const ConstString &
4690Process::ProcessEventData::GetFlavorString ()
4691{
4692 static ConstString g_flavor ("Process::ProcessEventData");
4693 return g_flavor;
4694}
4695
4696const ConstString &
4697Process::ProcessEventData::GetFlavor () const
4698{
4699 return ProcessEventData::GetFlavorString ();
4700}
4701
Chris Lattner30fdc8d2010-06-08 16:52:244702void
4703Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4704{
Greg Claytonaeb3b8b2015-05-29 03:20:374705 ProcessSP process_sp(m_process_wp.lock());
4706
4707 if (!process_sp)
4708 return;
4709
Chris Lattner30fdc8d2010-06-08 16:52:244710 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:014711 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4712 // the public event queue, then other times when we're pretending that this is where we stopped at the
4713 // end of expression evaluation. m_update_state is used to distinguish these
4714 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:164715 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:014716 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:244717 return;
Jim Ingham0161b492013-02-09 01:29:054718
Greg Claytonaeb3b8b2015-05-29 03:20:374719 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:214720
4721 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4722 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4723 // end up restarting the process.
4724 if (m_interrupted)
4725 return;
4726
4727 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:244728 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:114729 {
Greg Claytonaeb3b8b2015-05-29 03:20:374730 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:384731 uint32_t num_threads = curr_thread_list.GetSize();
4732 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:354733
Jim Ingham4b536182011-08-09 02:12:224734 // The actions might change one of the thread's stop_info's opinions about whether we should
4735 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:114736
4737 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4738 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4739 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4740 // 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
4741 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:384742 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:114743 for (idx = 0; idx < num_threads; ++idx)
4744 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4745
Jim Inghamc7078c22012-12-13 22:24:154746 // Use this to track whether we should continue from here. We will only continue the target running if
4747 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4748 // then it doesn't matter what the other threads say...
4749
4750 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:224751
Jim Ingham0ad7e052013-04-25 02:04:594752 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4753 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4754 // thing to do is, and it's better to let the user decide than continue behind their backs.
4755
4756 bool does_anybody_have_an_opinion = false;
4757
Chris Lattner30fdc8d2010-06-08 16:52:244758 for (idx = 0; idx < num_threads; ++idx)
4759 {
Greg Claytonaeb3b8b2015-05-29 03:20:374760 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:114761 if (curr_thread_list.GetSize() != num_threads)
4762 {
Greg Clayton5160ce52013-03-27 23:08:404763 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:154764 if (log)
Greg Clayton61e7a582011-12-01 23:28:384765 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:114766 break;
4767 }
4768
4769 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4770
4771 if (thread_sp->GetIndexID() != thread_index_array[idx])
4772 {
Greg Clayton5160ce52013-03-27 23:08:404773 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:154774 if (log)
Greg Clayton61e7a582011-12-01 23:28:384775 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:154776 idx,
4777 thread_index_array[idx],
4778 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:114779 break;
4780 }
4781
Jim Inghamb15bfc72010-10-20 00:39:534782 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:334783 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:244784 {
Jim Ingham0ad7e052013-04-25 02:04:594785 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:054786 bool this_thread_wants_to_stop;
4787 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:224788 {
Jim Ingham0161b492013-02-09 01:29:054789 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4790 }
4791 else
4792 {
4793 stop_info_sp->PerformAction(event_ptr);
4794 // The stop action might restart the target. If it does, then we want to mark that in the
4795 // event so that whoever is receiving it will know to wait for the running event and reflect
4796 // that state appropriately.
4797 // We also need to stop processing actions, since they aren't expecting the target to be running.
4798
4799 // FIXME: we might have run.
4800 if (stop_info_sp->HasTargetRunSinceMe())
4801 {
4802 SetRestarted (true);
4803 break;
4804 }
4805
4806 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:224807 }
Jim Inghamc7078c22012-12-13 22:24:154808
Jim Inghamc7078c22012-12-13 22:24:154809 if (still_should_stop == false)
4810 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:244811 }
4812 }
Jim Ingham3ebcf7f2010-08-10 00:59:594813
Ashok Thirumurthicf7c55e2013-04-18 14:38:204814
Jim Inghama8ca6e22013-05-03 23:04:374815 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:594816 {
Jim Ingham0ad7e052013-04-25 02:04:594817 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:224818 {
4819 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:594820 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:334821 // Use the public resume method here, since this is just
4822 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:374823 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:224824 }
4825 else
4826 {
4827 // If we didn't restart, run the Stop Hooks here:
4828 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:374829 process_sp->GetTarget().RunStopHooks();
4830 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:224831 SetRestarted(true);
4832 }
Jim Ingham9575d842011-03-11 03:53:594833 }
Chris Lattner30fdc8d2010-06-08 16:52:244834 }
4835}
4836
4837void
4838Process::ProcessEventData::Dump (Stream *s) const
4839{
Greg Claytonaeb3b8b2015-05-29 03:20:374840 ProcessSP process_sp(m_process_wp.lock());
4841
4842 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:104843 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:374844 static_cast<void*>(process_sp.get()), process_sp->GetID());
4845 else
4846 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:244847
Greg Clayton8b82f082011-04-12 05:54:464848 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:244849}
4850
4851const Process::ProcessEventData *
4852Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4853{
4854 if (event_ptr)
4855 {
4856 const EventData *event_data = event_ptr->GetData();
4857 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4858 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4859 }
4860 return NULL;
4861}
4862
4863ProcessSP
4864Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4865{
4866 ProcessSP process_sp;
4867 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4868 if (data)
4869 process_sp = data->GetProcessSP();
4870 return process_sp;
4871}
4872
4873StateType
4874Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4875{
4876 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4877 if (data == NULL)
4878 return eStateInvalid;
4879 else
4880 return data->GetState();
4881}
4882
4883bool
4884Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4885{
4886 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4887 if (data == NULL)
4888 return false;
4889 else
4890 return data->GetRestarted();
4891}
4892
4893void
4894Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4895{
4896 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4897 if (data != NULL)
4898 data->SetRestarted(new_value);
4899}
4900
Jim Ingham0161b492013-02-09 01:29:054901size_t
4902Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4903{
4904 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4905 if (data != NULL)
4906 return data->GetNumRestartedReasons();
4907 else
4908 return 0;
4909}
4910
4911const char *
4912Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4913{
4914 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4915 if (data != NULL)
4916 return data->GetRestartedReasonAtIndex(idx);
4917 else
4918 return NULL;
4919}
4920
4921void
4922Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4923{
4924 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4925 if (data != NULL)
4926 data->AddRestartedReason(reason);
4927}
4928
Chris Lattner30fdc8d2010-06-08 16:52:244929bool
Jim Ingham0d8bcc72010-11-17 02:32:004930Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4931{
4932 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4933 if (data == NULL)
4934 return false;
4935 else
4936 return data->GetInterrupted ();
4937}
4938
4939void
4940Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4941{
4942 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4943 if (data != NULL)
4944 data->SetInterrupted(new_value);
4945}
4946
4947bool
Chris Lattner30fdc8d2010-06-08 16:52:244948Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4949{
4950 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4951 if (data)
4952 {
4953 data->SetUpdateStateOnRemoval();
4954 return true;
4955 }
4956 return false;
4957}
4958
Greg Claytond9e416c2012-02-18 05:35:264959lldb::TargetSP
4960Process::CalculateTarget ()
4961{
4962 return m_target.shared_from_this();
4963}
4964
Chris Lattner30fdc8d2010-06-08 16:52:244965void
Greg Clayton0603aa92010-10-04 01:05:564966Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:244967{
Greg Claytonc14ee322011-09-22 04:58:264968 exe_ctx.SetTargetPtr (&m_target);
4969 exe_ctx.SetProcessPtr (this);
4970 exe_ctx.SetThreadPtr(NULL);
4971 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:244972}
4973
Greg Claytone996fd32011-03-08 22:40:154974//uint32_t
4975//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4976//{
4977// return 0;
4978//}
4979//
4980//ArchSpec
4981//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4982//{
4983// return Host::GetArchSpecForExistingProcess (pid);
4984//}
4985//
4986//ArchSpec
4987//Process::GetArchSpecForExistingProcess (const char *process_name)
4988//{
4989// return Host::GetArchSpecForExistingProcess (process_name);
4990//}
4991//
Caroline Ticeef5c6d02010-11-16 05:07:414992void
4993Process::AppendSTDOUT (const char * s, size_t len)
4994{
Greg Clayton3af9ea52010-11-18 05:57:034995 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:414996 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:084997 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:414998}
4999
5000void
Greg Clayton93e86192011-11-13 04:45:225001Process::AppendSTDERR (const char * s, size_t len)
5002{
5003 Mutex::Locker locker (m_stdio_communication_mutex);
5004 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:085005 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:225006}
5007
Han Ming Ongab3b8b22012-11-17 00:21:045008void
Han Ming Ong91ed6b82013-06-24 18:15:055009Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:045010{
5011 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:055012 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:045013 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
5014}
5015
5016size_t
5017Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
5018{
5019 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:455020 if (m_profile_data.empty())
5021 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:055022
5023 std::string &one_profile_data = m_profile_data.front();
5024 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:045025 if (bytes_available > 0)
5026 {
Greg Clayton5160ce52013-03-27 23:08:405027 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:045028 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:105029 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5030 static_cast<void*>(buf),
5031 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:045032 if (bytes_available > buf_size)
5033 {
Han Ming Ong91ed6b82013-06-24 18:15:055034 memcpy(buf, one_profile_data.c_str(), buf_size);
5035 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:045036 bytes_available = buf_size;
5037 }
5038 else
5039 {
Han Ming Ong91ed6b82013-06-24 18:15:055040 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:455041 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:045042 }
5043 }
5044 return bytes_available;
5045}
5046
5047
Greg Clayton93e86192011-11-13 04:45:225048//------------------------------------------------------------------
5049// Process STDIO
5050//------------------------------------------------------------------
5051
5052size_t
5053Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5054{
5055 Mutex::Locker locker(m_stdio_communication_mutex);
5056 size_t bytes_available = m_stdout_data.size();
5057 if (bytes_available > 0)
5058 {
Greg Clayton5160ce52013-03-27 23:08:405059 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:225060 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:105061 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5062 static_cast<void*>(buf),
5063 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:225064 if (bytes_available > buf_size)
5065 {
5066 memcpy(buf, m_stdout_data.c_str(), buf_size);
5067 m_stdout_data.erase(0, buf_size);
5068 bytes_available = buf_size;
5069 }
5070 else
5071 {
5072 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5073 m_stdout_data.clear();
5074 }
5075 }
5076 return bytes_available;
5077}
5078
5079
5080size_t
5081Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5082{
5083 Mutex::Locker locker(m_stdio_communication_mutex);
5084 size_t bytes_available = m_stderr_data.size();
5085 if (bytes_available > 0)
5086 {
Greg Clayton5160ce52013-03-27 23:08:405087 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:225088 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:105089 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5090 static_cast<void*>(buf),
5091 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:225092 if (bytes_available > buf_size)
5093 {
5094 memcpy(buf, m_stderr_data.c_str(), buf_size);
5095 m_stderr_data.erase(0, buf_size);
5096 bytes_available = buf_size;
5097 }
5098 else
5099 {
5100 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5101 m_stderr_data.clear();
5102 }
5103 }
5104 return bytes_available;
5105}
5106
5107void
Caroline Ticeef5c6d02010-11-16 05:07:415108Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5109{
5110 Process *process = (Process *) baton;
5111 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5112}
5113
Greg Clayton44d93782014-01-27 23:43:245114class IOHandlerProcessSTDIO :
5115 public IOHandler
5116{
5117public:
5118 IOHandlerProcessSTDIO (Process *process,
5119 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:595120 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:245121 m_process (process),
5122 m_read_file (),
5123 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:395124 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:245125 {
Pavel Labathfb7d5b82015-05-28 13:41:085126 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:245127 m_read_file.SetDescriptor(GetInputFD(), false);
5128 }
5129
5130 virtual
5131 ~IOHandlerProcessSTDIO ()
5132 {
5133
5134 }
5135
Greg Clayton44d93782014-01-27 23:43:245136 // Each IOHandler gets to run until it is done. It should read data
5137 // from the "in" and place output into "out" and "err and return
5138 // when done.
Pavel Labath44464872015-05-27 12:40:325139 void
5140 Run () override
Greg Clayton44d93782014-01-27 23:43:245141 {
Pavel Labathfb7d5b82015-05-28 13:41:085142 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:245143 {
Pavel Labathfb7d5b82015-05-28 13:41:085144 SetIsDone(true);
5145 return;
5146 }
5147
5148 SetIsDone(false);
5149 const int read_fd = m_read_file.GetDescriptor();
5150 TerminalState terminal_state;
5151 terminal_state.Save (read_fd, false);
5152 Terminal terminal(read_fd);
5153 terminal.SetCanonical(false);
5154 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:465155// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:235156#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:085157 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5158 while (!GetIsDone())
5159 {
5160 fd_set read_fdset;
5161 FD_ZERO (&read_fdset);
5162 FD_SET (read_fd, &read_fdset);
5163 FD_SET (pipe_read_fd, &read_fdset);
5164 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5165 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5166 if (num_set_fds < 0)
5167 {
5168 const int select_errno = errno;
5169
5170 if (select_errno != EINTR)
5171 SetIsDone(true);
5172 }
5173 else if (num_set_fds > 0)
5174 {
5175 char ch = 0;
5176 size_t n;
5177 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:245178 {
Pavel Labathfb7d5b82015-05-28 13:41:085179 n = 1;
5180 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:245181 {
Pavel Labathfb7d5b82015-05-28 13:41:085182 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:245183 SetIsDone(true);
5184 }
Pavel Labathfb7d5b82015-05-28 13:41:085185 else
5186 SetIsDone(true);
5187 }
5188 if (FD_ISSET (pipe_read_fd, &read_fdset))
5189 {
5190 size_t bytes_read;
5191 // Consume the interrupt byte
5192 Error error = m_pipe.Read(&ch, 1, bytes_read);
5193 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:245194 {
Pavel Labathfb7d5b82015-05-28 13:41:085195 switch (ch)
Greg Clayton44d93782014-01-27 23:43:245196 {
Pavel Labathfb7d5b82015-05-28 13:41:085197 case 'q':
Greg Clayton44d93782014-01-27 23:43:245198 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:085199 break;
5200 case 'i':
5201 if (StateIsRunningState(m_process->GetState()))
5202 m_process->Halt();
5203 break;
Greg Clayton44d93782014-01-27 23:43:245204 }
5205 }
5206 }
Greg Clayton44d93782014-01-27 23:43:245207 }
Greg Clayton44d93782014-01-27 23:43:245208 }
Pavel Labathfb7d5b82015-05-28 13:41:085209#endif
5210 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:245211 }
5212
Pavel Labath44464872015-05-27 12:40:325213 void
5214 Cancel () override
Greg Clayton44d93782014-01-27 23:43:245215 {
Greg Clayton19e11352014-02-26 22:47:335216 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:195217 size_t bytes_written = 0;
5218 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:245219 }
Greg Claytone68f5d62014-02-24 22:50:575220
Pavel Labath44464872015-05-27 12:40:325221 bool
5222 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:575223 {
Greg Clayton19e11352014-02-26 22:47:335224 // Do only things that are safe to do in an interrupt context (like in
5225 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5226 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5227 // that was written to the pipe and then call m_process->Halt() from a
5228 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:415229 if (m_active)
5230 {
5231 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:195232 size_t bytes_written = 0;
5233 Error result = m_pipe.Write(&ch, 1, bytes_written);
5234 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:415235 }
5236 else
5237 {
5238 // This IOHandler might be pushed on the stack, but not being run currently
5239 // so do the right thing if we aren't actively watching for STDIN by sending
5240 // the interrupt to the process. Otherwise the write to the pipe above would
5241 // do nothing. This can happen when the command interpreter is running and
5242 // gets a "expression ...". It will be on the IOHandler thread and sending
5243 // the input is complete to the delegate which will cause the expression to
5244 // run, which will push the process IO handler, but not run it.
5245
5246 if (StateIsRunningState(m_process->GetState()))
5247 {
5248 m_process->SendAsyncInterrupt();
5249 return true;
5250 }
5251 }
5252 return false;
Greg Claytone68f5d62014-02-24 22:50:575253 }
Greg Clayton44d93782014-01-27 23:43:245254
Pavel Labath44464872015-05-27 12:40:325255 void
5256 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:245257 {
5258
5259 }
5260
5261protected:
5262 Process *m_process;
5263 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5264 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:395265 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:245266};
5267
Caroline Ticeef5c6d02010-11-16 05:07:415268void
Greg Clayton44d93782014-01-27 23:43:245269Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:415270{
5271 // First set up the Read Thread for reading/handling process I/O
5272
Greg Clayton44d93782014-01-27 23:43:245273 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:415274
5275 if (conn_ap.get())
5276 {
5277 m_stdio_communication.SetConnection (conn_ap.release());
5278 if (m_stdio_communication.IsConnected())
5279 {
5280 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5281 m_stdio_communication.StartReadThread();
5282
5283 // Now read thread is set up, set up input reader.
5284
5285 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:245286 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:415287 }
5288 }
5289}
5290
Greg Claytonb4874f12014-02-28 18:22:245291bool
Greg Clayton6fea17e2014-03-03 19:15:205292Process::ProcessIOHandlerIsActive ()
5293{
5294 IOHandlerSP io_handler_sp (m_process_input_reader);
5295 if (io_handler_sp)
5296 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5297 return false;
5298}
5299bool
Greg Clayton44d93782014-01-27 23:43:245300Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:415301{
Greg Clayton44d93782014-01-27 23:43:245302 IOHandlerSP io_handler_sp (m_process_input_reader);
5303 if (io_handler_sp)
5304 {
Pavel Labath44464872015-05-27 12:40:325305 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5306 if (log)
5307 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5308
Greg Clayton44d93782014-01-27 23:43:245309 io_handler_sp->SetIsDone(false);
5310 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:245311 return true;
Greg Clayton44d93782014-01-27 23:43:245312 }
Greg Claytonb4874f12014-02-28 18:22:245313 return false;
Caroline Ticeef5c6d02010-11-16 05:07:415314}
5315
Greg Claytonb4874f12014-02-28 18:22:245316bool
Greg Clayton44d93782014-01-27 23:43:245317Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:415318{
Greg Clayton44d93782014-01-27 23:43:245319 IOHandlerSP io_handler_sp (m_process_input_reader);
5320 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:245321 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5322 return false;
Caroline Ticeef5c6d02010-11-16 05:07:415323}
5324
Greg Claytonbfe5f3b2011-02-18 01:44:255325// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:355326void
Caroline Tice20bd37f2011-03-10 22:14:105327Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:465328{
Greg Clayton6920b522012-08-22 18:39:035329 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:355330}
Caroline Tice3df9a8d2010-09-04 00:03:465331
Greg Clayton99d0faf2010-11-18 23:32:355332void
Caroline Tice20bd37f2011-03-10 22:14:105333Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:255334{
Greg Clayton6920b522012-08-22 18:39:035335 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:355336}
Caroline Tice3df9a8d2010-09-04 00:03:465337
Jim Ingham1624a2d2014-05-05 02:26:405338ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:115339Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:415340 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:475341 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:115342 Stream &errors)
5343{
Jim Ingham8646d3c2014-05-05 02:47:445344 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:105345
Jim Ingham77787032011-01-20 02:03:185346 if (thread_plan_sp.get() == NULL)
5347 {
5348 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:445349 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:185350 }
Saleem Abdulrasool324a1032014-04-04 04:06:105351
Jim Ingham7d7931d2013-03-28 00:05:345352 if (!thread_plan_sp->ValidatePlan(NULL))
5353 {
5354 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:445355 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:345356 }
Saleem Abdulrasool324a1032014-04-04 04:06:105357
Greg Claytonc14ee322011-09-22 04:58:265358 if (exe_ctx.GetProcessPtr() != this)
5359 {
5360 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:445361 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:265362 }
5363
5364 Thread *thread = exe_ctx.GetThreadPtr();
5365 if (thread == NULL)
5366 {
5367 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:445368 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:265369 }
Saleem Abdulrasool324a1032014-04-04 04:06:105370
Jim Ingham17e5c4e2011-05-17 22:24:545371 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5372 // For that to be true the plan can't be private - since private plans suppress themselves in the
5373 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:105374
Jim Ingham17e5c4e2011-05-17 22:24:545375 bool orig_plan_private = thread_plan_sp->GetPrivate();
5376 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:105377
Jim Ingham444586b2011-01-24 06:34:175378 if (m_private_state.GetValue() != eStateStopped)
5379 {
5380 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:445381 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:175382 }
Saleem Abdulrasool324a1032014-04-04 04:06:105383
Jim Ingham66243842011-08-13 00:56:105384 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:265385 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a1b2013-11-04 09:33:305386 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:455387 if (!selected_frame_sp)
5388 {
5389 thread->SetSelectedFrame(0);
5390 selected_frame_sp = thread->GetSelectedFrame();
5391 if (!selected_frame_sp)
5392 {
5393 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:445394 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:455395 }
5396 }
Saleem Abdulrasool324a1032014-04-04 04:06:105397
Jim Ingham11b0e052013-02-19 23:22:455398 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:115399
5400 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5401 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:105402
Greg Claytonc14ee322011-09-22 04:58:265403 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:105404
Jim Ingham66243842011-08-13 00:56:105405 uint32_t selected_tid;
5406 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:155407 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:115408 {
5409 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:105410 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:115411 }
5412 else
5413 {
5414 selected_tid = LLDB_INVALID_THREAD_ID;
5415 }
5416
Zachary Turner39de3112014-09-09 20:54:565417 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:315418 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:575419 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:415420
Greg Clayton5160ce52013-03-27 23:08:405421 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:565422 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:415423 {
Jim Ingham076b3042012-04-10 01:21:575424 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5425 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:415426 // 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:575427 // we are fielding public events here.
5428 if (log)
Jason Molendad251c9d2012-11-17 01:41:045429 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Ingham076b3042012-04-10 01:21:575430
Jim Ingham372787f2012-04-07 00:00:415431 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:575432
5433 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5434 // returning control here.
5435 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5436 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5437 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5438 // do just what we want.
5439 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5440 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5441 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5442 old_state = m_public_state.GetValue();
5443 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:105444
Jim Ingham076b3042012-04-10 01:21:575445 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:415446 StartPrivateStateThread(true);
5447 }
Saleem Abdulrasool324a1032014-04-04 04:06:105448
Jim Ingham372787f2012-04-07 00:00:415449 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:105450
Jim Ingham6fbc48b2013-11-07 00:11:475451 if (options.GetDebug())
5452 {
5453 // In this case, we aren't actually going to run, we just want to stop right away.
5454 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5455 // FIXME: To make this prettier we should invent some stop reason for this, but that
5456 // is only cosmetic, and this functionality is only of use to lldb developers who can
5457 // live with not pretty...
5458 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:445459 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:475460 }
Saleem Abdulrasool324a1032014-04-04 04:06:105461
Jim Ingham1e7a9ee2011-01-23 21:14:085462 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:105463
Sean Callanana46ec452012-07-11 21:31:245464 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:105465
Jim Ingham77787032011-01-20 02:03:185466 {
Sean Callanana46ec452012-07-11 21:31:245467 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5468 // restored on exit to the function.
5469 //
5470 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5471 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:105472
Sean Callanana46ec452012-07-11 21:31:245473 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:105474
Jim Inghamf48169b2010-11-30 02:22:115475 if (log)
Jim Ingham0f16e732011-02-08 05:20:595476 {
5477 StreamString s;
Sean Callanana46ec452012-07-11 21:31:245478 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:155479 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:245480 thread->GetIndexID(),
5481 thread->GetID(),
5482 s.GetData());
5483 }
Saleem Abdulrasool324a1032014-04-04 04:06:105484
Sean Callanana46ec452012-07-11 21:31:245485 bool got_event;
5486 lldb::EventSP event_sp;
5487 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:105488
Sean Callanana46ec452012-07-11 21:31:245489 TimeValue* timeout_ptr = NULL;
5490 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:105491
Jim Ingham0161b492013-02-09 01:29:055492 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:245493 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:485494 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:585495 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:105496
Jim Ingham0161b492013-02-09 01:29:055497 // This is just for accounting:
5498 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:105499
Jim Ingham6fbc48b2013-11-07 00:11:475500 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:525501 uint32_t one_thread_timeout_usec;
5502 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:485503
5504 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5505 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5506 // first timeout already.
5507
5508 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:065509 {
5510 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:525511 one_thread_timeout_usec = 0;
5512 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:065513 }
Jim Inghamfe1c3422014-04-16 02:24:485514 else
Jim Ingham0161b492013-02-09 01:29:055515 {
Jim Inghamfd95f892014-04-22 01:41:525516 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:105517
Jim Ingham914f4e72014-03-28 21:58:285518 // If the overall wait is forever, then we only need to set the one thread timeout:
5519 if (timeout_usec == 0)
5520 {
Ed Maste801335c2014-03-31 19:28:145521 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:525522 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:285523 else
Jim Inghamfd95f892014-04-22 01:41:525524 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:285525 }
Jim Ingham0161b492013-02-09 01:29:055526 else
5527 {
Jim Ingham914f4e72014-03-28 21:58:285528 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5529 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5530 uint64_t computed_one_thread_timeout;
5531 if (option_one_thread_timeout != 0)
5532 {
5533 if (timeout_usec < option_one_thread_timeout)
5534 {
5535 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:445536 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:285537 }
5538 computed_one_thread_timeout = option_one_thread_timeout;
5539 }
5540 else
5541 {
5542 computed_one_thread_timeout = timeout_usec / 2;
5543 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5544 computed_one_thread_timeout = default_one_thread_timeout_usec;
5545 }
Jim Inghamfd95f892014-04-22 01:41:525546 one_thread_timeout_usec = computed_one_thread_timeout;
5547 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5548
Jim Ingham0161b492013-02-09 01:29:055549 }
Jim Ingham0161b492013-02-09 01:29:055550 }
Jim Inghamfe1c3422014-04-16 02:24:485551
5552 if (log)
Jim Inghamfd95f892014-04-22 01:41:525553 log->Printf ("Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32 " - all threads: %" PRIu32 ".\n",
Jim Inghamfe1c3422014-04-16 02:24:485554 options.GetStopOthers(),
5555 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:525556 before_first_timeout,
5557 one_thread_timeout_usec,
5558 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:055559
Jim Ingham1460e4b2014-01-10 23:46:595560 // This isn't going to work if there are unfetched events on the queue.
5561 // Are there cases where we might want to run the remaining events here, and then try to
5562 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:105563
Jim Ingham1460e4b2014-01-10 23:46:595564 Event *other_events = listener.PeekAtNextEvent();
5565 if (other_events != NULL)
5566 {
5567 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:445568 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:595569 }
Saleem Abdulrasool324a1032014-04-04 04:06:105570
Jim Ingham1460e4b2014-01-10 23:46:595571 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5572 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5573 // event coalescing to cause us to lose OUR running event...
5574 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:105575
Jim Ingham8559a352012-11-26 23:52:185576 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5577 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:215578
5579#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5580 // It's pretty much impossible to write test cases for things like:
5581 // One thread timeout expires, I go to halt, but the process already stopped
5582 // on the function call stop breakpoint. Turning on this define will make us not
5583 // fetch the first event till after the halt. So if you run a quick function, it will have
5584 // completed, and the completion event will be waiting, when you interrupt for halt.
5585 // The expression evaluation should still succeed.
5586 bool miss_first_event = true;
5587#endif
Jim Inghamfd95f892014-04-22 01:41:525588 TimeValue one_thread_timeout;
5589 TimeValue final_timeout;
5590
Jim Ingham35878c42014-04-08 21:33:215591
Sean Callanana46ec452012-07-11 21:31:245592 while (1)
5593 {
5594 // We usually want to resume the process if we get to the top of the loop.
5595 // The only exception is if we get two running events with no intervening
5596 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:055597 if (log)
5598 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5599 do_resume,
5600 handle_running_event,
5601 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:105602
Jim Ingham184e9812013-01-15 02:47:485603 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:245604 {
5605 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:105606
Jim Ingham184e9812013-01-15 02:47:485607 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:245608 {
Jim Ingham0161b492013-02-09 01:29:055609 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:485610 Error resume_error = PrivateResume ();
5611 if (!resume_error.Success())
5612 {
Jim Ingham0161b492013-02-09 01:29:055613 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5614 num_resumes,
5615 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:445616 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:485617 break;
5618 }
Sean Callanana46ec452012-07-11 21:31:245619 }
Saleem Abdulrasool324a1032014-04-04 04:06:105620
Jim Ingham0161b492013-02-09 01:29:055621 TimeValue resume_timeout = TimeValue::Now();
5622 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:105623
Jim Ingham0161b492013-02-09 01:29:055624 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:245625 if (!got_event)
5626 {
5627 if (log)
Jim Ingham0161b492013-02-09 01:29:055628 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5629 num_resumes);
Sean Callanana46ec452012-07-11 21:31:245630
Jim Ingham0161b492013-02-09 01:29:055631 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:445632 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:245633 break;
5634 }
Saleem Abdulrasool324a1032014-04-04 04:06:105635
Sean Callanana46ec452012-07-11 21:31:245636 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:055637
Sean Callanana46ec452012-07-11 21:31:245638 if (stop_state != eStateRunning)
5639 {
Jim Ingham0161b492013-02-09 01:29:055640 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:105641
Jim Ingham0161b492013-02-09 01:29:055642 if (stop_state == eStateStopped)
5643 {
5644 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5645 if (log)
5646 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5647 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5648 num_resumes,
5649 StateAsCString(stop_state),
5650 restarted,
5651 do_resume,
5652 handle_running_event);
5653 }
Saleem Abdulrasool324a1032014-04-04 04:06:105654
Jim Ingham0161b492013-02-09 01:29:055655 if (restarted)
5656 {
5657 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5658 // event here. But if I do, the best thing is to Halt and then get out of here.
5659 Halt();
5660 }
Saleem Abdulrasool324a1032014-04-04 04:06:105661
Jim Ingham35e1bda2012-10-16 21:41:585662 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5663 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:445664 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:245665 break;
5666 }
Saleem Abdulrasool324a1032014-04-04 04:06:105667
Sean Callanana46ec452012-07-11 21:31:245668 if (log)
5669 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5670 // We need to call the function synchronously, so spin waiting for it to return.
5671 // If we get interrupted while executing, we're going to lose our context, and
5672 // won't be able to gather the result at this point.
5673 // We set the timeout AFTER the resume, since the resume takes some time and we
5674 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:245675 }
Jim Ingham0f16e732011-02-08 05:20:595676 else
5677 {
Sean Callanana46ec452012-07-11 21:31:245678 if (log)
Jim Ingham0161b492013-02-09 01:29:055679 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:595680 }
Saleem Abdulrasool324a1032014-04-04 04:06:105681
Jim Ingham0161b492013-02-09 01:29:055682 if (before_first_timeout)
5683 {
Jim Ingham6fbc48b2013-11-07 00:11:475684 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:525685 {
5686 one_thread_timeout = TimeValue::Now();
5687 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:055688 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:525689 }
Jim Ingham0161b492013-02-09 01:29:055690 else
5691 {
5692 if (timeout_usec == 0)
5693 timeout_ptr = NULL;
5694 else
Jim Inghamfd95f892014-04-22 01:41:525695 {
5696 final_timeout = TimeValue::Now();
5697 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:055698 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:525699 }
Jim Ingham0161b492013-02-09 01:29:055700 }
5701 }
5702 else
5703 {
5704 if (timeout_usec == 0)
5705 timeout_ptr = NULL;
5706 else
Jim Inghamfd95f892014-04-22 01:41:525707 {
5708 final_timeout = TimeValue::Now();
5709 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:055710 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:525711 }
Jim Ingham0161b492013-02-09 01:29:055712 }
Saleem Abdulrasool324a1032014-04-04 04:06:105713
Jim Ingham0161b492013-02-09 01:29:055714 do_resume = true;
5715 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:105716
Sean Callanana46ec452012-07-11 21:31:245717 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:245718 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:595719
Jim Ingham0f16e732011-02-08 05:20:595720 if (log)
Jim Ingham20829ac2011-08-09 22:24:335721 {
Sean Callanana46ec452012-07-11 21:31:245722 if (timeout_ptr)
5723 {
Matt Kopec676a4872013-02-21 23:55:315724 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:055725 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5726 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:245727 }
Jim Ingham20829ac2011-08-09 22:24:335728 else
Sean Callanana46ec452012-07-11 21:31:245729 {
5730 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5731 }
5732 }
Jim Ingham35878c42014-04-08 21:33:215733
5734#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5735 // See comment above...
5736 if (miss_first_event)
5737 {
5738 usleep(1000);
5739 miss_first_event = false;
5740 got_event = false;
5741 }
5742 else
5743#endif
Sean Callanana46ec452012-07-11 21:31:245744 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:105745
Sean Callanana46ec452012-07-11 21:31:245746 if (got_event)
5747 {
5748 if (event_sp.get())
5749 {
5750 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:195751 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:245752 {
Jim Inghamcfc09352012-07-27 23:57:195753 Halt();
Jim Ingham8646d3c2014-05-05 02:47:445754 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:195755 errors.Printf ("Execution halted by user interrupt.");
5756 if (log)
5757 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:055758 break;
Jim Inghamcfc09352012-07-27 23:57:195759 }
5760 else
5761 {
5762 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5763 if (log)
5764 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:105765
Jim Inghamcfc09352012-07-27 23:57:195766 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:245767 {
Jim Inghamcfc09352012-07-27 23:57:195768 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:245769 {
Jim Ingham0161b492013-02-09 01:29:055770 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:195771 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5772 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:245773 {
Jim Inghamcfc09352012-07-27 23:57:195774 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:245775 if (log)
Jim Inghamcfc09352012-07-27 23:57:195776 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:445777 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:245778 }
5779 else
5780 {
Jim Ingham0161b492013-02-09 01:29:055781 // If we were restarted, we just need to go back up to fetch another event.
5782 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:195783 {
5784 if (log)
Jim Ingham0161b492013-02-09 01:29:055785 {
5786 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5787 }
5788 keep_going = true;
5789 do_resume = false;
5790 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:105791
Jim Inghamcfc09352012-07-27 23:57:195792 }
5793 else
5794 {
Jim Ingham0161b492013-02-09 01:29:055795 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5796 StopReason stop_reason = eStopReasonInvalid;
5797 if (stop_info_sp)
5798 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:105799
Jim Ingham0161b492013-02-09 01:29:055800 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5801 // it is OUR plan that is complete?
5802 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:485803 {
5804 if (log)
Jim Ingham0161b492013-02-09 01:29:055805 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5806 // Now mark this plan as private so it doesn't get reported as the stop reason
5807 // after this point.
5808 if (thread_plan_sp)
5809 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:445810 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:485811 }
5812 else
5813 {
Jim Ingham0161b492013-02-09 01:29:055814 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:485815 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:055816 {
5817 if (log)
5818 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:445819 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:475820 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:095821 {
5822 event_to_broadcast_sp = event_sp;
5823 }
Jim Ingham0161b492013-02-09 01:29:055824 }
Jim Ingham184e9812013-01-15 02:47:485825 else
Jim Ingham0161b492013-02-09 01:29:055826 {
5827 if (log)
5828 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:475829 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:095830 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:445831 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:055832 }
Jim Ingham184e9812013-01-15 02:47:485833 }
Jim Inghamcfc09352012-07-27 23:57:195834 }
Sean Callanana46ec452012-07-11 21:31:245835 }
Jim Inghamcfc09352012-07-27 23:57:195836 }
5837 break;
Sean Callanana46ec452012-07-11 21:31:245838
Jim Inghamcfc09352012-07-27 23:57:195839 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:055840 // This shouldn't really happen, but sometimes we do get two running events without an
5841 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:195842 do_resume = false;
5843 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:485844 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:195845 break;
Sean Callanana46ec452012-07-11 21:31:245846
Jim Inghamcfc09352012-07-27 23:57:195847 default:
5848 if (log)
5849 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:105850
Jim Inghamcfc09352012-07-27 23:57:195851 if (stop_state == eStateExited)
5852 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:105853
Sean Callananbf154da2012-08-08 17:35:105854 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:445855 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:195856 break;
5857 }
Sean Callanana46ec452012-07-11 21:31:245858 }
Saleem Abdulrasool324a1032014-04-04 04:06:105859
Sean Callanana46ec452012-07-11 21:31:245860 if (keep_going)
5861 continue;
5862 else
5863 break;
5864 }
5865 else
5866 {
5867 if (log)
5868 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:445869 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:245870 break;
5871 }
5872 }
5873 else
5874 {
5875 // If we didn't get an event that means we've timed out...
5876 // We will interrupt the process here. Depending on what we were asked to do we will
5877 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:105878
Sean Callanana46ec452012-07-11 21:31:245879 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:475880 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:245881 {
Jim Ingham0161b492013-02-09 01:29:055882 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:485883 {
5884 if (timeout_usec != 0)
5885 {
Jim Inghamfe1c3422014-04-16 02:24:485886 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:525887 "running for %" PRIu32 " usec with all threads enabled.",
5888 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:485889 }
5890 else
5891 {
5892 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:065893 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:485894 }
5895 }
Sean Callanana46ec452012-07-11 21:31:245896 else
5897 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:235898 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:585899 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:245900 }
5901 else
Jason Molenda6a8658a2013-10-27 02:32:235902 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:585903 "abandoning execution.",
5904 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:245905 }
Saleem Abdulrasool324a1032014-04-04 04:06:105906
Jim Ingham0161b492013-02-09 01:29:055907 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5908 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5909 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5910 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5911 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:105912
Jim Ingham0161b492013-02-09 01:29:055913 bool back_to_top = true;
5914 uint32_t try_halt_again = 0;
5915 bool do_halt = true;
5916 const uint32_t num_retries = 5;
5917 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:245918 {
Jim Ingham0161b492013-02-09 01:29:055919 Error halt_error;
5920 if (do_halt)
5921 {
5922 if (log)
5923 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5924 halt_error = Halt();
5925 }
5926 if (halt_error.Success())
5927 {
5928 if (log)
5929 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:105930
Jim Ingham0161b492013-02-09 01:29:055931 real_timeout = TimeValue::Now();
5932 real_timeout.OffsetWithMicroSeconds(500000);
5933
5934 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:105935
Jim Ingham0161b492013-02-09 01:29:055936 if (got_event)
Sean Callanana46ec452012-07-11 21:31:245937 {
Jim Ingham0161b492013-02-09 01:29:055938 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5939 if (log)
Sean Callanana46ec452012-07-11 21:31:245940 {
Jim Ingham0161b492013-02-09 01:29:055941 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5942 if (stop_state == lldb::eStateStopped
5943 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5944 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:245945 }
Saleem Abdulrasool324a1032014-04-04 04:06:105946
Jim Ingham0161b492013-02-09 01:29:055947 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:245948 {
Jim Ingham0161b492013-02-09 01:29:055949 // Between the time we initiated the Halt and the time we delivered it, the process could have
5950 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:105951
Jim Ingham0161b492013-02-09 01:29:055952 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5953 {
5954 if (log)
5955 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5956 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:445957 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:055958 back_to_top = false;
5959 break;
5960 }
Saleem Abdulrasool324a1032014-04-04 04:06:105961
Jim Ingham0161b492013-02-09 01:29:055962 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5963 {
5964 if (log)
5965 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5966 "Exiting wait loop.");
5967 try_halt_again++;
5968 do_halt = false;
5969 continue;
5970 }
Sean Callanana46ec452012-07-11 21:31:245971
Jim Ingham6fbc48b2013-11-07 00:11:475972 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:055973 {
5974 if (log)
5975 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:445976 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:055977 back_to_top = false;
5978 break;
5979 }
Saleem Abdulrasool324a1032014-04-04 04:06:105980
Jim Ingham0161b492013-02-09 01:29:055981 if (before_first_timeout)
5982 {
5983 // Set all the other threads to run, and return to the top of the loop, which will continue;
5984 before_first_timeout = false;
5985 thread_plan_sp->SetStopOthers (false);
5986 if (log)
5987 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:245988
Jim Ingham0161b492013-02-09 01:29:055989 back_to_top = true;
5990 break;
5991 }
5992 else
5993 {
5994 // Running all threads failed, so return Interrupted.
5995 if (log)
5996 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:445997 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:055998 back_to_top = false;
5999 break;
6000 }
Sean Callanana46ec452012-07-11 21:31:246001 }
6002 }
6003 else
Jim Ingham0161b492013-02-09 01:29:056004 { if (log)
6005 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
6006 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:446007 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:056008 back_to_top = false;
6009 break;
Sean Callanana46ec452012-07-11 21:31:246010 }
6011 }
Jim Ingham0161b492013-02-09 01:29:056012 else
6013 {
6014 try_halt_again++;
6015 continue;
6016 }
Sean Callanana46ec452012-07-11 21:31:246017 }
Saleem Abdulrasool324a1032014-04-04 04:06:106018
Jim Ingham0161b492013-02-09 01:29:056019 if (!back_to_top || try_halt_again > num_retries)
6020 break;
6021 else
6022 continue;
Sean Callanana46ec452012-07-11 21:31:246023 }
Sean Callanana46ec452012-07-11 21:31:246024 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:106025
Sean Callanana46ec452012-07-11 21:31:246026 // 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:096027 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:246028 {
6029 StopPrivateStateThread();
6030 Error error;
6031 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:266032 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:246033 {
6034 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6035 }
Jason Molenda76513fd2014-10-15 23:39:316036 if (old_state != eStateInvalid)
6037 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:246038 }
Saleem Abdulrasool324a1032014-04-04 04:06:106039
Jim Ingham184e9812013-01-15 02:47:486040 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6041 // could happen:
6042 // 1) The execution successfully completed
6043 // 2) We hit a breakpoint, and ignore_breakpoints was true
6044 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:446045 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6046 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:106047
Jim Ingham8646d3c2014-05-05 02:47:446048 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:486049 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:186050 {
6051 thread_plan_sp->RestoreThreadState();
6052 }
Saleem Abdulrasool324a1032014-04-04 04:06:106053
Sean Callanana46ec452012-07-11 21:31:246054 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:446055 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:246056 {
6057 if (log)
6058 {
6059 StreamString s;
6060 if (event_sp)
6061 event_sp->Dump (&s);
6062 else
6063 {
6064 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6065 }
6066
6067 StreamString ts;
6068
6069 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:106070
Sean Callanana46ec452012-07-11 21:31:246071 do
6072 {
Jim Inghamcfc09352012-07-27 23:57:196073 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:246074 {
Jim Inghamcfc09352012-07-27 23:57:196075 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:246076 break;
6077 }
Jim Inghamcfc09352012-07-27 23:57:196078 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:246079 {
Jim Inghamcfc09352012-07-27 23:57:196080 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:246081 break;
6082 }
Jim Inghamcfc09352012-07-27 23:57:196083 else
Sean Callanana46ec452012-07-11 21:31:246084 {
Jim Inghamcfc09352012-07-27 23:57:196085 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6086
6087 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:246088 {
Jim Inghamcfc09352012-07-27 23:57:196089 event_explanation = "<no event data>";
6090 break;
Sean Callanana46ec452012-07-11 21:31:246091 }
Saleem Abdulrasool324a1032014-04-04 04:06:106092
Jim Inghamcfc09352012-07-27 23:57:196093 Process *process = event_data->GetProcessSP().get();
6094
6095 if (!process)
Sean Callanana46ec452012-07-11 21:31:246096 {
Jim Inghamcfc09352012-07-27 23:57:196097 event_explanation = "<no process>";
6098 break;
Sean Callanana46ec452012-07-11 21:31:246099 }
Saleem Abdulrasool324a1032014-04-04 04:06:106100
Jim Inghamcfc09352012-07-27 23:57:196101 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:106102
Jim Inghamcfc09352012-07-27 23:57:196103 uint32_t num_threads = thread_list.GetSize();
6104 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:106105
Jim Inghamcfc09352012-07-27 23:57:196106 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:106107
Jim Inghamcfc09352012-07-27 23:57:196108 for (thread_index = 0;
6109 thread_index < num_threads;
6110 ++thread_index)
6111 {
6112 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:106113
Jim Inghamcfc09352012-07-27 23:57:196114 if (!thread)
6115 {
6116 ts.Printf("<?> ");
6117 continue;
6118 }
Saleem Abdulrasool324a1032014-04-04 04:06:106119
Daniel Malead01b2952012-11-29 21:49:156120 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:196121 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:106122
Jim Inghamcfc09352012-07-27 23:57:196123 if (register_context)
Daniel Malead01b2952012-11-29 21:49:156124 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:196125 else
6126 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:106127
Jim Inghamcfc09352012-07-27 23:57:196128 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6129 if (stop_info_sp)
6130 {
6131 const char *stop_desc = stop_info_sp->GetDescription();
6132 if (stop_desc)
6133 ts.PutCString (stop_desc);
6134 }
6135 ts.Printf(">");
6136 }
Saleem Abdulrasool324a1032014-04-04 04:06:106137
Jim Inghamcfc09352012-07-27 23:57:196138 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:246139 }
Sean Callanana46ec452012-07-11 21:31:246140 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:106141
Jim Inghamcfc09352012-07-27 23:57:196142 if (event_explanation)
6143 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:246144 else
Jim Inghamcfc09352012-07-27 23:57:196145 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6146 }
Saleem Abdulrasool324a1032014-04-04 04:06:106147
Jim Inghame4483cf2013-09-27 01:13:016148 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:196149 {
6150 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:106151 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6152 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:196153 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6154 thread_plan_sp->SetPrivate (orig_plan_private);
6155 }
6156 else
6157 {
6158 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:106159 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6160 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:246161 }
6162 }
Jim Ingham8646d3c2014-05-05 02:47:446163 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:246164 {
6165 if (log)
6166 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:106167
Jim Ingham6fbc48b2013-11-07 00:11:476168 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:596169 {
Greg Claytonc14ee322011-09-22 04:58:266170 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:226171 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:596172 }
Jim Inghamf48169b2010-11-30 02:22:116173 }
6174 else
6175 {
Sean Callanana46ec452012-07-11 21:31:246176 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:116177 {
Jim Ingham0f16e732011-02-08 05:20:596178 if (log)
Sean Callanana46ec452012-07-11 21:31:246179 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:446180 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:246181 }
6182 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6183 {
6184 if (log)
6185 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:446186 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:246187 }
6188 else
6189 {
6190 if (log)
6191 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:476192 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:246193 {
6194 if (log)
Jim Ingham184e9812013-01-15 02:47:486195 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:246196 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6197 thread_plan_sp->SetPrivate (orig_plan_private);
6198 }
6199 }
6200 }
Saleem Abdulrasool324a1032014-04-04 04:06:106201
Sean Callanana46ec452012-07-11 21:31:246202 // Thread we ran the function in may have gone away because we ran the target
6203 // Check that it's still there, and if it is put it back in the context. Also restore the
6204 // frame in the context if it is still present.
6205 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6206 if (thread)
6207 {
6208 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6209 }
Saleem Abdulrasool324a1032014-04-04 04:06:106210
Sean Callanana46ec452012-07-11 21:31:246211 // Also restore the current process'es selected frame & thread, since this function calling may
6212 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:106213
Sean Callanana46ec452012-07-11 21:31:246214 if (selected_tid != LLDB_INVALID_THREAD_ID)
6215 {
6216 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6217 {
6218 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:206219 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a1b2013-11-04 09:33:306220 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:246221 if (old_frame_sp)
6222 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:116223 }
Jim Inghamf48169b2010-11-30 02:22:116224 }
6225 }
Saleem Abdulrasool324a1032014-04-04 04:06:106226
Sean Callanana46ec452012-07-11 21:31:246227 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:106228
Sean Callanana46ec452012-07-11 21:31:246229 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:116230 {
Sean Callanana46ec452012-07-11 21:31:246231 if (log)
6232 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6233 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:116234 }
Saleem Abdulrasool324a1032014-04-04 04:06:106235
Jim Inghamf48169b2010-11-30 02:22:116236 return return_value;
6237}
6238
6239const char *
Jim Ingham1624a2d2014-05-05 02:26:406240Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:116241{
6242 const char *result_name;
6243
6244 switch (result)
6245 {
Jim Ingham8646d3c2014-05-05 02:47:446246 case eExpressionCompleted:
6247 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:116248 break;
Jim Ingham8646d3c2014-05-05 02:47:446249 case eExpressionDiscarded:
6250 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:116251 break;
Jim Ingham8646d3c2014-05-05 02:47:446252 case eExpressionInterrupted:
6253 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:116254 break;
Jim Ingham8646d3c2014-05-05 02:47:446255 case eExpressionHitBreakpoint:
6256 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:486257 break;
Jim Ingham8646d3c2014-05-05 02:47:446258 case eExpressionSetupError:
6259 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:116260 break;
Jim Ingham8646d3c2014-05-05 02:47:446261 case eExpressionParseError:
6262 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:406263 break;
Jim Ingham8646d3c2014-05-05 02:47:446264 case eExpressionResultUnavailable:
6265 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:406266 break;
Jim Ingham8646d3c2014-05-05 02:47:446267 case eExpressionTimedOut:
6268 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:116269 break;
Jim Ingham8646d3c2014-05-05 02:47:446270 case eExpressionStoppedForDebug:
6271 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:476272 break;
Jim Inghamf48169b2010-11-30 02:22:116273 }
6274 return result_name;
6275}
6276
Greg Clayton7260f622011-04-18 08:33:376277void
6278Process::GetStatus (Stream &strm)
6279{
6280 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:076281 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:376282 {
6283 if (state == eStateExited)
6284 {
6285 int exit_status = GetExitStatus();
6286 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:156287 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:376288 GetID(),
6289 exit_status,
6290 exit_status,
6291 exit_description ? exit_description : "");
6292 }
6293 else
6294 {
6295 if (state == eStateConnected)
6296 strm.Printf ("Connected to remote target.\n");
6297 else
Daniel Malead01b2952012-11-29 21:49:156298 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:376299 }
6300 }
6301 else
6302 {
Daniel Malead01b2952012-11-29 21:49:156303 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:376304 }
6305}
6306
6307size_t
6308Process::GetThreadStatus (Stream &strm,
6309 bool only_threads_with_stop_reason,
6310 uint32_t start_frame,
6311 uint32_t num_frames,
6312 uint32_t num_frames_with_source)
6313{
6314 size_t num_thread_infos_dumped = 0;
6315
Jim Ingham4a65fb12014-03-07 11:20:036316 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6317 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6318 // ID's, and look them up one by one:
6319
6320 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:086321 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:036322 //Scope for thread list locker;
6323 {
6324 Mutex::Locker locker (GetThreadList().GetMutex());
6325 ThreadList &curr_thread_list = GetThreadList();
6326 num_threads = curr_thread_list.GetSize();
6327 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:086328 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:036329 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:086330 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:036331 }
6332
Greg Clayton7260f622011-04-18 08:33:376333 for (uint32_t i = 0; i < num_threads; i++)
6334 {
Greg Clayton332e8b12015-01-13 21:13:086335 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:036336 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:376337 {
6338 if (only_threads_with_stop_reason)
6339 {
Jim Ingham4a65fb12014-03-07 11:20:036340 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:336341 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:376342 continue;
6343 }
Jim Ingham4a65fb12014-03-07 11:20:036344 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:376345 start_frame,
6346 num_frames,
6347 num_frames_with_source);
6348 ++num_thread_infos_dumped;
6349 }
Jim Ingham4a65fb12014-03-07 11:20:036350 else
6351 {
6352 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6353 if (log)
6354 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6355
6356 }
Greg Clayton7260f622011-04-18 08:33:376357 }
6358 return num_thread_infos_dumped;
6359}
6360
Greg Claytona9f40ad2012-02-22 04:37:266361void
6362Process::AddInvalidMemoryRegion (const LoadRange &region)
6363{
6364 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6365}
6366
6367bool
6368Process::RemoveInvalidMemoryRange (const LoadRange &region)
6369{
6370 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6371}
6372
Jim Ingham372787f2012-04-07 00:00:416373void
6374Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6375{
6376 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6377}
6378
6379bool
6380Process::RunPreResumeActions ()
6381{
6382 bool result = true;
6383 while (!m_pre_resume_actions.empty())
6384 {
6385 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6386 m_pre_resume_actions.pop_back();
6387 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:156388 if (result == true)
6389 result = this_result;
Jim Ingham372787f2012-04-07 00:00:416390 }
6391 return result;
6392}
6393
6394void
6395Process::ClearPreResumeActions ()
6396{
6397 m_pre_resume_actions.clear();
6398}
Greg Claytona9f40ad2012-02-22 04:37:266399
Zachary Turner93749ab2015-03-03 21:51:256400ProcessRunLock &
6401Process::GetRunLock()
6402{
6403 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6404 return m_private_run_lock;
6405 else
6406 return m_public_run_lock;
6407}
6408
Greg Claytonfa559e52012-05-18 02:38:056409void
6410Process::Flush ()
6411{
6412 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:166413 m_extended_thread_list.Flush();
6414 m_extended_thread_stop_id = 0;
6415 m_queue_list.Clear();
6416 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:056417}
Greg Clayton90ba8112012-12-05 00:16:596418
6419void
6420Process::DidExec ()
6421{
Todd Fiala76e0fc92014-08-27 22:58:266422 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6423 if (log)
6424 log->Printf ("Process::%s()", __FUNCTION__);
6425
Greg Clayton90ba8112012-12-05 00:16:596426 Target &target = GetTarget();
6427 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:316428 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:596429 m_dynamic_checkers_ap.reset();
6430 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:196431 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:596432 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:526433 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:436434 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:596435 m_image_tokens.clear();
6436 m_allocated_memory_cache.Clear();
6437 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:036438 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:526439 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:526440 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:026441 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:596442 DoDidExec();
6443 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:006444 // Flush the process (threads and all stack frames) after running CompleteAttach()
6445 // in case the dynamic loader loaded things in new locations.
6446 Flush();
Greg Claytonb35db632013-11-09 00:03:316447
6448 // After we figure out what was loaded/unloaded in CompleteAttach,
6449 // we need to let the target know so it can do any cleanup it needs to.
6450 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:596451}
Greg Clayton095eeaa2013-11-05 23:28:006452
Jim Ingham1460e4b2014-01-10 23:46:596453addr_t
6454Process::ResolveIndirectFunction(const Address *address, Error &error)
6455{
6456 if (address == nullptr)
6457 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:056458 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:596459 return LLDB_INVALID_ADDRESS;
6460 }
6461
6462 addr_t function_addr = LLDB_INVALID_ADDRESS;
6463
6464 addr_t addr = address->GetLoadAddress(&GetTarget());
6465 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6466 if (iter != m_resolved_indirect_addresses.end())
6467 {
6468 function_addr = (*iter).second;
6469 }
6470 else
6471 {
6472 if (!InferiorCall(this, address, function_addr))
6473 {
6474 Symbol *symbol = address->CalculateSymbolContextSymbol();
6475 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6476 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6477 function_addr = LLDB_INVALID_ADDRESS;
6478 }
6479 else
6480 {
6481 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6482 }
6483 }
6484 return function_addr;
6485}
6486
Andrew MacPhersoneb4d0602014-03-13 09:37:026487void
6488Process::ModulesDidLoad (ModuleList &module_list)
6489{
Kuba Breckaafdf8422014-10-10 23:43:036490 SystemRuntime *sys_runtime = GetSystemRuntime();
6491 if (sys_runtime)
6492 {
6493 sys_runtime->ModulesDidLoad (module_list);
6494 }
Andrew MacPhersoneb4d0602014-03-13 09:37:026495
Kuba Breckaafdf8422014-10-10 23:43:036496 GetJITLoaders().ModulesDidLoad (module_list);
6497
6498 // Give runtimes a chance to be created.
6499 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6500
6501 // Tell runtimes about new modules.
6502 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6503 {
6504 InstrumentationRuntimeSP runtime = pos->second;
6505 runtime->ModulesDidLoad(module_list);
6506 }
6507
Greg Clayton35ca64b2015-04-16 17:13:346508 // Let any language runtimes we have already created know
6509 // about the modules that loaded.
6510
6511 // Iterate over a copy of this language runtime list in case
6512 // the language runtime ModulesDidLoad somehow causes the language
6513 // riuntime to be unloaded.
6514 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6515 for (const auto &pair: language_runtimes)
6516 {
6517 // We must check language_runtime_sp to make sure it is not
6518 // NULL as we might cache the fact that we didn't have a
6519 // language runtime for a language.
6520 LanguageRuntimeSP language_runtime_sp = pair.second;
6521 if (language_runtime_sp)
6522 language_runtime_sp->ModulesDidLoad(module_list);
6523 }
Andrew MacPhersoneb4d0602014-03-13 09:37:026524}
Kuba Breckaa51ea382014-09-06 01:33:136525
6526ThreadCollectionSP
6527Process::GetHistoryThreads(lldb::addr_t addr)
6528{
6529 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:346530
Kuba Breckaa51ea382014-09-06 01:33:136531 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6532
6533 if (! memory_history.get()) {
6534 return threads;
6535 }
6536
6537 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6538
6539 return threads;
6540}
Kuba Brecka63927542014-10-11 01:59:326541
6542InstrumentationRuntimeSP
6543Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6544{
6545 InstrumentationRuntimeCollection::iterator pos;
6546 pos = m_instrumentation_runtimes.find (type);
6547 if (pos == m_instrumentation_runtimes.end())
6548 {
6549 return InstrumentationRuntimeSP();
6550 }
6551 else
6552 return (*pos).second;
6553}
Tamas Berghammer7cb18bf2015-03-24 11:15:236554
6555bool
6556Process::GetModuleSpec(const FileSpec& module_file_spec,
6557 const ArchSpec& arch,
6558 ModuleSpec& module_spec)
6559{
6560 module_spec.Clear();
6561 return false;
6562}