Bug Summary

File:tools/lldb/source/Target/Process.cpp
Location:line 2538, column 17
Description:Value stored to 'bytes_written' is never read

Annotated Source Code

1//===-- 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
10#include "lldb/lldb-python.h"
11
12#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Core/Module.h"
22#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
24#include "lldb/Core/StreamFile.h"
25#include "lldb/Expression/ClangUserExpression.h"
26#include "lldb/Host/ConnectionFileDescriptor.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Host/HostInfo.h"
29#include "lldb/Host/Pipe.h"
30#include "lldb/Host/Terminal.h"
31#include "lldb/Host/ThreadLauncher.h"
32#include "lldb/Interpreter/CommandInterpreter.h"
33#include "lldb/Symbol/Symbol.h"
34#include "lldb/Target/ABI.h"
35#include "lldb/Target/DynamicLoader.h"
36#include "lldb/Target/JITLoader.h"
37#include "lldb/Target/MemoryHistory.h"
38#include "lldb/Target/OperatingSystem.h"
39#include "lldb/Target/LanguageRuntime.h"
40#include "lldb/Target/CPPLanguageRuntime.h"
41#include "lldb/Target/ObjCLanguageRuntime.h"
42#include "lldb/Target/Platform.h"
43#include "lldb/Target/RegisterContext.h"
44#include "lldb/Target/StopInfo.h"
45#include "lldb/Target/SystemRuntime.h"
46#include "lldb/Target/Target.h"
47#include "lldb/Target/TargetList.h"
48#include "lldb/Target/Thread.h"
49#include "lldb/Target/ThreadPlan.h"
50#include "lldb/Target/ThreadPlanBase.h"
51#include "lldb/Target/InstrumentationRuntime.h"
52#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
53
54using namespace lldb;
55using namespace lldb_private;
56
57
58// Comment out line below to disable memory caching, overriding the process setting
59// target.process.disable-memory-cache
60#define ENABLE_MEMORY_CACHING
61
62#ifdef ENABLE_MEMORY_CACHING
63#define DISABLE_MEM_CACHE_DEFAULTfalse false
64#else
65#define DISABLE_MEM_CACHE_DEFAULTfalse true
66#endif
67
68class ProcessOptionValueProperties : public OptionValueProperties
69{
70public:
71 ProcessOptionValueProperties (const ConstString &name) :
72 OptionValueProperties (name)
73 {
74 }
75
76 // This constructor is used when creating ProcessOptionValueProperties when it
77 // is part of a new lldb_private::Process instance. It will copy all current
78 // global property values as needed
79 ProcessOptionValueProperties (ProcessProperties *global_properties) :
80 OptionValueProperties(*global_properties->GetValueProperties())
81 {
82 }
83
84 virtual const Property *
85 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
86 {
87 // When getting the value for a key from the process options, we will always
88 // try and grab the setting from the current process if there is one. Else we just
89 // use the one from this instance.
90 if (exe_ctx)
91 {
92 Process *process = exe_ctx->GetProcessPtr();
93 if (process)
94 {
95 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
96 if (this != instance_properties)
97 return instance_properties->ProtectedGetPropertyAtIndex (idx);
98 }
99 }
100 return ProtectedGetPropertyAtIndex (idx);
101 }
102};
103
104static PropertyDefinition
105g_properties[] =
106{
107 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULTfalse, NULL__null, NULL__null, "Disable reading and caching of memory in fixed-size units." },
108 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL__null, NULL__null, "A list containing extra commands understood by the particular process plugin used. "
109 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
110 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL__null, NULL__null, "If true, breakpoints will be ignored during expression evaluation." },
111 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL__null, NULL__null, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
112 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL__null, NULL__null, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
113 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL__null, NULL__null, "If true, stop when a shared library is loaded or unloaded." },
114 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL__null, NULL__null, "If true, detach will attempt to keep the process stopped." },
115 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL__null, NULL__null, "The memory cache line size" },
116 { NULL__null , OptionValue::eTypeInvalid, false, 0, NULL__null, NULL__null, NULL__null }
117};
118
119enum {
120 ePropertyDisableMemCache,
121 ePropertyExtraStartCommand,
122 ePropertyIgnoreBreakpointsInExpressions,
123 ePropertyUnwindOnErrorInExpressions,
124 ePropertyPythonOSPluginPath,
125 ePropertyStopOnSharedLibraryEvents,
126 ePropertyDetachKeepsStopped,
127 ePropertyMemCacheLineSize
128};
129
130ProcessProperties::ProcessProperties (bool is_global) :
131 Properties ()
132{
133 if (is_global)
134 {
135 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
136 m_collection_sp->Initialize(g_properties);
137 m_collection_sp->AppendProperty(ConstString("thread"),
138 ConstString("Settings specific to threads."),
139 true,
140 Thread::GetGlobalProperties()->GetValueProperties());
141 }
142 else
143 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
144}
145
146ProcessProperties::~ProcessProperties()
147{
148}
149
150bool
151ProcessProperties::GetDisableMemoryCache() const
152{
153 const uint32_t idx = ePropertyDisableMemCache;
154 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL__null, idx, g_properties[idx].default_uint_value != 0);
155}
156
157uint64_t
158ProcessProperties::GetMemoryCacheLineSize() const
159{
160 const uint32_t idx = ePropertyMemCacheLineSize;
161 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL__null, idx, g_properties[idx].default_uint_value);
162}
163
164Args
165ProcessProperties::GetExtraStartupCommands () const
166{
167 Args args;
168 const uint32_t idx = ePropertyExtraStartCommand;
169 m_collection_sp->GetPropertyAtIndexAsArgs(NULL__null, idx, args);
170 return args;
171}
172
173void
174ProcessProperties::SetExtraStartupCommands (const Args &args)
175{
176 const uint32_t idx = ePropertyExtraStartCommand;
177 m_collection_sp->SetPropertyAtIndexFromArgs(NULL__null, idx, args);
178}
179
180FileSpec
181ProcessProperties::GetPythonOSPluginPath () const
182{
183 const uint32_t idx = ePropertyPythonOSPluginPath;
184 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL__null, idx);
185}
186
187void
188ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
189{
190 const uint32_t idx = ePropertyPythonOSPluginPath;
191 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL__null, idx, file);
192}
193
194
195bool
196ProcessProperties::GetIgnoreBreakpointsInExpressions () const
197{
198 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
199 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL__null, idx, g_properties[idx].default_uint_value != 0);
200}
201
202void
203ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
204{
205 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
206 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL__null, idx, ignore);
207}
208
209bool
210ProcessProperties::GetUnwindOnErrorInExpressions () const
211{
212 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
213 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL__null, idx, g_properties[idx].default_uint_value != 0);
214}
215
216void
217ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
218{
219 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
220 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL__null, idx, ignore);
221}
222
223bool
224ProcessProperties::GetStopOnSharedLibraryEvents () const
225{
226 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL__null, idx, g_properties[idx].default_uint_value != 0);
228}
229
230void
231ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
232{
233 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
234 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL__null, idx, stop);
235}
236
237bool
238ProcessProperties::GetDetachKeepsStopped () const
239{
240 const uint32_t idx = ePropertyDetachKeepsStopped;
241 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL__null, idx, g_properties[idx].default_uint_value != 0);
242}
243
244void
245ProcessProperties::SetDetachKeepsStopped (bool stop)
246{
247 const uint32_t idx = ePropertyDetachKeepsStopped;
248 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL__null, idx, stop);
249}
250
251void
252ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
253{
254 const char *cstr;
255 if (m_pid != LLDB_INVALID_PROCESS_ID0)
256 s.Printf (" pid = %" PRIu64"l" "u" "\n", m_pid);
257
258 if (m_parent_pid != LLDB_INVALID_PROCESS_ID0)
259 s.Printf (" parent = %" PRIu64"l" "u" "\n", m_parent_pid);
260
261 if (m_executable)
262 {
263 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
264 s.PutCString (" file = ");
265 m_executable.Dump(&s);
266 s.EOL();
267 }
268 const uint32_t argc = m_arguments.GetArgumentCount();
269 if (argc > 0)
270 {
271 for (uint32_t i=0; i<argc; i++)
272 {
273 const char *arg = m_arguments.GetArgumentAtIndex(i);
274 if (i < 10)
275 s.Printf (" arg[%u] = %s\n", i, arg);
276 else
277 s.Printf ("arg[%u] = %s\n", i, arg);
278 }
279 }
280
281 const uint32_t envc = m_environment.GetArgumentCount();
282 if (envc > 0)
283 {
284 for (uint32_t i=0; i<envc; i++)
285 {
286 const char *env = m_environment.GetArgumentAtIndex(i);
287 if (i < 10)
288 s.Printf (" env[%u] = %s\n", i, env);
289 else
290 s.Printf ("env[%u] = %s\n", i, env);
291 }
292 }
293
294 if (m_arch.IsValid())
295 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
296
297 if (m_uid != UINT32_MAX(4294967295U))
298 {
299 cstr = platform->GetUserName (m_uid);
300 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
301 }
302 if (m_gid != UINT32_MAX(4294967295U))
303 {
304 cstr = platform->GetGroupName (m_gid);
305 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
306 }
307 if (m_euid != UINT32_MAX(4294967295U))
308 {
309 cstr = platform->GetUserName (m_euid);
310 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
311 }
312 if (m_egid != UINT32_MAX(4294967295U))
313 {
314 cstr = platform->GetGroupName (m_egid);
315 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
316 }
317}
318
319void
320ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
321{
322 const char *label;
323 if (show_args || verbose)
324 label = "ARGUMENTS";
325 else
326 label = "NAME";
327
328 if (verbose)
329 {
330 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
331 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
332 }
333 else
334 {
335 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
336 s.PutCString ("====== ====== ========== ======================== ============================\n");
337 }
338}
339
340void
341ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
342{
343 if (m_pid != LLDB_INVALID_PROCESS_ID0)
344 {
345 const char *cstr;
346 s.Printf ("%-6" PRIu64"l" "u" " %-6" PRIu64"l" "u" " ", m_pid, m_parent_pid);
347
348
349 if (verbose)
350 {
351 cstr = platform->GetUserName (m_uid);
352 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
353 s.Printf ("%-10s ", cstr);
354 else
355 s.Printf ("%-10u ", m_uid);
356
357 cstr = platform->GetGroupName (m_gid);
358 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
359 s.Printf ("%-10s ", cstr);
360 else
361 s.Printf ("%-10u ", m_gid);
362
363 cstr = platform->GetUserName (m_euid);
364 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
365 s.Printf ("%-10s ", cstr);
366 else
367 s.Printf ("%-10u ", m_euid);
368
369 cstr = platform->GetGroupName (m_egid);
370 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
371 s.Printf ("%-10s ", cstr);
372 else
373 s.Printf ("%-10u ", m_egid);
374 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
375 }
376 else
377 {
378 s.Printf ("%-10s %-24s ",
379 platform->GetUserName (m_euid),
380 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
381 }
382
383 if (verbose || show_args)
384 {
385 const uint32_t argc = m_arguments.GetArgumentCount();
386 if (argc > 0)
387 {
388 for (uint32_t i=0; i<argc; i++)
389 {
390 if (i > 0)
391 s.PutChar (' ');
392 s.PutCString (m_arguments.GetArgumentAtIndex(i));
393 }
394 }
395 }
396 else
397 {
398 s.PutCString (GetName());
399 }
400
401 s.EOL();
402 }
403}
404
405Error
406ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
407{
408 Error error;
409 const int short_option = m_getopt_table[option_idx].val;
410
411 switch (short_option)
412 {
413 case 's': // Stop at program entry point
414 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
415 break;
416
417 case 'i': // STDIN for read only
418 {
419 FileAction action;
420 if (action.Open (STDIN_FILENO0, option_arg, true, false))
421 launch_info.AppendFileAction (action);
422 break;
423 }
424
425 case 'o': // Open STDOUT for write only
426 {
427 FileAction action;
428 if (action.Open (STDOUT_FILENO1, option_arg, false, true))
429 launch_info.AppendFileAction (action);
430 break;
431 }
432
433 case 'e': // STDERR for write only
434 {
435 FileAction action;
436 if (action.Open (STDERR_FILENO2, option_arg, false, true))
437 launch_info.AppendFileAction (action);
438 break;
439 }
440
441 case 'p': // Process plug-in name
442 launch_info.SetProcessPluginName (option_arg);
443 break;
444
445 case 'n': // Disable STDIO
446 {
447 FileAction action;
448 if (action.Open (STDIN_FILENO0, "/dev/null", true, false))
449 launch_info.AppendFileAction (action);
450 if (action.Open (STDOUT_FILENO1, "/dev/null", false, true))
451 launch_info.AppendFileAction (action);
452 if (action.Open (STDERR_FILENO2, "/dev/null", false, true))
453 launch_info.AppendFileAction (action);
454 break;
455 }
456
457 case 'w':
458 launch_info.SetWorkingDirectory (option_arg);
459 break;
460
461 case 't': // Open process in new terminal window
462 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
463 break;
464
465 case 'a':
466 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
467 launch_info.GetArchitecture().SetTriple (option_arg);
468 break;
469
470 case 'A': // Disable ASLR.
471 {
472 bool success;
473 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
474 if (success)
475 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
476 else
477 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
478 break;
479 }
480
481 case 'c':
482 if (option_arg && option_arg[0])
483 launch_info.SetShell (option_arg);
484 else
485 launch_info.SetShell (LLDB_DEFAULT_SHELL"/bin/sh");
486 break;
487
488 case 'v':
489 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
490 break;
491
492 default:
493 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
494 break;
495 }
496 return error;
497}
498
499OptionDefinition
500ProcessLaunchCommandOptions::g_option_table[] =
501{
502{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL__null, NULL__null, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
503{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process."},
504{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
505{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
506{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "arch", 'a', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
507{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "environment", 'v', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
508{ LLDB_OPT_SET_ALL0xFFFFFFFFU, false, "shell", 'c', OptionParser::eOptionalArgument, NULL__null, NULL__null, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
509
510{ LLDB_OPT_SET_1(1U << 0) , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
511{ LLDB_OPT_SET_1(1U << 0) , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
512{ LLDB_OPT_SET_1(1U << 0) , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL__null, NULL__null, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
513
514{ LLDB_OPT_SET_2(1U << 1) , false, "tty", 't', OptionParser::eNoArgument, NULL__null, NULL__null, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
515
516{ LLDB_OPT_SET_3(1U << 2) , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL__null, NULL__null, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
517
518{ 0 , false, NULL__null, 0, 0, NULL__null, NULL__null, 0, eArgTypeNone, NULL__null }
519};
520
521
522
523bool
524ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
525{
526 if (m_name_match_type == eNameMatchIgnore || process_name == NULL__null)
527 return true;
528 const char *match_name = m_match_info.GetName();
529 if (!match_name)
530 return true;
531
532 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
533}
534
535bool
536ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
537{
538 if (!NameMatches (proc_info.GetName()))
539 return false;
540
541 if (m_match_info.ProcessIDIsValid() &&
542 m_match_info.GetProcessID() != proc_info.GetProcessID())
543 return false;
544
545 if (m_match_info.ParentProcessIDIsValid() &&
546 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
547 return false;
548
549 if (m_match_info.UserIDIsValid () &&
550 m_match_info.GetUserID() != proc_info.GetUserID())
551 return false;
552
553 if (m_match_info.GroupIDIsValid () &&
554 m_match_info.GetGroupID() != proc_info.GetGroupID())
555 return false;
556
557 if (m_match_info.EffectiveUserIDIsValid () &&
558 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
559 return false;
560
561 if (m_match_info.EffectiveGroupIDIsValid () &&
562 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
563 return false;
564
565 if (m_match_info.GetArchitecture().IsValid() &&
566 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
567 return false;
568 return true;
569}
570
571bool
572ProcessInstanceInfoMatch::MatchAllProcesses () const
573{
574 if (m_name_match_type != eNameMatchIgnore)
575 return false;
576
577 if (m_match_info.ProcessIDIsValid())
578 return false;
579
580 if (m_match_info.ParentProcessIDIsValid())
581 return false;
582
583 if (m_match_info.UserIDIsValid ())
584 return false;
585
586 if (m_match_info.GroupIDIsValid ())
587 return false;
588
589 if (m_match_info.EffectiveUserIDIsValid ())
590 return false;
591
592 if (m_match_info.EffectiveGroupIDIsValid ())
593 return false;
594
595 if (m_match_info.GetArchitecture().IsValid())
596 return false;
597
598 if (m_match_all_users)
599 return false;
600
601 return true;
602
603}
604
605void
606ProcessInstanceInfoMatch::Clear()
607{
608 m_match_info.Clear();
609 m_name_match_type = eNameMatchIgnore;
610 m_match_all_users = false;
611}
612
613ProcessSP
614Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
615{
616 static uint32_t g_process_unique_id = 0;
617
618 ProcessSP process_sp;
619 ProcessCreateInstance create_callback = NULL__null;
620 if (plugin_name)
621 {
622 ConstString const_plugin_name(plugin_name);
623 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
624 if (create_callback)
625 {
626 process_sp = create_callback(target, listener, crash_file_path);
627 if (process_sp)
628 {
629 if (process_sp->CanDebug(target, true))
630 {
631 process_sp->m_process_unique_id = ++g_process_unique_id;
632 }
633 else
634 process_sp.reset();
635 }
636 }
637 }
638 else
639 {
640 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL__null; ++idx)
641 {
642 process_sp = create_callback(target, listener, crash_file_path);
643 if (process_sp)
644 {
645 if (process_sp->CanDebug(target, false))
646 {
647 process_sp->m_process_unique_id = ++g_process_unique_id;
648 break;
649 }
650 else
651 process_sp.reset();
652 }
653 }
654 }
655 return process_sp;
656}
657
658ConstString &
659Process::GetStaticBroadcasterClass ()
660{
661 static ConstString class_name ("lldb.process");
662 return class_name;
663}
664
665//----------------------------------------------------------------------
666// Process constructor
667//----------------------------------------------------------------------
668Process::Process(Target &target, Listener &listener) :
669 Process(target, listener, Host::GetUnixSignals ())
670{
671 // This constructor just delegates to the full Process constructor,
672 // defaulting to using the Host's UnixSignals.
673}
674
675Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
676 ProcessProperties (false),
677 UserID (LLDB_INVALID_PROCESS_ID0),
678 Broadcaster (&(target.GetDebugger()), "lldb.process"),
679 m_target (target),
680 m_public_state (eStateUnloaded),
681 m_private_state (eStateUnloaded),
682 m_private_state_broadcaster (NULL__null, "lldb.process.internal_state_broadcaster"),
683 m_private_state_control_broadcaster (NULL__null, "lldb.process.internal_state_control_broadcaster"),
684 m_private_state_listener ("lldb.process.internal_state_listener"),
685 m_private_state_control_wait(),
686 m_mod_id (),
687 m_process_unique_id(0),
688 m_thread_index_id (0),
689 m_thread_id_to_index_id_map (),
690 m_exit_status (-1),
691 m_exit_string (),
692 m_exit_status_mutex(),
693 m_thread_mutex (Mutex::eMutexTypeRecursive),
694 m_thread_list_real (this),
695 m_thread_list (this),
696 m_extended_thread_list (this),
697 m_extended_thread_stop_id (0),
698 m_queue_list (this),
699 m_queue_list_stop_id (0),
700 m_notifications (),
701 m_image_tokens (),
702 m_listener (listener),
703 m_breakpoint_site_list (),
704 m_dynamic_checkers_ap (),
705 m_unix_signals_sp (unix_signals_sp),
706 m_abi_sp (),
707 m_process_input_reader (),
708 m_stdio_communication ("process.stdio"),
709 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
710 m_stdout_data (),
711 m_stderr_data (),
712 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
713 m_profile_data (),
714 m_iohandler_sync (false),
715 m_memory_cache (*this),
716 m_allocated_memory_cache (*this),
717 m_should_detach (false),
718 m_next_event_action_ap(),
719 m_public_run_lock (),
720 m_private_run_lock (),
721 m_currently_handling_event(false),
722 m_finalize_called(false),
723 m_clear_thread_plans_on_stop (false),
724 m_force_next_event_delivery(false),
725 m_last_broadcast_state (eStateInvalid),
726 m_destroy_in_process (false),
727 m_can_jit(eCanJITDontKnow)
728{
729 CheckInWithManager ();
730
731 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT(1u << 11)));
732 if (log)
733 log->Printf ("%p Process::Process()", static_cast<void*>(this));
734
735 if (!m_unix_signals_sp)
736 m_unix_signals_sp.reset (new UnixSignals ());
737
738 SetEventName (eBroadcastBitStateChanged, "state-changed");
739 SetEventName (eBroadcastBitInterrupt, "interrupt");
740 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
741 SetEventName (eBroadcastBitSTDERR, "stderr-available");
742 SetEventName (eBroadcastBitProfileData, "profile-data-available");
743
744 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
745 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
746 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
747
748 listener.StartListeningForEvents (this,
749 eBroadcastBitStateChanged |
750 eBroadcastBitInterrupt |
751 eBroadcastBitSTDOUT |
752 eBroadcastBitSTDERR |
753 eBroadcastBitProfileData);
754
755 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
756 eBroadcastBitStateChanged |
757 eBroadcastBitInterrupt);
758
759 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
760 eBroadcastInternalStateControlStop |
761 eBroadcastInternalStateControlPause |
762 eBroadcastInternalStateControlResume);
763 // We need something valid here, even if just the default UnixSignalsSP.
764 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization")((m_unix_signals_sp && "null m_unix_signals_sp after initialization"
) ? static_cast<void> (0) : __assert_fail ("m_unix_signals_sp && \"null m_unix_signals_sp after initialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 764, __PRETTY_FUNCTION__))
;
765}
766
767//----------------------------------------------------------------------
768// Destructor
769//----------------------------------------------------------------------
770Process::~Process()
771{
772 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT(1u << 11)));
773 if (log)
774 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
775 StopPrivateStateThread();
776
777 // ThreadList::Clear() will try to acquire this process's mutex, so
778 // explicitly clear the thread list here to ensure that the mutex
779 // is not destroyed before the thread list.
780 m_thread_list.Clear();
781}
782
783const ProcessPropertiesSP &
784Process::GetGlobalProperties()
785{
786 static ProcessPropertiesSP g_settings_sp;
787 if (!g_settings_sp)
788 g_settings_sp.reset (new ProcessProperties (true));
789 return g_settings_sp;
790}
791
792void
793Process::Finalize()
794{
795 switch (GetPrivateState())
796 {
797 case eStateConnected:
798 case eStateAttaching:
799 case eStateLaunching:
800 case eStateStopped:
801 case eStateRunning:
802 case eStateStepping:
803 case eStateCrashed:
804 case eStateSuspended:
805 if (GetShouldDetach())
806 {
807 // FIXME: This will have to be a process setting:
808 bool keep_stopped = false;
809 Detach(keep_stopped);
810 }
811 else
812 Destroy();
813 break;
814
815 case eStateInvalid:
816 case eStateUnloaded:
817 case eStateDetached:
818 case eStateExited:
819 break;
820 }
821
822 // Clear our broadcaster before we proceed with destroying
823 Broadcaster::Clear();
824
825 // Do any cleanup needed prior to being destructed... Subclasses
826 // that override this method should call this superclass method as well.
827
828 // We need to destroy the loader before the derived Process class gets destroyed
829 // since it is very likely that undoing the loader will require access to the real process.
830 m_dynamic_checkers_ap.reset();
831 m_abi_sp.reset();
832 m_os_ap.reset();
833 m_system_runtime_ap.reset();
834 m_dyld_ap.reset();
835 m_jit_loaders_ap.reset();
836 m_thread_list_real.Destroy();
837 m_thread_list.Destroy();
838 m_extended_thread_list.Destroy();
839 m_queue_list.Clear();
840 m_queue_list_stop_id = 0;
841 std::vector<Notifications> empty_notifications;
842 m_notifications.swap(empty_notifications);
843 m_image_tokens.clear();
844 m_memory_cache.Clear();
845 m_allocated_memory_cache.Clear();
846 m_language_runtimes.clear();
847 m_instrumentation_runtimes.clear();
848 m_next_event_action_ap.reset();
849//#ifdef LLDB_CONFIGURATION_DEBUG
850// StreamFile s(stdout, false);
851// EventSP event_sp;
852// while (m_private_state_listener.GetNextEvent(event_sp))
853// {
854// event_sp->Dump (&s);
855// s.EOL();
856// }
857//#endif
858 // We have to be very careful here as the m_private_state_listener might
859 // contain events that have ProcessSP values in them which can keep this
860 // process around forever. These events need to be cleared out.
861 m_private_state_listener.Clear();
862 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
863 m_public_run_lock.SetStopped();
864 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
865 m_private_run_lock.SetStopped();
866 m_finalize_called = true;
867}
868
869void
870Process::RegisterNotificationCallbacks (const Notifications& callbacks)
871{
872 m_notifications.push_back(callbacks);
873 if (callbacks.initialize != NULL__null)
874 callbacks.initialize (callbacks.baton, this);
875}
876
877bool
878Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
879{
880 std::vector<Notifications>::iterator pos, end = m_notifications.end();
881 for (pos = m_notifications.begin(); pos != end; ++pos)
882 {
883 if (pos->baton == callbacks.baton &&
884 pos->initialize == callbacks.initialize &&
885 pos->process_state_changed == callbacks.process_state_changed)
886 {
887 m_notifications.erase(pos);
888 return true;
889 }
890 }
891 return false;
892}
893
894void
895Process::SynchronouslyNotifyStateChanged (StateType state)
896{
897 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
898 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
899 {
900 if (notification_pos->process_state_changed)
901 notification_pos->process_state_changed (notification_pos->baton, this, state);
902 }
903}
904
905// FIXME: We need to do some work on events before the general Listener sees them.
906// For instance if we are continuing from a breakpoint, we need to ensure that we do
907// the little "insert real insn, step & stop" trick. But we can't do that when the
908// event is delivered by the broadcaster - since that is done on the thread that is
909// waiting for new events, so if we needed more than one event for our handling, we would
910// stall. So instead we do it when we fetch the event off of the queue.
911//
912
913StateType
914Process::GetNextEvent (EventSP &event_sp)
915{
916 StateType state = eStateInvalid;
917
918 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
919 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
920
921 return state;
922}
923
924bool
925Process::SyncIOHandler (uint64_t timeout_msec)
926{
927 bool timed_out = false;
928
929 // don't sync (potentially context switch) in case where there is no process IO
930 if (m_process_input_reader)
931 {
932 TimeValue timeout = TimeValue::Now();
933 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
934
935 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
936
937 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
938 if(log)
939 {
940 if(timed_out)
941 log->Printf ("Process::%s pid %" PRIu64"l" "u" " (timeout=%" PRIu64"l" "u" "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
942 else
943 log->Printf ("Process::%s pid %" PRIu64"l" "u" ": SUCCESS", __FUNCTION__, GetID ());
944 }
945
946 // reset sync one-shot so it will be ready for next launch
947 m_iohandler_sync.SetValue(false, eBroadcastNever);
948 }
949
950 return !timed_out;
951}
952
953StateType
954Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
955{
956 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
957 // We have to actually check each event, and in the case of a stopped event check the restarted flag
958 // on the event.
959 if (event_sp_ptr)
960 event_sp_ptr->reset();
961 StateType state = GetState();
962 // If we are exited or detached, we won't ever get back to any
963 // other valid state...
964 if (state == eStateDetached || state == eStateExited)
965 return state;
966
967 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
968 if (log)
969 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
970 static_cast<const void*>(timeout));
971
972 if (!wait_always &&
973 StateIsStoppedState(state, true) &&
974 StateIsStoppedState(GetPrivateState(), true)) {
975 if (log)
976 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
977 __FUNCTION__);
978 return state;
979 }
980
981 while (state != eStateInvalid)
982 {
983 EventSP event_sp;
984 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
985 if (event_sp_ptr && event_sp)
986 *event_sp_ptr = event_sp;
987
988 switch (state)
989 {
990 case eStateCrashed:
991 case eStateDetached:
992 case eStateExited:
993 case eStateUnloaded:
994 // We need to toggle the run lock as this won't get done in
995 // SetPublicState() if the process is hijacked.
996 if (hijack_listener)
997 m_public_run_lock.SetStopped();
998 return state;
999 case eStateStopped:
1000 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1001 continue;
1002 else
1003 {
1004 // We need to toggle the run lock as this won't get done in
1005 // SetPublicState() if the process is hijacked.
1006 if (hijack_listener)
1007 m_public_run_lock.SetStopped();
1008 return state;
1009 }
1010 default:
1011 continue;
1012 }
1013 }
1014 return state;
1015}
1016
1017
1018StateType
1019Process::WaitForState
1020(
1021 const TimeValue *timeout,
1022 const StateType *match_states,
1023 const uint32_t num_match_states
1024)
1025{
1026 EventSP event_sp;
1027 uint32_t i;
1028 StateType state = GetState();
1029 while (state != eStateInvalid)
1030 {
1031 // If we are exited or detached, we won't ever get back to any
1032 // other valid state...
1033 if (state == eStateDetached || state == eStateExited)
1034 return state;
1035
1036 state = WaitForStateChangedEvents (timeout, event_sp, NULL__null);
1037
1038 for (i=0; i<num_match_states; ++i)
1039 {
1040 if (match_states[i] == state)
1041 return state;
1042 }
1043 }
1044 return state;
1045}
1046
1047bool
1048Process::HijackProcessEvents (Listener *listener)
1049{
1050 if (listener != NULL__null)
1051 {
1052 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1053 }
1054 else
1055 return false;
1056}
1057
1058void
1059Process::RestoreProcessEvents ()
1060{
1061 RestoreBroadcaster();
1062}
1063
1064bool
1065Process::HijackPrivateProcessEvents (Listener *listener)
1066{
1067 if (listener != NULL__null)
1068 {
1069 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1070 }
1071 else
1072 return false;
1073}
1074
1075void
1076Process::RestorePrivateProcessEvents ()
1077{
1078 m_private_state_broadcaster.RestoreBroadcaster();
1079}
1080
1081StateType
1082Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
1083{
1084 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
1085
1086 if (log)
1087 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1088 static_cast<const void*>(timeout));
1089
1090 Listener *listener = hijack_listener;
1091 if (listener == NULL__null)
1092 listener = &m_listener;
1093
1094 StateType state = eStateInvalid;
1095 if (listener->WaitForEventForBroadcasterWithType (timeout,
1096 this,
1097 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1098 event_sp))
1099 {
1100 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1101 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1102 else if (log)
1103 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1104 }
1105
1106 if (log)
1107 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1108 __FUNCTION__, static_cast<const void*>(timeout),
1109 StateAsCString(state));
1110 return state;
1111}
1112
1113Event *
1114Process::PeekAtStateChangedEvents ()
1115{
1116 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
1117
1118 if (log)
1119 log->Printf ("Process::%s...", __FUNCTION__);
1120
1121 Event *event_ptr;
1122 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1123 eBroadcastBitStateChanged);
1124 if (log)
1125 {
1126 if (event_ptr)
1127 {
1128 log->Printf ("Process::%s (event_ptr) => %s",
1129 __FUNCTION__,
1130 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1131 }
1132 else
1133 {
1134 log->Printf ("Process::%s no events found",
1135 __FUNCTION__);
1136 }
1137 }
1138 return event_ptr;
1139}
1140
1141StateType
1142Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1143{
1144 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
1145
1146 if (log)
1147 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1148 static_cast<const void*>(timeout));
1149
1150 StateType state = eStateInvalid;
1151 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1152 &m_private_state_broadcaster,
1153 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1154 event_sp))
1155 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1156 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1157
1158 // This is a bit of a hack, but when we wait here we could very well return
1159 // to the command-line, and that could disable the log, which would render the
1160 // log we got above invalid.
1161 if (log)
1162 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1163 __FUNCTION__, static_cast<const void *>(timeout),
1164 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1165 return state;
1166}
1167
1168bool
1169Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1170{
1171 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
1172
1173 if (log)
1174 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1175 static_cast<const void*>(timeout));
1176
1177 if (control_only)
1178 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1179 else
1180 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1181}
1182
1183bool
1184Process::IsRunning () const
1185{
1186 return StateIsRunningState (m_public_state.GetValue());
1187}
1188
1189int
1190Process::GetExitStatus ()
1191{
1192 Mutex::Locker locker (m_exit_status_mutex);
1193
1194 if (m_public_state.GetValue() == eStateExited)
1195 return m_exit_status;
1196 return -1;
1197}
1198
1199
1200const char *
1201Process::GetExitDescription ()
1202{
1203 Mutex::Locker locker (m_exit_status_mutex);
1204
1205 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1206 return m_exit_string.c_str();
1207 return NULL__null;
1208}
1209
1210bool
1211Process::SetExitStatus (int status, const char *cstr)
1212{
1213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE(1u << 10) | LIBLLDB_LOG_PROCESS(1u << 1)));
1214 if (log)
1215 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1216 status, status,
1217 cstr ? "\"" : "",
1218 cstr ? cstr : "NULL",
1219 cstr ? "\"" : "");
1220
1221 // We were already in the exited state
1222 if (m_private_state.GetValue() == eStateExited)
1223 {
1224 if (log)
1225 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
1226 return false;
1227 }
1228
1229 // use a mutex to protect the status and string during updating
1230 {
1231 Mutex::Locker locker (m_exit_status_mutex);
1232
1233 m_exit_status = status;
1234 if (cstr)
1235 m_exit_string = cstr;
1236 else
1237 m_exit_string.clear();
1238 }
1239
1240 DidExit ();
1241
1242 SetPrivateState (eStateExited);
1243 return true;
1244}
1245
1246// This static callback can be used to watch for local child processes on
1247// the current host. The child process exits, the process will be
1248// found in the global target list (we want to be completely sure that the
1249// lldb_private::Process doesn't go away before we can deliver the signal.
1250bool
1251Process::SetProcessExitStatus (void *callback_baton,
1252 lldb::pid_t pid,
1253 bool exited,
1254 int signo, // Zero for no signal
1255 int exit_status // Exit value of process if signal is zero
1256)
1257{
1258 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
1259 if (log)
1260 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64"l" "u" ", exited=%i, signal=%i, exit_status=%i)\n",
1261 callback_baton,
1262 pid,
1263 exited,
1264 signo,
1265 exit_status);
1266
1267 if (exited)
1268 {
1269 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
1270 if (target_sp)
1271 {
1272 ProcessSP process_sp (target_sp->GetProcessSP());
1273 if (process_sp)
1274 {
1275 const char *signal_cstr = NULL__null;
1276 if (signo)
1277 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1278
1279 process_sp->SetExitStatus (exit_status, signal_cstr);
1280 }
1281 }
1282 return true;
1283 }
1284 return false;
1285}
1286
1287
1288void
1289Process::UpdateThreadListIfNeeded ()
1290{
1291 const uint32_t stop_id = GetStopID();
1292 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1293 {
1294 const StateType state = GetPrivateState();
1295 if (StateIsStoppedState (state, true))
1296 {
1297 Mutex::Locker locker (m_thread_list.GetMutex ());
1298 // m_thread_list does have its own mutex, but we need to
1299 // hold onto the mutex between the call to UpdateThreadList(...)
1300 // and the os->UpdateThreadList(...) so it doesn't change on us
1301 ThreadList &old_thread_list = m_thread_list;
1302 ThreadList real_thread_list(this);
1303 ThreadList new_thread_list(this);
1304 // Always update the thread list with the protocol specific
1305 // thread list, but only update if "true" is returned
1306 if (UpdateThreadList (m_thread_list_real, real_thread_list))
1307 {
1308 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1309 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1310 // shutting us down, causing a deadlock.
1311 if (!m_destroy_in_process)
1312 {
1313 OperatingSystem *os = GetOperatingSystem ();
1314 if (os)
1315 {
1316 // Clear any old backing threads where memory threads might have been
1317 // backed by actual threads from the lldb_private::Process subclass
1318 size_t num_old_threads = old_thread_list.GetSize(false);
1319 for (size_t i=0; i<num_old_threads; ++i)
1320 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1321
1322 // Now let the OperatingSystem plug-in update the thread list
1323 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1324 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1325 new_thread_list); // The new thread list that we will show to the user that gets filled in
1326 }
1327 else
1328 {
1329 // No OS plug-in, the new thread list is the same as the real thread list
1330 new_thread_list = real_thread_list;
1331 }
1332 }
1333
1334 m_thread_list_real.Update(real_thread_list);
1335 m_thread_list.Update (new_thread_list);
1336 m_thread_list.SetStopID (stop_id);
1337
1338 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1339 {
1340 // Clear any extended threads that we may have accumulated previously
1341 m_extended_thread_list.Clear();
1342 m_extended_thread_stop_id = GetLastNaturalStopID ();
1343
1344 m_queue_list.Clear();
1345 m_queue_list_stop_id = GetLastNaturalStopID ();
1346 }
1347 }
1348 }
1349 }
1350}
1351
1352void
1353Process::UpdateQueueListIfNeeded ()
1354{
1355 if (m_system_runtime_ap.get())
1356 {
1357 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1358 {
1359 const StateType state = GetPrivateState();
1360 if (StateIsStoppedState (state, true))
1361 {
1362 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1363 m_queue_list_stop_id = GetLastNaturalStopID();
1364 }
1365 }
1366 }
1367}
1368
1369ThreadSP
1370Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1371{
1372 OperatingSystem *os = GetOperatingSystem ();
1373 if (os)
1374 return os->CreateThread(tid, context);
1375 return ThreadSP();
1376}
1377
1378uint32_t
1379Process::GetNextThreadIndexID (uint64_t thread_id)
1380{
1381 return AssignIndexIDToThread(thread_id);
1382}
1383
1384bool
1385Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1386{
1387 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1388 if (iterator == m_thread_id_to_index_id_map.end())
1389 {
1390 return false;
1391 }
1392 else
1393 {
1394 return true;
1395 }
1396}
1397
1398uint32_t
1399Process::AssignIndexIDToThread(uint64_t thread_id)
1400{
1401 uint32_t result = 0;
1402 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1403 if (iterator == m_thread_id_to_index_id_map.end())
1404 {
1405 result = ++m_thread_index_id;
1406 m_thread_id_to_index_id_map[thread_id] = result;
1407 }
1408 else
1409 {
1410 result = iterator->second;
1411 }
1412
1413 return result;
1414}
1415
1416StateType
1417Process::GetState()
1418{
1419 // If any other threads access this we will need a mutex for it
1420 return m_public_state.GetValue ();
1421}
1422
1423void
1424Process::SetPublicState (StateType new_state, bool restarted)
1425{
1426 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE(1u << 10) | LIBLLDB_LOG_PROCESS(1u << 1)));
1427 if (log)
1428 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
1429 const StateType old_state = m_public_state.GetValue();
1430 m_public_state.SetValue (new_state);
1431
1432 // On the transition from Run to Stopped, we unlock the writer end of the
1433 // run lock. The lock gets locked in Resume, which is the public API
1434 // to tell the program to run.
1435 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1436 {
1437 if (new_state == eStateDetached)
1438 {
1439 if (log)
1440 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1441 m_public_run_lock.SetStopped();
1442 }
1443 else
1444 {
1445 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1446 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1447 if ((old_state_is_stopped != new_state_is_stopped))
1448 {
1449 if (new_state_is_stopped && !restarted)
1450 {
1451 if (log)
1452 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1453 m_public_run_lock.SetStopped();
1454 }
1455 }
1456 }
1457 }
1458}
1459
1460Error
1461Process::Resume ()
1462{
1463 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE(1u << 10) | LIBLLDB_LOG_PROCESS(1u << 1)));
1464 if (log)
1465 log->Printf("Process::Resume -- locking run lock");
1466 if (!m_public_run_lock.TrySetRunning())
1467 {
1468 Error error("Resume request failed - process still running.");
1469 if (log)
1470 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1471 return error;
1472 }
1473 return PrivateResume();
1474}
1475
1476StateType
1477Process::GetPrivateState ()
1478{
1479 return m_private_state.GetValue();
1480}
1481
1482void
1483Process::SetPrivateState (StateType new_state)
1484{
1485 if (m_finalize_called)
1486 return;
1487
1488 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE(1u << 10) | LIBLLDB_LOG_PROCESS(1u << 1)));
1489 bool state_changed = false;
1490
1491 if (log)
1492 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1493
1494 Mutex::Locker thread_locker(m_thread_list.GetMutex());
1495 Mutex::Locker locker(m_private_state.GetMutex());
1496
1497 const StateType old_state = m_private_state.GetValueNoLock ();
1498 state_changed = old_state != new_state;
1499
1500 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1501 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1502 if (old_state_is_stopped != new_state_is_stopped)
1503 {
1504 if (new_state_is_stopped)
1505 m_private_run_lock.SetStopped();
1506 else
1507 m_private_run_lock.SetRunning();
1508 }
1509
1510 if (state_changed)
1511 {
1512 m_private_state.SetValueNoLock (new_state);
1513 if (StateIsStoppedState(new_state, false))
1514 {
1515 // Note, this currently assumes that all threads in the list
1516 // stop when the process stops. In the future we will want to
1517 // support a debugging model where some threads continue to run
1518 // while others are stopped. When that happens we will either need
1519 // a way for the thread list to identify which threads are stopping
1520 // or create a special thread list containing only threads which
1521 // actually stopped.
1522 //
1523 // The process plugin is responsible for managing the actual
1524 // behavior of the threads and should have stopped any threads
1525 // that are going to stop before we get here.
1526 m_thread_list.DidStop();
1527
1528 m_mod_id.BumpStopID();
1529 m_memory_cache.Clear();
1530 if (log)
1531 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
1532 }
1533 // Use our target to get a shared pointer to ourselves...
1534 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1535 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1536 else
1537 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1538 }
1539 else
1540 {
1541 if (log)
1542 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
1543 }
1544}
1545
1546void
1547Process::SetRunningUserExpression (bool on)
1548{
1549 m_mod_id.SetRunningUserExpression (on);
1550}
1551
1552addr_t
1553Process::GetImageInfoAddress()
1554{
1555 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
1556}
1557
1558//----------------------------------------------------------------------
1559// LoadImage
1560//
1561// This function provides a default implementation that works for most
1562// unix variants. Any Process subclasses that need to do shared library
1563// loading differently should override LoadImage and UnloadImage and
1564// do what is needed.
1565//----------------------------------------------------------------------
1566uint32_t
1567Process::LoadImage (const FileSpec &image_spec, Error &error)
1568{
1569 char path[PATH_MAX4096];
1570 image_spec.GetPath(path, sizeof(path));
1571
1572 DynamicLoader *loader = GetDynamicLoader();
1573 if (loader)
1574 {
1575 error = loader->CanLoadImage();
1576 if (error.Fail())
1577 return LLDB_INVALID_IMAGE_TOKEN(4294967295U);
1578 }
1579
1580 if (error.Success())
1581 {
1582 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1583
1584 if (thread_sp)
1585 {
1586 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1587
1588 if (frame_sp)
1589 {
1590 ExecutionContext exe_ctx;
1591 frame_sp->CalculateExecutionContext (exe_ctx);
1592 EvaluateExpressionOptions expr_options;
1593 expr_options.SetUnwindOnError(true);
1594 expr_options.SetIgnoreBreakpoints(true);
1595 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
1596 expr_options.SetResultIsInternal(true);
1597
1598 StreamString expr;
1599 expr.Printf(R"(
1600 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1601 the_result.image_ptr = dlopen ("%s", 2);
1602 if (the_result.image_ptr == (void *) 0x0)
1603 {
1604 the_result.error_str = dlerror();
1605 }
1606 else
1607 {
1608 the_result.error_str = (const char *) 0x0;
1609 }
1610 the_result;
1611 )",
1612 path);
1613 const char *prefix = R"(
1614 extern "C" void* dlopen (const char *path, int mode);
1615 extern "C" const char *dlerror (void);
1616 )";
1617 lldb::ValueObjectSP result_valobj_sp;
1618 Error expr_error;
1619 ClangUserExpression::Evaluate (exe_ctx,
1620 expr_options,
1621 expr.GetData(),
1622 prefix,
1623 result_valobj_sp,
1624 expr_error);
1625 if (expr_error.Success())
1626 {
1627 error = result_valobj_sp->GetError();
1628 if (error.Success())
1629 {
1630 Scalar scalar;
1631 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1632 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
1633 {
1634 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1635 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS(18446744073709551615UL))
1636 {
1637 uint32_t image_token = m_image_tokens.size();
1638 m_image_tokens.push_back (image_ptr);
1639 return image_token;
1640 }
1641 else if (image_ptr == 0)
1642 {
1643 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1644 if (error_str_sp)
1645 {
1646 if (error_str_sp->IsCStringContainer(true))
1647 {
1648 StreamString s;
1649 size_t num_chars = error_str_sp->ReadPointedString (s, error);
1650 if (error.Success() && num_chars > 0)
1651 {
1652 error.Clear();
1653 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
1654 }
1655 }
1656 }
1657 }
1658 }
1659 }
1660 }
1661 else
1662 error = expr_error;
1663 }
1664 }
1665 }
1666 if (!error.AsCString())
1667 error.SetErrorStringWithFormat("unable to load '%s'", path);
1668 return LLDB_INVALID_IMAGE_TOKEN(4294967295U);
1669}
1670
1671//----------------------------------------------------------------------
1672// UnloadImage
1673//
1674// This function provides a default implementation that works for most
1675// unix variants. Any Process subclasses that need to do shared library
1676// loading differently should override LoadImage and UnloadImage and
1677// do what is needed.
1678//----------------------------------------------------------------------
1679Error
1680Process::UnloadImage (uint32_t image_token)
1681{
1682 Error error;
1683 if (image_token < m_image_tokens.size())
1684 {
1685 const addr_t image_addr = m_image_tokens[image_token];
1686 if (image_addr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
1687 {
1688 error.SetErrorString("image already unloaded");
1689 }
1690 else
1691 {
1692 DynamicLoader *loader = GetDynamicLoader();
1693 if (loader)
1694 error = loader->CanLoadImage();
1695
1696 if (error.Success())
1697 {
1698 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1699
1700 if (thread_sp)
1701 {
1702 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1703
1704 if (frame_sp)
1705 {
1706 ExecutionContext exe_ctx;
1707 frame_sp->CalculateExecutionContext (exe_ctx);
1708 EvaluateExpressionOptions expr_options;
1709 expr_options.SetUnwindOnError(true);
1710 expr_options.SetIgnoreBreakpoints(true);
1711 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
1712 StreamString expr;
1713 expr.Printf("dlclose ((void *)0x%" PRIx64"l" "x" ")", image_addr);
1714 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
1715 lldb::ValueObjectSP result_valobj_sp;
1716 Error expr_error;
1717 ClangUserExpression::Evaluate (exe_ctx,
1718 expr_options,
1719 expr.GetData(),
1720 prefix,
1721 result_valobj_sp,
1722 expr_error);
1723 if (result_valobj_sp->GetError().Success())
1724 {
1725 Scalar scalar;
1726 if (result_valobj_sp->ResolveValue (scalar))
1727 {
1728 if (scalar.UInt(1))
1729 {
1730 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1731 }
1732 else
1733 {
1734 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1735 }
1736 }
1737 }
1738 else
1739 {
1740 error = result_valobj_sp->GetError();
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747 else
1748 {
1749 error.SetErrorString("invalid image token");
1750 }
1751 return error;
1752}
1753
1754const lldb::ABISP &
1755Process::GetABI()
1756{
1757 if (!m_abi_sp)
1758 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1759 return m_abi_sp;
1760}
1761
1762LanguageRuntime *
1763Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
1764{
1765 LanguageRuntimeCollection::iterator pos;
1766 pos = m_language_runtimes.find (language);
1767 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
1768 {
1769 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
1770
1771 m_language_runtimes[language] = runtime_sp;
1772 return runtime_sp.get();
1773 }
1774 else
1775 return (*pos).second.get();
1776}
1777
1778CPPLanguageRuntime *
1779Process::GetCPPLanguageRuntime (bool retry_if_null)
1780{
1781 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1782 if (runtime != NULL__null && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1783 return static_cast<CPPLanguageRuntime *> (runtime);
1784 return NULL__null;
1785}
1786
1787ObjCLanguageRuntime *
1788Process::GetObjCLanguageRuntime (bool retry_if_null)
1789{
1790 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1791 if (runtime != NULL__null && runtime->GetLanguageType() == eLanguageTypeObjC)
1792 return static_cast<ObjCLanguageRuntime *> (runtime);
1793 return NULL__null;
1794}
1795
1796bool
1797Process::IsPossibleDynamicValue (ValueObject& in_value)
1798{
1799 if (in_value.IsDynamic())
1800 return false;
1801 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1802
1803 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1804 {
1805 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1806 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1807 }
1808
1809 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1810 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1811 return true;
1812
1813 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1814 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1815}
1816
1817BreakpointSiteList &
1818Process::GetBreakpointSiteList()
1819{
1820 return m_breakpoint_site_list;
1821}
1822
1823const BreakpointSiteList &
1824Process::GetBreakpointSiteList() const
1825{
1826 return m_breakpoint_site_list;
1827}
1828
1829
1830void
1831Process::DisableAllBreakpointSites ()
1832{
1833 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1834// bp_site->SetEnabled(true);
1835 DisableBreakpointSite(bp_site);
1836 });
1837}
1838
1839Error
1840Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1841{
1842 Error error (DisableBreakpointSiteByID (break_id));
1843
1844 if (error.Success())
1845 m_breakpoint_site_list.Remove(break_id);
1846
1847 return error;
1848}
1849
1850Error
1851Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1852{
1853 Error error;
1854 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1855 if (bp_site_sp)
1856 {
1857 if (bp_site_sp->IsEnabled())
1858 error = DisableBreakpointSite (bp_site_sp.get());
1859 }
1860 else
1861 {
1862 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64"l" "u", break_id);
1863 }
1864
1865 return error;
1866}
1867
1868Error
1869Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1870{
1871 Error error;
1872 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1873 if (bp_site_sp)
1874 {
1875 if (!bp_site_sp->IsEnabled())
1876 error = EnableBreakpointSite (bp_site_sp.get());
1877 }
1878 else
1879 {
1880 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64"l" "u", break_id);
1881 }
1882 return error;
1883}
1884
1885lldb::break_id_t
1886Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
1887{
1888 addr_t load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1889
1890 bool show_error = true;
1891 switch (GetState())
1892 {
1893 case eStateInvalid:
1894 case eStateUnloaded:
1895 case eStateConnected:
1896 case eStateAttaching:
1897 case eStateLaunching:
1898 case eStateDetached:
1899 case eStateExited:
1900 show_error = false;
1901 break;
1902
1903 case eStateStopped:
1904 case eStateRunning:
1905 case eStateStepping:
1906 case eStateCrashed:
1907 case eStateSuspended:
1908 show_error = IsAlive();
1909 break;
1910 }
1911
1912 // Reset the IsIndirect flag here, in case the location changes from
1913 // pointing to a indirect symbol to a regular symbol.
1914 owner->SetIsIndirect (false);
1915
1916 if (owner->ShouldResolveIndirectFunctions())
1917 {
1918 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1919 if (symbol && symbol->IsIndirect())
1920 {
1921 Error error;
1922 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1923 if (!error.Success() && show_error)
1924 {
1925 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64"l" "x" " for breakpoint %i.%i: %s\n",
1926 symbol->GetAddress().GetLoadAddress(&m_target),
1927 owner->GetBreakpoint().GetID(),
1928 owner->GetID(),
1929 error.AsCString() ? error.AsCString() : "unknown error");
1930 return LLDB_INVALID_BREAK_ID0;
1931 }
1932 Address resolved_address(load_addr);
1933 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1934 owner->SetIsIndirect(true);
1935 }
1936 else
1937 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1938 }
1939 else
1940 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1941
1942 if (load_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL))
1943 {
1944 BreakpointSiteSP bp_site_sp;
1945
1946 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1947 // create a new breakpoint site and add it.
1948
1949 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1950
1951 if (bp_site_sp)
1952 {
1953 bp_site_sp->AddOwner (owner);
1954 owner->SetBreakpointSite (bp_site_sp);
1955 return bp_site_sp->GetID();
1956 }
1957 else
1958 {
1959 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
1960 if (bp_site_sp)
1961 {
1962 Error error = EnableBreakpointSite (bp_site_sp.get());
1963 if (error.Success())
1964 {
1965 owner->SetBreakpointSite (bp_site_sp);
1966 return m_breakpoint_site_list.Add (bp_site_sp);
1967 }
1968 else
1969 {
1970 if (show_error)
1971 {
1972 // Report error for setting breakpoint...
1973 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64"l" "x" " for breakpoint %i.%i: %s\n",
1974 load_addr,
1975 owner->GetBreakpoint().GetID(),
1976 owner->GetID(),
1977 error.AsCString() ? error.AsCString() : "unknown error");
1978 }
1979 }
1980 }
1981 }
1982 }
1983 // We failed to enable the breakpoint
1984 return LLDB_INVALID_BREAK_ID0;
1985
1986}
1987
1988void
1989Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1990{
1991 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1992 if (num_owners == 0)
1993 {
1994 // Don't try to disable the site if we don't have a live process anymore.
1995 if (IsAlive())
1996 DisableBreakpointSite (bp_site_sp.get());
1997 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1998 }
1999}
2000
2001
2002size_t
2003Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2004{
2005 size_t bytes_removed = 0;
2006 BreakpointSiteList bp_sites_in_range;
2007
2008 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
2009 {
2010 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2011 if (bp_site->GetType() == BreakpointSite::eSoftware)
2012 {
2013 addr_t intersect_addr;
2014 size_t intersect_size;
2015 size_t opcode_offset;
2016 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
2017 {
2018 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size)((bp_addr <= intersect_addr && intersect_addr <
bp_addr + size) ? static_cast<void> (0) : __assert_fail
("bp_addr <= intersect_addr && intersect_addr < bp_addr + size"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2018, __PRETTY_FUNCTION__))
;
2019 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size)((bp_addr < intersect_addr + intersect_size && intersect_addr
+ intersect_size <= bp_addr + size) ? static_cast<void
> (0) : __assert_fail ("bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2019, __PRETTY_FUNCTION__))
;
2020 assert(opcode_offset + intersect_size <= bp_site->GetByteSize())((opcode_offset + intersect_size <= bp_site->GetByteSize
()) ? static_cast<void> (0) : __assert_fail ("opcode_offset + intersect_size <= bp_site->GetByteSize()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2020, __PRETTY_FUNCTION__))
;
2021 size_t buf_offset = intersect_addr - bp_addr;
2022 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
2023 }
2024 }
2025 });
2026 }
2027 return bytes_removed;
2028}
2029
2030
2031
2032size_t
2033Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2034{
2035 PlatformSP platform_sp (m_target.GetPlatform());
2036 if (platform_sp)
2037 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2038 return 0;
2039}
2040
2041Error
2042Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2043{
2044 Error error;
2045 assert (bp_site != NULL)((bp_site != __null) ? static_cast<void> (0) : __assert_fail
("bp_site != __null", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2045, __PRETTY_FUNCTION__))
;
2046 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS(1u << 5)));
2047 const addr_t bp_addr = bp_site->GetLoadAddress();
2048 if (log)
2049 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x", bp_site->GetID(), (uint64_t)bp_addr);
2050 if (bp_site->IsEnabled())
2051 {
2052 if (log)
2053 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x" " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
2054 return error;
2055 }
2056
2057 if (bp_addr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
2058 {
2059 error.SetErrorString("BreakpointSite contains an invalid load address.");
2060 return error;
2061 }
2062 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2063 // trap for the breakpoint site
2064 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2065
2066 if (bp_opcode_size == 0)
2067 {
2068 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64"l" "x", bp_addr);
2069 }
2070 else
2071 {
2072 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2073
2074 if (bp_opcode_bytes == NULL__null)
2075 {
2076 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2077 return error;
2078 }
2079
2080 // Save the original opcode by reading it
2081 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2082 {
2083 // Write a software breakpoint in place of the original opcode
2084 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2085 {
2086 uint8_t verify_bp_opcode_bytes[64];
2087 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2088 {
2089 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2090 {
2091 bp_site->SetEnabled(true);
2092 bp_site->SetType (BreakpointSite::eSoftware);
2093 if (log)
2094 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x" " -- SUCCESS",
2095 bp_site->GetID(),
2096 (uint64_t)bp_addr);
2097 }
2098 else
2099 error.SetErrorString("failed to verify the breakpoint trap in memory.");
2100 }
2101 else
2102 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2103 }
2104 else
2105 error.SetErrorString("Unable to write breakpoint trap to memory.");
2106 }
2107 else
2108 error.SetErrorString("Unable to read memory at breakpoint address.");
2109 }
2110 if (log && error.Fail())
2111 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x" " -- FAILED: %s",
2112 bp_site->GetID(),
2113 (uint64_t)bp_addr,
2114 error.AsCString());
2115 return error;
2116}
2117
2118Error
2119Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2120{
2121 Error error;
2122 assert (bp_site != NULL)((bp_site != __null) ? static_cast<void> (0) : __assert_fail
("bp_site != __null", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2122, __PRETTY_FUNCTION__))
;
2123 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS(1u << 5)));
2124 addr_t bp_addr = bp_site->GetLoadAddress();
2125 lldb::user_id_t breakID = bp_site->GetID();
2126 if (log)
2127 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64"l" "u" ") addr = 0x%" PRIx64"l" "x", breakID, (uint64_t)bp_addr);
2128
2129 if (bp_site->IsHardware())
2130 {
2131 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2132 }
2133 else if (bp_site->IsEnabled())
2134 {
2135 const size_t break_op_size = bp_site->GetByteSize();
2136 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2137 if (break_op_size > 0)
2138 {
2139 // Clear a software breakpoint instruction
2140 uint8_t curr_break_op[8];
2141 assert (break_op_size <= sizeof(curr_break_op))((break_op_size <= sizeof(curr_break_op)) ? static_cast<
void> (0) : __assert_fail ("break_op_size <= sizeof(curr_break_op)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2141, __PRETTY_FUNCTION__))
;
2142 bool break_op_found = false;
2143
2144 // Read the breakpoint opcode
2145 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2146 {
2147 bool verify = false;
2148 // Make sure we have the a breakpoint opcode exists at this address
2149 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2150 {
2151 break_op_found = true;
2152 // We found a valid breakpoint opcode at this address, now restore
2153 // the saved opcode.
2154 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2155 {
2156 verify = true;
2157 }
2158 else
2159 error.SetErrorString("Memory write failed when restoring original opcode.");
2160 }
2161 else
2162 {
2163 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2164 // Set verify to true and so we can check if the original opcode has already been restored
2165 verify = true;
2166 }
2167
2168 if (verify)
2169 {
2170 uint8_t verify_opcode[8];
2171 assert (break_op_size < sizeof(verify_opcode))((break_op_size < sizeof(verify_opcode)) ? static_cast<
void> (0) : __assert_fail ("break_op_size < sizeof(verify_opcode)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2171, __PRETTY_FUNCTION__))
;
2172 // Verify that our original opcode made it back to the inferior
2173 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2174 {
2175 // compare the memory we just read with the original opcode
2176 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2177 {
2178 // SUCCESS
2179 bp_site->SetEnabled(false);
2180 if (log)
2181 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x" " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2182 return error;
2183 }
2184 else
2185 {
2186 if (break_op_found)
2187 error.SetErrorString("Failed to restore original opcode.");
2188 }
2189 }
2190 else
2191 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2192 }
2193 }
2194 else
2195 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2196 }
2197 }
2198 else
2199 {
2200 if (log)
2201 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x" " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2202 return error;
2203 }
2204
2205 if (log)
2206 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64"l" "x" " -- FAILED: %s",
2207 bp_site->GetID(),
2208 (uint64_t)bp_addr,
2209 error.AsCString());
2210 return error;
2211
2212}
2213
2214// Uncomment to verify memory caching works after making changes to caching code
2215//#define VERIFY_MEMORY_READS
2216
2217size_t
2218Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2219{
2220 error.Clear();
2221 if (!GetDisableMemoryCache())
2222 {
2223#if defined (VERIFY_MEMORY_READS)
2224 // Memory caching is enabled, with debug verification
2225
2226 if (buf && size)
2227 {
2228 // Uncomment the line below to make sure memory caching is working.
2229 // I ran this through the test suite and got no assertions, so I am
2230 // pretty confident this is working well. If any changes are made to
2231 // memory caching, uncomment the line below and test your changes!
2232
2233 // Verify all memory reads by using the cache first, then redundantly
2234 // reading the same memory from the inferior and comparing to make sure
2235 // everything is exactly the same.
2236 std::string verify_buf (size, '\0');
2237 assert (verify_buf.size() == size)((verify_buf.size() == size) ? static_cast<void> (0) : __assert_fail
("verify_buf.size() == size", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2237, __PRETTY_FUNCTION__))
;
2238 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2239 Error verify_error;
2240 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2241 assert (cache_bytes_read == verify_bytes_read)((cache_bytes_read == verify_bytes_read) ? static_cast<void
> (0) : __assert_fail ("cache_bytes_read == verify_bytes_read"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2241, __PRETTY_FUNCTION__))
;
2242 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0)((memcmp(buf, verify_buf.data(), verify_buf.size()) == 0) ? static_cast
<void> (0) : __assert_fail ("memcmp(buf, verify_buf.data(), verify_buf.size()) == 0"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2242, __PRETTY_FUNCTION__))
;
2243 assert (verify_error.Success() == error.Success())((verify_error.Success() == error.Success()) ? static_cast<
void> (0) : __assert_fail ("verify_error.Success() == error.Success()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2243, __PRETTY_FUNCTION__))
;
2244 return cache_bytes_read;
2245 }
2246 return 0;
2247#else // !defined(VERIFY_MEMORY_READS)
2248 // Memory caching is enabled, without debug verification
2249
2250 return m_memory_cache.Read (addr, buf, size, error);
2251#endif // defined (VERIFY_MEMORY_READS)
2252 }
2253 else
2254 {
2255 // Memory caching is disabled
2256
2257 return ReadMemoryFromInferior (addr, buf, size, error);
2258 }
2259}
2260
2261size_t
2262Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2263{
2264 char buf[256];
2265 out_str.clear();
2266 addr_t curr_addr = addr;
2267 while (1)
2268 {
2269 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2270 if (length == 0)
2271 break;
2272 out_str.append(buf, length);
2273 // If we got "length - 1" bytes, we didn't get the whole C string, we
2274 // need to read some more characters
2275 if (length == sizeof(buf) - 1)
2276 curr_addr += length;
2277 else
2278 break;
2279 }
2280 return out_str.size();
2281}
2282
2283
2284size_t
2285Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2286 size_t type_width)
2287{
2288 size_t total_bytes_read = 0;
2289 if (dst && max_bytes && type_width && max_bytes >= type_width)
2290 {
2291 // Ensure a null terminator independent of the number of bytes that is read.
2292 memset (dst, 0, max_bytes);
2293 size_t bytes_left = max_bytes - type_width;
2294
2295 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2296 assert(sizeof(terminator) >= type_width &&((sizeof(terminator) >= type_width && "Attempting to validate a string with more than 4 bytes per character!"
) ? static_cast<void> (0) : __assert_fail ("sizeof(terminator) >= type_width && \"Attempting to validate a string with more than 4 bytes per character!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2297, __PRETTY_FUNCTION__))
2297 "Attempting to validate a string with more than 4 bytes per character!")((sizeof(terminator) >= type_width && "Attempting to validate a string with more than 4 bytes per character!"
) ? static_cast<void> (0) : __assert_fail ("sizeof(terminator) >= type_width && \"Attempting to validate a string with more than 4 bytes per character!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2297, __PRETTY_FUNCTION__))
;
2298
2299 addr_t curr_addr = addr;
2300 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2301 char *curr_dst = dst;
2302
2303 error.Clear();
2304 while (bytes_left > 0 && error.Success())
2305 {
2306 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2307 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2308 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2309
2310 if (bytes_read == 0)
2311 break;
2312
2313 // Search for a null terminator of correct size and alignment in bytes_read
2314 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2315 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2316 if (::strncmp(&dst[i], terminator, type_width) == 0)
2317 {
2318 error.Clear();
2319 return i;
2320 }
2321
2322 total_bytes_read += bytes_read;
2323 curr_dst += bytes_read;
2324 curr_addr += bytes_read;
2325 bytes_left -= bytes_read;
2326 }
2327 }
2328 else
2329 {
2330 if (max_bytes)
2331 error.SetErrorString("invalid arguments");
2332 }
2333 return total_bytes_read;
2334}
2335
2336// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2337// null terminators.
2338size_t
2339Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
2340{
2341 size_t total_cstr_len = 0;
2342 if (dst && dst_max_len)
2343 {
2344 result_error.Clear();
2345 // NULL out everything just to be safe
2346 memset (dst, 0, dst_max_len);
2347 Error error;
2348 addr_t curr_addr = addr;
2349 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2350 size_t bytes_left = dst_max_len - 1;
2351 char *curr_dst = dst;
2352
2353 while (bytes_left > 0)
2354 {
2355 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2356 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2357 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2358
2359 if (bytes_read == 0)
2360 {
2361 result_error = error;
2362 dst[total_cstr_len] = '\0';
2363 break;
2364 }
2365 const size_t len = strlen(curr_dst);
2366
2367 total_cstr_len += len;
2368
2369 if (len < bytes_to_read)
2370 break;
2371
2372 curr_dst += bytes_read;
2373 curr_addr += bytes_read;
2374 bytes_left -= bytes_read;
2375 }
2376 }
2377 else
2378 {
2379 if (dst == NULL__null)
2380 result_error.SetErrorString("invalid arguments");
2381 else
2382 result_error.Clear();
2383 }
2384 return total_cstr_len;
2385}
2386
2387size_t
2388Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2389{
2390 if (buf == NULL__null || size == 0)
2391 return 0;
2392
2393 size_t bytes_read = 0;
2394 uint8_t *bytes = (uint8_t *)buf;
2395
2396 while (bytes_read < size)
2397 {
2398 const size_t curr_size = size - bytes_read;
2399 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2400 bytes + bytes_read,
2401 curr_size,
2402 error);
2403 bytes_read += curr_bytes_read;
2404 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2405 break;
2406 }
2407
2408 // Replace any software breakpoint opcodes that fall into this range back
2409 // into "buf" before we return
2410 if (bytes_read > 0)
2411 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2412 return bytes_read;
2413}
2414
2415uint64_t
2416Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
2417{
2418 Scalar scalar;
2419 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2420 return scalar.ULongLong(fail_value);
2421 return fail_value;
2422}
2423
2424addr_t
2425Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2426{
2427 Scalar scalar;
2428 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2429 return scalar.ULongLong(LLDB_INVALID_ADDRESS(18446744073709551615UL));
2430 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
2431}
2432
2433
2434bool
2435Process::WritePointerToMemory (lldb::addr_t vm_addr,
2436 lldb::addr_t ptr_value,
2437 Error &error)
2438{
2439 Scalar scalar;
2440 const uint32_t addr_byte_size = GetAddressByteSize();
2441 if (addr_byte_size <= 4)
2442 scalar = (uint32_t)ptr_value;
2443 else
2444 scalar = ptr_value;
2445 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
2446}
2447
2448size_t
2449Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2450{
2451 size_t bytes_written = 0;
2452 const uint8_t *bytes = (const uint8_t *)buf;
2453
2454 while (bytes_written < size)
2455 {
2456 const size_t curr_size = size - bytes_written;
2457 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2458 bytes + bytes_written,
2459 curr_size,
2460 error);
2461 bytes_written += curr_bytes_written;
2462 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2463 break;
2464 }
2465 return bytes_written;
2466}
2467
2468size_t
2469Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2470{
2471#if defined (ENABLE_MEMORY_CACHING)
2472 m_memory_cache.Flush (addr, size);
2473#endif
2474
2475 if (buf == NULL__null || size == 0)
2476 return 0;
2477
2478 m_mod_id.BumpMemoryID();
2479
2480 // We need to write any data that would go where any current software traps
2481 // (enabled software breakpoints) any software traps (breakpoints) that we
2482 // may have placed in our tasks memory.
2483
2484 BreakpointSiteList bp_sites_in_range;
2485
2486 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
2487 {
2488 // No breakpoint sites overlap
2489 if (bp_sites_in_range.IsEmpty())
2490 return WriteMemoryPrivate (addr, buf, size, error);
2491 else
2492 {
2493 const uint8_t *ubuf = (const uint8_t *)buf;
2494 uint64_t bytes_written = 0;
2495
2496 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2497
2498 if (error.Success())
2499 {
2500 addr_t intersect_addr;
2501 size_t intersect_size;
2502 size_t opcode_offset;
2503 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2504 assert(intersects)((intersects) ? static_cast<void> (0) : __assert_fail (
"intersects", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2504, __PRETTY_FUNCTION__))
;
2505 assert(addr <= intersect_addr && intersect_addr < addr + size)((addr <= intersect_addr && intersect_addr < addr
+ size) ? static_cast<void> (0) : __assert_fail ("addr <= intersect_addr && intersect_addr < addr + size"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2505, __PRETTY_FUNCTION__))
;
2506 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size)((addr < intersect_addr + intersect_size && intersect_addr
+ intersect_size <= addr + size) ? static_cast<void>
(0) : __assert_fail ("addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2506, __PRETTY_FUNCTION__))
;
2507 assert(opcode_offset + intersect_size <= bp->GetByteSize())((opcode_offset + intersect_size <= bp->GetByteSize()) ?
static_cast<void> (0) : __assert_fail ("opcode_offset + intersect_size <= bp->GetByteSize()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2507, __PRETTY_FUNCTION__))
;
2508
2509 // Check for bytes before this breakpoint
2510 const addr_t curr_addr = addr + bytes_written;
2511 if (intersect_addr > curr_addr)
2512 {
2513 // There are some bytes before this breakpoint that we need to
2514 // just write to memory
2515 size_t curr_size = intersect_addr - curr_addr;
2516 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2517 ubuf + bytes_written,
2518 curr_size,
2519 error);
2520 bytes_written += curr_bytes_written;
2521 if (curr_bytes_written != curr_size)
2522 {
2523 // We weren't able to write all of the requested bytes, we
2524 // are done looping and will return the number of bytes that
2525 // we have written so far.
2526 if (error.Success())
2527 error.SetErrorToGenericError();
2528 }
2529 }
2530 // Now write any bytes that would cover up any software breakpoints
2531 // directly into the breakpoint opcode buffer
2532 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2533 bytes_written += intersect_size;
2534 }
2535 });
2536
2537 if (bytes_written < size)
2538 bytes_written += WriteMemoryPrivate (addr + bytes_written,
Value stored to 'bytes_written' is never read
2539 ubuf + bytes_written,
2540 size - bytes_written,
2541 error);
2542 }
2543 }
2544 else
2545 {
2546 return WriteMemoryPrivate (addr, buf, size, error);
2547 }
2548
2549 // Write any remaining bytes after the last breakpoint if we have any left
2550 return 0; //bytes_written;
2551}
2552
2553size_t
2554Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
2555{
2556 if (byte_size == UINT32_MAX(4294967295U))
2557 byte_size = scalar.GetByteSize();
2558 if (byte_size > 0)
2559 {
2560 uint8_t buf[32];
2561 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2562 if (mem_size > 0)
2563 return WriteMemory(addr, buf, mem_size, error);
2564 else
2565 error.SetErrorString ("failed to get scalar as memory data");
2566 }
2567 else
2568 {
2569 error.SetErrorString ("invalid scalar value");
2570 }
2571 return 0;
2572}
2573
2574size_t
2575Process::ReadScalarIntegerFromMemory (addr_t addr,
2576 uint32_t byte_size,
2577 bool is_signed,
2578 Scalar &scalar,
2579 Error &error)
2580{
2581 uint64_t uval = 0;
2582 if (byte_size == 0)
2583 {
2584 error.SetErrorString ("byte size is zero");
2585 }
2586 else if (byte_size & (byte_size - 1))
2587 {
2588 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2589 }
2590 else if (byte_size <= sizeof(uval))
2591 {
2592 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2593 if (bytes_read == byte_size)
2594 {
2595 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2596 lldb::offset_t offset = 0;
2597 if (byte_size <= 4)
2598 scalar = data.GetMaxU32 (&offset, byte_size);
2599 else
2600 scalar = data.GetMaxU64 (&offset, byte_size);
2601 if (is_signed)
2602 scalar.SignExtend(byte_size * 8);
2603 return bytes_read;
2604 }
2605 }
2606 else
2607 {
2608 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2609 }
2610 return 0;
2611}
2612
2613#define USE_ALLOCATE_MEMORY_CACHE1 1
2614addr_t
2615Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2616{
2617 if (GetPrivateState() != eStateStopped)
2618 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
2619
2620#if defined (USE_ALLOCATE_MEMORY_CACHE1)
2621 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2622#else
2623 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2624 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
2625 if (log)
2626 log->Printf("Process::AllocateMemory(size=%" PRIu64"l" "u" ", permissions=%s) => 0x%16.16" PRIx64"l" "x" " (m_stop_id = %u m_memory_id = %u)",
2627 (uint64_t)size,
2628 GetPermissionsAsCString (permissions),
2629 (uint64_t)allocated_addr,
2630 m_mod_id.GetStopID(),
2631 m_mod_id.GetMemoryID());
2632 return allocated_addr;
2633#endif
2634}
2635
2636bool
2637Process::CanJIT ()
2638{
2639 if (m_can_jit == eCanJITDontKnow)
2640 {
2641 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
2642 Error err;
2643
2644 uint64_t allocated_memory = AllocateMemory(8,
2645 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2646 err);
2647
2648 if (err.Success())
2649 {
2650 m_can_jit = eCanJITYes;
2651 if (log)
2652 log->Printf ("Process::%s pid %" PRIu64"l" "u" " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2653 }
2654 else
2655 {
2656 m_can_jit = eCanJITNo;
2657 if (log)
2658 log->Printf ("Process::%s pid %" PRIu64"l" "u" " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2659 }
2660
2661 DeallocateMemory (allocated_memory);
2662 }
2663
2664 return m_can_jit == eCanJITYes;
2665}
2666
2667void
2668Process::SetCanJIT (bool can_jit)
2669{
2670 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2671}
2672
2673Error
2674Process::DeallocateMemory (addr_t ptr)
2675{
2676 Error error;
2677#if defined (USE_ALLOCATE_MEMORY_CACHE1)
2678 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2679 {
2680 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64"l" "x" " failed.", (uint64_t)ptr);
2681 }
2682#else
2683 error = DoDeallocateMemory (ptr);
2684
2685 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
2686 if (log)
2687 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64"l" "x" ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2688 ptr,
2689 error.AsCString("SUCCESS"),
2690 m_mod_id.GetStopID(),
2691 m_mod_id.GetMemoryID());
2692#endif
2693 return error;
2694}
2695
2696
2697ModuleSP
2698Process::ReadModuleFromMemory (const FileSpec& file_spec,
2699 lldb::addr_t header_addr,
2700 size_t size_to_read)
2701{
2702 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
2703 if (module_sp)
2704 {
2705 Error error;
2706 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
2707 if (objfile)
2708 return module_sp;
2709 }
2710 return ModuleSP();
2711}
2712
2713Error
2714Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
2715{
2716 Error error;
2717 error.SetErrorString("watchpoints are not supported");
2718 return error;
2719}
2720
2721Error
2722Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
2723{
2724 Error error;
2725 error.SetErrorString("watchpoints are not supported");
2726 return error;
2727}
2728
2729StateType
2730Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2731{
2732 StateType state;
2733 // Now wait for the process to launch and return control to us, and then
2734 // call DidLaunch:
2735 while (1)
2736 {
2737 event_sp.reset();
2738 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2739
2740 if (StateIsStoppedState(state, false))
2741 break;
2742
2743 // If state is invalid, then we timed out
2744 if (state == eStateInvalid)
2745 break;
2746
2747 if (event_sp)
2748 HandlePrivateEvent (event_sp);
2749 }
2750 return state;
2751}
2752
2753Error
2754Process::Launch (ProcessLaunchInfo &launch_info)
2755{
2756 Error error;
2757 m_abi_sp.reset();
2758 m_dyld_ap.reset();
2759 m_jit_loaders_ap.reset();
2760 m_system_runtime_ap.reset();
2761 m_os_ap.reset();
2762 m_process_input_reader.reset();
2763
2764 Module *exe_module = m_target.GetExecutableModulePointer();
2765 if (exe_module)
2766 {
2767 char local_exec_file_path[PATH_MAX4096];
2768 char platform_exec_file_path[PATH_MAX4096];
2769 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2770 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
2771 if (exe_module->GetFileSpec().Exists())
2772 {
2773 // Install anything that might need to be installed prior to launching.
2774 // For host systems, this will do nothing, but if we are connected to a
2775 // remote platform it will install any needed binaries
2776 error = GetTarget().Install(&launch_info);
2777 if (error.Fail())
2778 return error;
2779
2780 if (PrivateStateThreadIsValid ())
2781 PausePrivateStateThread ();
2782
2783 error = WillLaunch (exe_module);
2784 if (error.Success())
2785 {
2786 const bool restarted = false;
2787 SetPublicState (eStateLaunching, restarted);
2788 m_should_detach = false;
2789
2790 if (m_public_run_lock.TrySetRunning())
2791 {
2792 // Now launch using these arguments.
2793 error = DoLaunch (exe_module, launch_info);
2794 }
2795 else
2796 {
2797 // This shouldn't happen
2798 error.SetErrorString("failed to acquire process run lock");
2799 }
2800
2801 if (error.Fail())
2802 {
2803 if (GetID() != LLDB_INVALID_PROCESS_ID0)
2804 {
2805 SetID (LLDB_INVALID_PROCESS_ID0);
2806 const char *error_string = error.AsCString();
2807 if (error_string == NULL__null)
2808 error_string = "launch failed";
2809 SetExitStatus (-1, error_string);
2810 }
2811 }
2812 else
2813 {
2814 EventSP event_sp;
2815 TimeValue timeout_time;
2816 timeout_time = TimeValue::Now();
2817 timeout_time.OffsetWithSeconds(10);
2818 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
2819
2820 if (state == eStateInvalid || event_sp.get() == NULL__null)
2821 {
2822 // We were able to launch the process, but we failed to
2823 // catch the initial stop.
2824 SetExitStatus (0, "failed to catch stop after launch");
2825 Destroy();
2826 }
2827 else if (state == eStateStopped || state == eStateCrashed)
2828 {
2829
2830 DidLaunch ();
2831
2832 DynamicLoader *dyld = GetDynamicLoader ();
2833 if (dyld)
2834 dyld->DidLaunch();
2835
2836 GetJITLoaders().DidLaunch();
2837
2838 SystemRuntime *system_runtime = GetSystemRuntime ();
2839 if (system_runtime)
2840 system_runtime->DidLaunch();
2841
2842 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL__null));
2843
2844 // Note, the stop event was consumed above, but not handled. This was done
2845 // to give DidLaunch a chance to run. The target is either stopped or crashed.
2846 // Directly set the state. This is done to prevent a stop message with a bunch
2847 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
2848 SetPublicState(state, false);
2849
2850 if (PrivateStateThreadIsValid ())
2851 ResumePrivateStateThread ();
2852 else
2853 StartPrivateStateThread ();
2854 }
2855 else if (state == eStateExited)
2856 {
2857 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2858 // not likely to work, and return an invalid pid.
2859 HandlePrivateEvent (event_sp);
2860 }
2861 }
2862 }
2863 }
2864 else
2865 {
2866 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
2867 }
2868 }
2869 return error;
2870}
2871
2872
2873Error
2874Process::LoadCore ()
2875{
2876 Error error = DoLoadCore();
2877 if (error.Success())
2878 {
2879 if (PrivateStateThreadIsValid ())
2880 ResumePrivateStateThread ();
2881 else
2882 StartPrivateStateThread ();
2883
2884 DynamicLoader *dyld = GetDynamicLoader ();
2885 if (dyld)
2886 dyld->DidAttach();
2887
2888 GetJITLoaders().DidAttach();
2889
2890 SystemRuntime *system_runtime = GetSystemRuntime ();
2891 if (system_runtime)
2892 system_runtime->DidAttach();
2893
2894 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL__null));
2895 // We successfully loaded a core file, now pretend we stopped so we can
2896 // show all of the threads in the core file and explore the crashed
2897 // state.
2898 SetPrivateState (eStateStopped);
2899
2900 }
2901 return error;
2902}
2903
2904DynamicLoader *
2905Process::GetDynamicLoader ()
2906{
2907 if (m_dyld_ap.get() == NULL__null)
2908 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL__null));
2909 return m_dyld_ap.get();
2910}
2911
2912const lldb::DataBufferSP
2913Process::GetAuxvData()
2914{
2915 return DataBufferSP ();
2916}
2917
2918JITLoaderList &
2919Process::GetJITLoaders ()
2920{
2921 if (!m_jit_loaders_ap)
2922 {
2923 m_jit_loaders_ap.reset(new JITLoaderList());
2924 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2925 }
2926 return *m_jit_loaders_ap;
2927}
2928
2929SystemRuntime *
2930Process::GetSystemRuntime ()
2931{
2932 if (m_system_runtime_ap.get() == NULL__null)
2933 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2934 return m_system_runtime_ap.get();
2935}
2936
2937Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
2938 NextEventAction (process),
2939 m_exec_count (exec_count)
2940{
2941 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
2942 if (log)
2943 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32"u", __FUNCTION__, static_cast<void*>(process), exec_count);
2944}
2945
2946Process::NextEventAction::EventActionResult
2947Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
2948{
2949 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
2950
2951 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2952 if (log)
2953 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
2954
2955 switch (state)
2956 {
2957 case eStateRunning:
2958 case eStateConnected:
2959 return eEventActionRetry;
2960
2961 case eStateStopped:
2962 case eStateCrashed:
2963 {
2964 // During attach, prior to sending the eStateStopped event,
2965 // lldb_private::Process subclasses must set the new process ID.
2966 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID)((m_process->GetID() != 0) ? static_cast<void> (0) :
__assert_fail ("m_process->GetID() != 0", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 2966, __PRETTY_FUNCTION__))
;
2967 // We don't want these events to be reported, so go set the ShouldReportStop here:
2968 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2969
2970 if (m_exec_count > 0)
2971 {
2972 --m_exec_count;
2973
2974 if (log)
2975 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32"u" ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
2976
2977 RequestResume();
2978 return eEventActionRetry;
2979 }
2980 else
2981 {
2982 if (log)
2983 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
2984
2985 m_process->CompleteAttach ();
2986 return eEventActionSuccess;
2987 }
2988 }
2989 break;
2990
2991 default:
2992 case eStateExited:
2993 case eStateInvalid:
2994 break;
2995 }
2996
2997 m_exit_string.assign ("No valid Process");
2998 return eEventActionExit;
2999}
3000
3001Process::NextEventAction::EventActionResult
3002Process::AttachCompletionHandler::HandleBeingInterrupted()
3003{
3004 return eEventActionSuccess;
3005}
3006
3007const char *
3008Process::AttachCompletionHandler::GetExitString ()
3009{
3010 return m_exit_string.c_str();
3011}
3012
3013Error
3014Process::Attach (ProcessAttachInfo &attach_info)
3015{
3016 m_abi_sp.reset();
3017 m_process_input_reader.reset();
3018 m_dyld_ap.reset();
3019 m_jit_loaders_ap.reset();
3020 m_system_runtime_ap.reset();
3021 m_os_ap.reset();
3022
3023 lldb::pid_t attach_pid = attach_info.GetProcessID();
3024 Error error;
3025 if (attach_pid == LLDB_INVALID_PROCESS_ID0)
3026 {
3027 char process_name[PATH_MAX4096];
3028
3029 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
3030 {
3031 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3032
3033 if (wait_for_launch)
3034 {
3035 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3036 if (error.Success())
3037 {
3038 if (m_public_run_lock.TrySetRunning())
3039 {
3040 m_should_detach = true;
3041 const bool restarted = false;
3042 SetPublicState (eStateAttaching, restarted);
3043 // Now attach using these arguments.
3044 error = DoAttachToProcessWithName (process_name, attach_info);
3045 }
3046 else
3047 {
3048 // This shouldn't happen
3049 error.SetErrorString("failed to acquire process run lock");
3050 }
3051
3052 if (error.Fail())
3053 {
3054 if (GetID() != LLDB_INVALID_PROCESS_ID0)
3055 {
3056 SetID (LLDB_INVALID_PROCESS_ID0);
3057 if (error.AsCString() == NULL__null)
3058 error.SetErrorString("attach failed");
3059
3060 SetExitStatus(-1, error.AsCString());
3061 }
3062 }
3063 else
3064 {
3065 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3066 StartPrivateStateThread();
3067 }
3068 return error;
3069 }
3070 }
3071 else
3072 {
3073 ProcessInstanceInfoList process_infos;
3074 PlatformSP platform_sp (m_target.GetPlatform ());
3075
3076 if (platform_sp)
3077 {
3078 ProcessInstanceInfoMatch match_info;
3079 match_info.GetProcessInfo() = attach_info;
3080 match_info.SetNameMatchType (eNameMatchEquals);
3081 platform_sp->FindProcesses (match_info, process_infos);
3082 const uint32_t num_matches = process_infos.GetSize();
3083 if (num_matches == 1)
3084 {
3085 attach_pid = process_infos.GetProcessIDAtIndex(0);
3086 // Fall through and attach using the above process ID
3087 }
3088 else
3089 {
3090 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3091 if (num_matches > 1)
3092 {
3093 StreamString s;
3094 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3095 for (size_t i = 0; i < num_matches; i++)
3096 {
3097 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3098 }
3099 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3100 process_name,
3101 s.GetData());
3102 }
3103 else
3104 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3105 }
3106 }
3107 else
3108 {
3109 error.SetErrorString ("invalid platform, can't find processes by name");
3110 return error;
3111 }
3112 }
3113 }
3114 else
3115 {
3116 error.SetErrorString ("invalid process name");
3117 }
3118 }
3119
3120 if (attach_pid != LLDB_INVALID_PROCESS_ID0)
3121 {
3122 error = WillAttachToProcessWithID(attach_pid);
3123 if (error.Success())
3124 {
3125
3126 if (m_public_run_lock.TrySetRunning())
3127 {
3128 // Now attach using these arguments.
3129 m_should_detach = true;
3130 const bool restarted = false;
3131 SetPublicState (eStateAttaching, restarted);
3132 error = DoAttachToProcessWithID (attach_pid, attach_info);
3133 }
3134 else
3135 {
3136 // This shouldn't happen
3137 error.SetErrorString("failed to acquire process run lock");
3138 }
3139
3140 if (error.Success())
3141 {
3142
3143 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3144 StartPrivateStateThread();
3145 }
3146 else
3147 {
3148 if (GetID() != LLDB_INVALID_PROCESS_ID0)
3149 {
3150 SetID (LLDB_INVALID_PROCESS_ID0);
3151 const char *error_string = error.AsCString();
3152 if (error_string == NULL__null)
3153 error_string = "attach failed";
3154
3155 SetExitStatus(-1, error_string);
3156 }
3157 }
3158 }
3159 }
3160 return error;
3161}
3162
3163void
3164Process::CompleteAttach ()
3165{
3166 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
3167 if (log)
3168 log->Printf ("Process::%s()", __FUNCTION__);
3169
3170 // Let the process subclass figure out at much as it can about the process
3171 // before we go looking for a dynamic loader plug-in.
3172 ArchSpec process_arch;
3173 DidAttach(process_arch);
3174
3175 if (process_arch.IsValid())
3176 {
3177 m_target.SetArchitecture(process_arch);
3178 if (log)
3179 {
3180 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3181 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3182 __FUNCTION__,
3183 triple_str ? triple_str : "<null>");
3184 }
3185 }
3186
3187 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3188 // the same as the one we've already set, switch architectures.
3189 PlatformSP platform_sp (m_target.GetPlatform ());
3190 assert (platform_sp.get())((platform_sp.get()) ? static_cast<void> (0) : __assert_fail
("platform_sp.get()", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 3190, __PRETTY_FUNCTION__))
;
3191 if (platform_sp)
3192 {
3193 const ArchSpec &target_arch = m_target.GetArchitecture();
3194 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL__null))
3195 {
3196 ArchSpec platform_arch;
3197 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3198 if (platform_sp)
3199 {
3200 m_target.SetPlatform (platform_sp);
3201 m_target.SetArchitecture(platform_arch);
3202 if (log)
3203 log->Printf ("Process::%s switching platform to %s and architecture to %s based on info from attach", __FUNCTION__, platform_sp->GetName().AsCString (""), platform_arch.GetTriple().getTriple().c_str ());
3204 }
3205 }
3206 else if (!process_arch.IsValid())
3207 {
3208 ProcessInstanceInfo process_info;
3209 platform_sp->GetProcessInfo (GetID(), process_info);
3210 const ArchSpec &process_arch = process_info.GetArchitecture();
3211 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
3212 {
3213 m_target.SetArchitecture (process_arch);
3214 if (log)
3215 log->Printf ("Process::%s switching architecture to %s based on info the platform retrieved for pid %" PRIu64"l" "u", __FUNCTION__, process_arch.GetTriple().getTriple().c_str (), GetID ());
3216 }
3217 }
3218 }
3219
3220 // We have completed the attach, now it is time to find the dynamic loader
3221 // plug-in
3222 DynamicLoader *dyld = GetDynamicLoader ();
3223 if (dyld)
3224 {
3225 dyld->DidAttach();
3226 if (log)
3227 {
3228 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3229 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3230 __FUNCTION__,
3231 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3232 dyld->GetPluginName().AsCString ("<unnamed>"));
3233 }
3234 }
3235
3236 GetJITLoaders().DidAttach();
3237
3238 SystemRuntime *system_runtime = GetSystemRuntime ();
3239 if (system_runtime)
3240 {
3241 system_runtime->DidAttach();
3242 if (log)
3243 {
3244 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3245 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3246 __FUNCTION__,
3247 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3248 system_runtime->GetPluginName().AsCString("<unnamed>"));
3249 }
3250 }
3251
3252 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL__null));
3253 // Figure out which one is the executable, and set that in our target:
3254 const ModuleList &target_modules = m_target.GetImages();
3255 Mutex::Locker modules_locker(target_modules.GetMutex());
3256 size_t num_modules = target_modules.GetSize();
3257 ModuleSP new_executable_module_sp;
3258
3259 for (size_t i = 0; i < num_modules; i++)
3260 {
3261 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
3262 if (module_sp && module_sp->IsExecutable())
3263 {
3264 if (m_target.GetExecutableModulePointer() != module_sp.get())
3265 new_executable_module_sp = module_sp;
3266 break;
3267 }
3268 }
3269 if (new_executable_module_sp)
3270 {
3271 m_target.SetExecutableModule (new_executable_module_sp, false);
3272 if (log)
3273 {
3274 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3275 log->Printf ("Process::%s after looping through modules, target executable is %s",
3276 __FUNCTION__,
3277 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3278 }
3279 }
3280}
3281
3282Error
3283Process::ConnectRemote (Stream *strm, const char *remote_url)
3284{
3285 m_abi_sp.reset();
3286 m_process_input_reader.reset();
3287
3288 // Find the process and its architecture. Make sure it matches the architecture
3289 // of the current Target, and if not adjust it.
3290
3291 Error error (DoConnectRemote (strm, remote_url));
3292 if (error.Success())
3293 {
3294 if (GetID() != LLDB_INVALID_PROCESS_ID0)
3295 {
3296 EventSP event_sp;
3297 StateType state = WaitForProcessStopPrivate(NULL__null, event_sp);
3298
3299 if (state == eStateStopped || state == eStateCrashed)
3300 {
3301 // If we attached and actually have a process on the other end, then
3302 // this ended up being the equivalent of an attach.
3303 CompleteAttach ();
3304
3305 // This delays passing the stopped event to listeners till
3306 // CompleteAttach gets a chance to complete...
3307 HandlePrivateEvent (event_sp);
3308
3309 }
3310 }
3311
3312 if (PrivateStateThreadIsValid ())
3313 ResumePrivateStateThread ();
3314 else
3315 StartPrivateStateThread ();
3316 }
3317 return error;
3318}
3319
3320
3321Error
3322Process::PrivateResume ()
3323{
3324 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)|LIBLLDB_LOG_STEP(1u << 7)));
3325 if (log)
3326 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
3327 m_mod_id.GetStopID(),
3328 StateAsCString(m_public_state.GetValue()),
3329 StateAsCString(m_private_state.GetValue()));
3330
3331 Error error (WillResume());
3332 // Tell the process it is about to resume before the thread list
3333 if (error.Success())
3334 {
3335 // Now let the thread list know we are about to resume so it
3336 // can let all of our threads know that they are about to be
3337 // resumed. Threads will each be called with
3338 // Thread::WillResume(StateType) where StateType contains the state
3339 // that they are supposed to have when the process is resumed
3340 // (suspended/running/stepping). Threads should also check
3341 // their resume signal in lldb::Thread::GetResumeSignal()
3342 // to see if they are supposed to start back up with a signal.
3343 if (m_thread_list.WillResume())
3344 {
3345 // Last thing, do the PreResumeActions.
3346 if (!RunPreResumeActions())
3347 {
3348 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
3349 }
3350 else
3351 {
3352 m_mod_id.BumpResumeID();
3353 error = DoResume();
3354 if (error.Success())
3355 {
3356 DidResume();
3357 m_thread_list.DidResume();
3358 if (log)
3359 log->Printf ("Process thinks the process has resumed.");
3360 }
3361 }
3362 }
3363 else
3364 {
3365 // Somebody wanted to run without running. So generate a continue & a stopped event,
3366 // and let the world handle them.
3367 if (log)
3368 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3369
3370 SetPrivateState(eStateRunning);
3371 SetPrivateState(eStateStopped);
3372 }
3373 }
3374 else if (log)
3375 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
3376 return error;
3377}
3378
3379Error
3380Process::Halt (bool clear_thread_plans)
3381{
3382 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3383 // in case it was already set and some thread plan logic calls halt on its
3384 // own.
3385 m_clear_thread_plans_on_stop |= clear_thread_plans;
3386
3387 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3388 // we could just straightaway get another event. It just narrows the window...
3389 m_currently_handling_event.WaitForValueEqualTo(false);
3390
3391
3392 // Pause our private state thread so we can ensure no one else eats
3393 // the stop event out from under us.
3394 Listener halt_listener ("lldb.process.halt_listener");
3395 HijackPrivateProcessEvents(&halt_listener);
3396
3397 EventSP event_sp;
3398 Error error (WillHalt());
3399
3400 bool restored_process_events = false;
3401 if (error.Success())
3402 {
3403
3404 bool caused_stop = false;
3405
3406 // Ask the process subclass to actually halt our process
3407 error = DoHalt(caused_stop);
3408 if (error.Success())
3409 {
3410 if (m_public_state.GetValue() == eStateAttaching)
3411 {
3412 // Don't hijack and eat the eStateExited as the code that was doing
3413 // the attach will be waiting for this event...
3414 RestorePrivateProcessEvents();
3415 restored_process_events = true;
3416 SetExitStatus(SIGKILL9, "Cancelled async attach.");
3417 Destroy ();
3418 }
3419 else
3420 {
3421 // If "caused_stop" is true, then DoHalt stopped the process. If
3422 // "caused_stop" is false, the process was already stopped.
3423 // If the DoHalt caused the process to stop, then we want to catch
3424 // this event and set the interrupted bool to true before we pass
3425 // this along so clients know that the process was interrupted by
3426 // a halt command.
3427 if (caused_stop)
3428 {
3429 // Wait for 1 second for the process to stop.
3430 TimeValue timeout_time;
3431 timeout_time = TimeValue::Now();
3432 timeout_time.OffsetWithSeconds(10);
3433 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3434 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3435
3436 if (!got_event || state == eStateInvalid)
3437 {
3438 // We timeout out and didn't get a stop event...
3439 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
3440 }
3441 else
3442 {
3443 if (StateIsStoppedState (state, false))
3444 {
3445 // We caused the process to interrupt itself, so mark this
3446 // as such in the stop event so clients can tell an interrupted
3447 // process from a natural stop
3448 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3449 }
3450 else
3451 {
3452 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
3453 if (log)
3454 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3455 error.SetErrorString ("Did not get stopped event after halt.");
3456 }
3457 }
3458 }
3459 DidHalt();
3460 }
3461 }
3462 }
3463 // Resume our private state thread before we post the event (if any)
3464 if (!restored_process_events)
3465 RestorePrivateProcessEvents();
3466
3467 // Post any event we might have consumed. If all goes well, we will have
3468 // stopped the process, intercepted the event and set the interrupted
3469 // bool in the event. Post it to the private event queue and that will end up
3470 // correctly setting the state.
3471 if (event_sp)
3472 m_private_state_broadcaster.BroadcastEvent(event_sp);
3473
3474 return error;
3475}
3476
3477Error
3478Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3479{
3480 Error error;
3481 if (m_public_state.GetValue() == eStateRunning)
3482 {
3483 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
3484 if (log)
3485 log->Printf("Process::Destroy() About to halt.");
3486 error = Halt();
3487 if (error.Success())
3488 {
3489 // Consume the halt event.
3490 TimeValue timeout (TimeValue::Now());
3491 timeout.OffsetWithSeconds(1);
3492 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3493
3494 // If the process exited while we were waiting for it to stop, put the exited event into
3495 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3496 // they don't have a process anymore...
3497
3498 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3499 {
3500 if (log)
3501 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3502 return error;
3503 }
3504 else
3505 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3506
3507 if (state != eStateStopped)
3508 {
3509 if (log)
3510 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3511 // If we really couldn't stop the process then we should just error out here, but if the
3512 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3513 StateType private_state = m_private_state.GetValue();
3514 if (private_state != eStateStopped)
3515 {
3516 return error;
3517 }
3518 }
3519 }
3520 else
3521 {
3522 if (log)
3523 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3524 }
3525 }
3526 return error;
3527}
3528
3529Error
3530Process::Detach (bool keep_stopped)
3531{
3532 EventSP exit_event_sp;
3533 Error error;
3534 m_destroy_in_process = true;
3535
3536 error = WillDetach();
3537
3538 if (error.Success())
3539 {
3540 if (DetachRequiresHalt())
3541 {
3542 error = HaltForDestroyOrDetach (exit_event_sp);
3543 if (!error.Success())
3544 {
3545 m_destroy_in_process = false;
3546 return error;
3547 }
3548 else if (exit_event_sp)
3549 {
3550 // We shouldn't need to do anything else here. There's no process left to detach from...
3551 StopPrivateStateThread();
3552 m_destroy_in_process = false;
3553 return error;
3554 }
3555 }
3556
3557 m_thread_list.DiscardThreadPlans();
3558 DisableAllBreakpointSites();
3559
3560 error = DoDetach(keep_stopped);
3561 if (error.Success())
3562 {
3563 DidDetach();
3564 StopPrivateStateThread();
3565 }
3566 else
3567 {
3568 return error;
3569 }
3570 }
3571 m_destroy_in_process = false;
3572
3573 // If we exited when we were waiting for a process to stop, then
3574 // forward the event here so we don't lose the event
3575 if (exit_event_sp)
3576 {
3577 // Directly broadcast our exited event because we shut down our
3578 // private state thread above
3579 BroadcastEvent(exit_event_sp);
3580 }
3581
3582 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3583 // the last events through the event system, in which case we might strand the write lock. Unlock
3584 // it here so when we do to tear down the process we don't get an error destroying the lock.
3585
3586 m_public_run_lock.SetStopped();
3587 return error;
3588}
3589
3590Error
3591Process::Destroy ()
3592{
3593
3594 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3595 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3596 // failed and the process stays around for some reason it won't be in a confused state.
3597
3598 m_destroy_in_process = true;
3599
3600 Error error (WillDestroy());
3601 if (error.Success())
3602 {
3603 EventSP exit_event_sp;
3604 if (DestroyRequiresHalt())
3605 {
3606 error = HaltForDestroyOrDetach(exit_event_sp);
3607 }
3608
3609 if (m_public_state.GetValue() != eStateRunning)
3610 {
3611 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3612 // kill it, we don't want it hitting a breakpoint...
3613 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3614 // we're not going to have much luck doing this now.
3615 m_thread_list.DiscardThreadPlans();
3616 DisableAllBreakpointSites();
3617 }
3618
3619 error = DoDestroy();
3620 if (error.Success())
3621 {
3622 DidDestroy();
3623 StopPrivateStateThread();
3624 }
3625 m_stdio_communication.StopReadThread();
3626 m_stdio_communication.Disconnect();
3627
3628 if (m_process_input_reader)
3629 {
3630 m_process_input_reader->SetIsDone(true);
3631 m_process_input_reader->Cancel();
3632 m_process_input_reader.reset();
3633 }
3634
3635 // If we exited when we were waiting for a process to stop, then
3636 // forward the event here so we don't lose the event
3637 if (exit_event_sp)
3638 {
3639 // Directly broadcast our exited event because we shut down our
3640 // private state thread above
3641 BroadcastEvent(exit_event_sp);
3642 }
3643
3644 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3645 // the last events through the event system, in which case we might strand the write lock. Unlock
3646 // it here so when we do to tear down the process we don't get an error destroying the lock.
3647 m_public_run_lock.SetStopped();
3648 }
3649
3650 m_destroy_in_process = false;
3651
3652 return error;
3653}
3654
3655Error
3656Process::Signal (int signal)
3657{
3658 Error error (WillSignal());
3659 if (error.Success())
3660 {
3661 error = DoSignal(signal);
3662 if (error.Success())
3663 DidSignal();
3664 }
3665 return error;
3666}
3667
3668lldb::ByteOrder
3669Process::GetByteOrder () const
3670{
3671 return m_target.GetArchitecture().GetByteOrder();
3672}
3673
3674uint32_t
3675Process::GetAddressByteSize () const
3676{
3677 return m_target.GetArchitecture().GetAddressByteSize();
3678}
3679
3680
3681bool
3682Process::ShouldBroadcastEvent (Event *event_ptr)
3683{
3684 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3685 bool return_value = true;
3686 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS(1u << 4) | LIBLLDB_LOG_PROCESS(1u << 1)));
3687
3688 switch (state)
3689 {
3690 case eStateConnected:
3691 case eStateAttaching:
3692 case eStateLaunching:
3693 case eStateDetached:
3694 case eStateExited:
3695 case eStateUnloaded:
3696 // These events indicate changes in the state of the debugging session, always report them.
3697 return_value = true;
3698 break;
3699 case eStateInvalid:
3700 // We stopped for no apparent reason, don't report it.
3701 return_value = false;
3702 break;
3703 case eStateRunning:
3704 case eStateStepping:
3705 // If we've started the target running, we handle the cases where we
3706 // are already running and where there is a transition from stopped to
3707 // running differently.
3708 // running -> running: Automatically suppress extra running events
3709 // stopped -> running: Report except when there is one or more no votes
3710 // and no yes votes.
3711 SynchronouslyNotifyStateChanged (state);
3712 if (m_force_next_event_delivery)
3713 return_value = true;
3714 else
3715 {
3716 switch (m_last_broadcast_state)
3717 {
3718 case eStateRunning:
3719 case eStateStepping:
3720 // We always suppress multiple runnings with no PUBLIC stop in between.
3721 return_value = false;
3722 break;
3723 default:
3724 // TODO: make this work correctly. For now always report
3725 // run if we aren't running so we don't miss any running
3726 // events. If I run the lldb/test/thread/a.out file and
3727 // break at main.cpp:58, run and hit the breakpoints on
3728 // multiple threads, then somehow during the stepping over
3729 // of all breakpoints no run gets reported.
3730
3731 // This is a transition from stop to run.
3732 switch (m_thread_list.ShouldReportRun (event_ptr))
3733 {
3734 case eVoteYes:
3735 case eVoteNoOpinion:
3736 return_value = true;
3737 break;
3738 case eVoteNo:
3739 return_value = false;
3740 break;
3741 }
3742 break;
3743 }
3744 }
3745 break;
3746 case eStateStopped:
3747 case eStateCrashed:
3748 case eStateSuspended:
3749 {
3750 // We've stopped. First see if we're going to restart the target.
3751 // If we are going to stop, then we always broadcast the event.
3752 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
3753 // If no thread has an opinion, we don't report it.
3754
3755 RefreshStateAfterStop ();
3756 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
3757 {
3758 if (log)
3759 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3760 static_cast<void*>(event_ptr),
3761 StateAsCString(state));
3762 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3763 // so they can properly set their state.
3764 m_thread_list.ShouldStop (event_ptr);
3765 return_value = true;
3766 }
3767 else
3768 {
3769 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3770 bool should_resume = false;
3771
3772 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3773 // Asking the thread list is also not likely to go well, since we are running again.
3774 // So in that case just report the event.
3775
3776 if (!was_restarted)
3777 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3778
3779 if (was_restarted || should_resume || m_resume_requested)
3780 {
3781 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3782 if (log)
3783 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3784 should_resume, StateAsCString(state),
3785 was_restarted, stop_vote);
3786
3787 switch (stop_vote)
3788 {
3789 case eVoteYes:
3790 return_value = true;
3791 break;
3792 case eVoteNoOpinion:
3793 case eVoteNo:
3794 return_value = false;
3795 break;
3796 }
3797
3798 if (!was_restarted)
3799 {
3800 if (log)
3801 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3802 static_cast<void*>(event_ptr),
3803 StateAsCString(state));
3804 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3805 PrivateResume ();
3806 }
3807
3808 }
3809 else
3810 {
3811 return_value = true;
3812 SynchronouslyNotifyStateChanged (state);
3813 }
3814 }
3815 }
3816 break;
3817 }
3818
3819 // Forcing the next event delivery is a one shot deal. So reset it here.
3820 m_force_next_event_delivery = false;
3821
3822 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3823 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3824 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3825 // because the PublicState reflects the last event pulled off the queue, and there may be several
3826 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3827 // yet. m_last_broadcast_state gets updated here.
3828
3829 if (return_value)
3830 m_last_broadcast_state = state;
3831
3832 if (log)
3833 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3834 static_cast<void*>(event_ptr), StateAsCString(state),
3835 StateAsCString(m_last_broadcast_state),
3836 return_value ? "YES" : "NO");
3837 return return_value;
3838}
3839
3840
3841bool
3842Process::StartPrivateStateThread (bool force)
3843{
3844 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS(1u << 4)));
3845
3846 bool already_running = PrivateStateThreadIsValid ();
3847 if (log)
3848 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3849
3850 if (!force && already_running)
3851 return true;
3852
3853 // Create a thread that watches our internal state and controls which
3854 // events make it to clients (into the DCProcess event queue).
3855 char thread_name[1024];
3856
3857 if (HostInfo::GetMaxThreadNameLength() <= 30)
3858 {
3859 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3860 if (already_running)
3861 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3862 else
3863 snprintf(thread_name, sizeof(thread_name), "intern-state");
3864 }
3865 else
3866 {
3867 if (already_running)
3868 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64"l" "u" ")>", GetID());
3869 else
3870 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64"l" "u" ")>", GetID());
3871 }
3872
3873 // Create the private state thread, and start it running.
3874 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL__null);
3875 if (m_private_state_thread.IsJoinable())
3876 {
3877 ResumePrivateStateThread();
3878 return true;
3879 }
3880 else
3881 return false;
3882}
3883
3884void
3885Process::PausePrivateStateThread ()
3886{
3887 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3888}
3889
3890void
3891Process::ResumePrivateStateThread ()
3892{
3893 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3894}
3895
3896void
3897Process::StopPrivateStateThread ()
3898{
3899 if (PrivateStateThreadIsValid ())
3900 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
3901 else
3902 {
3903 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1)));
3904 if (log)
3905 log->Printf ("Went to stop the private state thread, but it was already invalid.");
3906 }
3907}
3908
3909void
3910Process::ControlPrivateStateThread (uint32_t signal)
3911{
3912 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1)));
3913
3914 assert (signal == eBroadcastInternalStateControlStop ||((signal == eBroadcastInternalStateControlStop || signal == eBroadcastInternalStateControlPause
|| signal == eBroadcastInternalStateControlResume) ? static_cast
<void> (0) : __assert_fail ("signal == eBroadcastInternalStateControlStop || signal == eBroadcastInternalStateControlPause || signal == eBroadcastInternalStateControlResume"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 3916, __PRETTY_FUNCTION__))
3915 signal == eBroadcastInternalStateControlPause ||((signal == eBroadcastInternalStateControlStop || signal == eBroadcastInternalStateControlPause
|| signal == eBroadcastInternalStateControlResume) ? static_cast
<void> (0) : __assert_fail ("signal == eBroadcastInternalStateControlStop || signal == eBroadcastInternalStateControlPause || signal == eBroadcastInternalStateControlResume"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 3916, __PRETTY_FUNCTION__))
3916 signal == eBroadcastInternalStateControlResume)((signal == eBroadcastInternalStateControlStop || signal == eBroadcastInternalStateControlPause
|| signal == eBroadcastInternalStateControlResume) ? static_cast
<void> (0) : __assert_fail ("signal == eBroadcastInternalStateControlStop || signal == eBroadcastInternalStateControlPause || signal == eBroadcastInternalStateControlResume"
, "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Target/Process.cpp"
, 3916, __PRETTY_FUNCTION__))
;
3917
3918 if (log)
3919 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
3920
3921 // Signal the private state thread. First we should copy this is case the
3922 // thread starts exiting since the private state thread will NULL this out
3923 // when it exits
3924 HostThread private_state_thread(m_private_state_thread);
3925 if (private_state_thread.IsJoinable())
3926 {
3927 TimeValue timeout_time;
3928 bool timed_out;
3929
3930 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL__null);
3931
3932 timeout_time = TimeValue::Now();
3933 timeout_time.OffsetWithSeconds(2);
3934 if (log)
3935 log->Printf ("Sending control event of type: %d.", signal);
3936 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3937 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3938
3939 if (signal == eBroadcastInternalStateControlStop)
3940 {
3941 if (timed_out)
3942 {
3943 Error error = private_state_thread.Cancel();
3944 if (log)
3945 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3946 }
3947 else
3948 {
3949 if (log)
3950 log->Printf ("The control event killed the private state thread without having to cancel.");
3951 }
3952
3953 thread_result_t result = NULL__null;
3954 private_state_thread.Join(&result);
3955 m_private_state_thread.Reset();
3956 }
3957 }
3958 else
3959 {
3960 if (log)
3961 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3962 }
3963}
3964
3965void
3966Process::SendAsyncInterrupt ()
3967{
3968 if (PrivateStateThreadIsValid())
3969 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL__null);
3970 else
3971 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL__null);
3972}
3973
3974void
3975Process::HandlePrivateEvent (EventSP &event_sp)
3976{
3977 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
3978 m_resume_requested = false;
3979
3980 m_currently_handling_event.SetValue(true, eBroadcastNever);
3981
3982 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3983
3984 // First check to see if anybody wants a shot at this event:
3985 if (m_next_event_action_ap.get() != NULL__null)
3986 {
3987 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
3988 if (log)
3989 log->Printf ("Ran next event action, result was %d.", action_result);
3990
3991 switch (action_result)
3992 {
3993 case NextEventAction::eEventActionSuccess:
3994 SetNextEventAction(NULL__null);
3995 break;
3996
3997 case NextEventAction::eEventActionRetry:
3998 break;
3999
4000 case NextEventAction::eEventActionExit:
4001 // Handle Exiting Here. If we already got an exited event,
4002 // we should just propagate it. Otherwise, swallow this event,
4003 // and set our state to exit so the next event will kill us.
4004 if (new_state != eStateExited)
4005 {
4006 // FIXME: should cons up an exited event, and discard this one.
4007 SetExitStatus(0, m_next_event_action_ap->GetExitString());
4008 m_currently_handling_event.SetValue(false, eBroadcastAlways);
4009 SetNextEventAction(NULL__null);
4010 return;
4011 }
4012 SetNextEventAction(NULL__null);
4013 break;
4014 }
4015 }
4016
4017 // See if we should broadcast this state to external clients?
4018 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
4019
4020 if (should_broadcast)
4021 {
4022 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
4023 if (log)
4024 {
4025 log->Printf ("Process::%s (pid = %" PRIu64"l" "u" ") broadcasting new state %s (old state %s) to %s",
4026 __FUNCTION__,
4027 GetID(),
4028 StateAsCString(new_state),
4029 StateAsCString (GetState ()),
4030 is_hijacked ? "hijacked" : "public");
4031 }
4032 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
4033 if (StateIsRunningState (new_state))
4034 {
4035 // Only push the input handler if we aren't fowarding events,
4036 // as this means the curses GUI is in use...
4037 // Or don't push it if we are launching since it will come up stopped.
4038 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
4039 PushProcessIOHandler ();
4040 m_iohandler_sync.SetValue(true, eBroadcastAlways);
4041 }
4042 else if (StateIsStoppedState(new_state, false))
4043 {
4044 m_iohandler_sync.SetValue(false, eBroadcastNever);
4045 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4046 {
4047 // If the lldb_private::Debugger is handling the events, we don't
4048 // want to pop the process IOHandler here, we want to do it when
4049 // we receive the stopped event so we can carefully control when
4050 // the process IOHandler is popped because when we stop we want to
4051 // display some text stating how and why we stopped, then maybe some
4052 // process/thread/frame info, and then we want the "(lldb) " prompt
4053 // to show up. If we pop the process IOHandler here, then we will
4054 // cause the command interpreter to become the top IOHandler after
4055 // the process pops off and it will update its prompt right away...
4056 // See the Debugger.cpp file where it calls the function as
4057 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4058 // Otherwise we end up getting overlapping "(lldb) " prompts and
4059 // garbled output.
4060 //
4061 // If we aren't handling the events in the debugger (which is indicated
4062 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4063 // are hijacked, then we always pop the process IO handler manually.
4064 // Hijacking happens when the internal process state thread is running
4065 // thread plans, or when commands want to run in synchronous mode
4066 // and they call "process->WaitForProcessToStop()". An example of something
4067 // that will hijack the events is a simple expression:
4068 //
4069 // (lldb) expr (int)puts("hello")
4070 //
4071 // This will cause the internal process state thread to resume and halt
4072 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4073 // events) and we do need the IO handler to be pushed and popped
4074 // correctly.
4075
4076 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4077 PopProcessIOHandler ();
4078 }
4079 }
4080
4081 BroadcastEvent (event_sp);
4082 }
4083 else
4084 {
4085 if (log)
4086 {
4087 log->Printf ("Process::%s (pid = %" PRIu64"l" "u" ") suppressing state %s (old state %s): should_broadcast == false",
4088 __FUNCTION__,
4089 GetID(),
4090 StateAsCString(new_state),
4091 StateAsCString (GetState ()));
4092 }
4093 }
4094 m_currently_handling_event.SetValue(false, eBroadcastAlways);
4095}
4096
4097thread_result_t
4098Process::PrivateStateThread (void *arg)
4099{
4100 Process *proc = static_cast<Process*> (arg);
4101 thread_result_t result = proc->RunPrivateStateThread();
4102 return result;
4103}
4104
4105thread_result_t
4106Process::RunPrivateStateThread ()
4107{
4108 bool control_only = true;
4109 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4110
4111 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
4112 if (log)
4113 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64"l" "u" ") thread starting...",
4114 __FUNCTION__, static_cast<void*>(this), GetID());
4115
4116 bool exit_now = false;
4117 while (!exit_now)
4118 {
4119 EventSP event_sp;
4120 WaitForEventsPrivate (NULL__null, event_sp, control_only);
4121 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4122 {
4123 if (log)
4124 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64"l" "u" ") got a control event: %d",
4125 __FUNCTION__, static_cast<void*>(this), GetID(),
4126 event_sp->GetType());
4127
4128 switch (event_sp->GetType())
4129 {
4130 case eBroadcastInternalStateControlStop:
4131 exit_now = true;
4132 break; // doing any internal state management below
4133
4134 case eBroadcastInternalStateControlPause:
4135 control_only = true;
4136 break;
4137
4138 case eBroadcastInternalStateControlResume:
4139 control_only = false;
4140 break;
4141 }
4142
4143 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4144 continue;
4145 }
4146 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4147 {
4148 if (m_public_state.GetValue() == eStateAttaching)
4149 {
4150 if (log)
4151 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64"l" "u" ") woke up with an interrupt while attaching - forwarding interrupt.",
4152 __FUNCTION__, static_cast<void*>(this),
4153 GetID());
4154 BroadcastEvent (eBroadcastBitInterrupt, NULL__null);
4155 }
4156 else
4157 {
4158 if (log)
4159 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64"l" "u" ") woke up with an interrupt - Halting.",
4160 __FUNCTION__, static_cast<void*>(this),
4161 GetID());
4162 Halt();
4163 }
4164 continue;
4165 }
4166
4167 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4168
4169 if (internal_state != eStateInvalid)
4170 {
4171 if (m_clear_thread_plans_on_stop &&
4172 StateIsStoppedState(internal_state, true))
4173 {
4174 m_clear_thread_plans_on_stop = false;
4175 m_thread_list.DiscardThreadPlans();
4176 }
4177 HandlePrivateEvent (event_sp);
4178 }
4179
4180 if (internal_state == eStateInvalid ||
4181 internal_state == eStateExited ||
4182 internal_state == eStateDetached )
4183 {
4184 if (log)
4185 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64"l" "u" ") about to exit with internal state %s...",
4186 __FUNCTION__, static_cast<void*>(this), GetID(),
4187 StateAsCString(internal_state));
4188
4189 break;
4190 }
4191 }
4192
4193 // Verify log is still enabled before attempting to write to it...
4194 if (log)
4195 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64"l" "u" ") thread exiting...",
4196 __FUNCTION__, static_cast<void*>(this), GetID());
4197
4198 m_public_run_lock.SetStopped();
4199 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4200 m_private_state_thread.Reset();
4201 return NULL__null;
4202}
4203
4204//------------------------------------------------------------------
4205// Process Event Data
4206//------------------------------------------------------------------
4207
4208Process::ProcessEventData::ProcessEventData () :
4209 EventData (),
4210 m_process_sp (),
4211 m_state (eStateInvalid),
4212 m_restarted (false),
4213 m_update_state (0),
4214 m_interrupted (false)
4215{
4216}
4217
4218Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4219 EventData (),
4220 m_process_sp (process_sp),
4221 m_state (state),
4222 m_restarted (false),
4223 m_update_state (0),
4224 m_interrupted (false)
4225{
4226}
4227
4228Process::ProcessEventData::~ProcessEventData()
4229{
4230}
4231
4232const ConstString &
4233Process::ProcessEventData::GetFlavorString ()
4234{
4235 static ConstString g_flavor ("Process::ProcessEventData");
4236 return g_flavor;
4237}
4238
4239const ConstString &
4240Process::ProcessEventData::GetFlavor () const
4241{
4242 return ProcessEventData::GetFlavorString ();
4243}
4244
4245void
4246Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4247{
4248 // This function gets called twice for each event, once when the event gets pulled
4249 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4250 // the public event queue, then other times when we're pretending that this is where we stopped at the
4251 // end of expression evaluation. m_update_state is used to distinguish these
4252 // three cases; it is 0 when we're just pulling it off for private handling,
4253 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
4254 if (m_update_state != 1)
4255 return;
4256
4257 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4258
4259 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4260 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4261 // end up restarting the process.
4262 if (m_interrupted)
4263 return;
4264
4265 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4266 if (m_state == eStateStopped && ! m_restarted)
4267 {
4268 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
4269 uint32_t num_threads = curr_thread_list.GetSize();
4270 uint32_t idx;
4271
4272 // The actions might change one of the thread's stop_info's opinions about whether we should
4273 // stop the process, so we need to query that as we go.
4274
4275 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4276 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4277 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4278 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back
4279 // against this list & bag out if anything differs.
4280 std::vector<uint32_t> thread_index_array(num_threads);
4281 for (idx = 0; idx < num_threads; ++idx)
4282 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4283
4284 // Use this to track whether we should continue from here. We will only continue the target running if
4285 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4286 // then it doesn't matter what the other threads say...
4287
4288 bool still_should_stop = false;
4289
4290 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4291 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4292 // thing to do is, and it's better to let the user decide than continue behind their backs.
4293
4294 bool does_anybody_have_an_opinion = false;
4295
4296 for (idx = 0; idx < num_threads; ++idx)
4297 {
4298 curr_thread_list = m_process_sp->GetThreadList();
4299 if (curr_thread_list.GetSize() != num_threads)
4300 {
4301 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP(1u << 7) | LIBLLDB_LOG_PROCESS(1u << 1)));
4302 if (log)
4303 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
4304 break;
4305 }
4306
4307 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4308
4309 if (thread_sp->GetIndexID() != thread_index_array[idx])
4310 {
4311 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP(1u << 7) | LIBLLDB_LOG_PROCESS(1u << 1)));
4312 if (log)
4313 log->Printf("The thread at position %u changed from %u to %u while processing event.",
4314 idx,
4315 thread_index_array[idx],
4316 thread_sp->GetIndexID());
4317 break;
4318 }
4319
4320 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
4321 if (stop_info_sp && stop_info_sp->IsValid())
4322 {
4323 does_anybody_have_an_opinion = true;
4324 bool this_thread_wants_to_stop;
4325 if (stop_info_sp->GetOverrideShouldStop())
4326 {
4327 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4328 }
4329 else
4330 {
4331 stop_info_sp->PerformAction(event_ptr);
4332 // The stop action might restart the target. If it does, then we want to mark that in the
4333 // event so that whoever is receiving it will know to wait for the running event and reflect
4334 // that state appropriately.
4335 // We also need to stop processing actions, since they aren't expecting the target to be running.
4336
4337 // FIXME: we might have run.
4338 if (stop_info_sp->HasTargetRunSinceMe())
4339 {
4340 SetRestarted (true);
4341 break;
4342 }
4343
4344 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4345 }
4346
4347 if (still_should_stop == false)
4348 still_should_stop = this_thread_wants_to_stop;
4349 }
4350 }
4351
4352
4353 if (!GetRestarted())
4354 {
4355 if (!still_should_stop && does_anybody_have_an_opinion)
4356 {
4357 // We've been asked to continue, so do that here.
4358 SetRestarted(true);
4359 // Use the public resume method here, since this is just
4360 // extending a public resume.
4361 m_process_sp->PrivateResume();
4362 }
4363 else
4364 {
4365 // If we didn't restart, run the Stop Hooks here:
4366 // They might also restart the target, so watch for that.
4367 m_process_sp->GetTarget().RunStopHooks();
4368 if (m_process_sp->GetPrivateState() == eStateRunning)
4369 SetRestarted(true);
4370 }
4371 }
4372 }
4373}
4374
4375void
4376Process::ProcessEventData::Dump (Stream *s) const
4377{
4378 if (m_process_sp)
4379 s->Printf(" process = %p (pid = %" PRIu64"l" "u" "), ",
4380 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
4381
4382 s->Printf("state = %s", StateAsCString(GetState()));
4383}
4384
4385const Process::ProcessEventData *
4386Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4387{
4388 if (event_ptr)
4389 {
4390 const EventData *event_data = event_ptr->GetData();
4391 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4392 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4393 }
4394 return NULL__null;
4395}
4396
4397ProcessSP
4398Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4399{
4400 ProcessSP process_sp;
4401 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4402 if (data)
4403 process_sp = data->GetProcessSP();
4404 return process_sp;
4405}
4406
4407StateType
4408Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4409{
4410 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4411 if (data == NULL__null)
4412 return eStateInvalid;
4413 else
4414 return data->GetState();
4415}
4416
4417bool
4418Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4419{
4420 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4421 if (data == NULL__null)
4422 return false;
4423 else
4424 return data->GetRestarted();
4425}
4426
4427void
4428Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4429{
4430 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4431 if (data != NULL__null)
4432 data->SetRestarted(new_value);
4433}
4434
4435size_t
4436Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4437{
4438 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4439 if (data != NULL__null)
4440 return data->GetNumRestartedReasons();
4441 else
4442 return 0;
4443}
4444
4445const char *
4446Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4447{
4448 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4449 if (data != NULL__null)
4450 return data->GetRestartedReasonAtIndex(idx);
4451 else
4452 return NULL__null;
4453}
4454
4455void
4456Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4457{
4458 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4459 if (data != NULL__null)
4460 data->AddRestartedReason(reason);
4461}
4462
4463bool
4464Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4465{
4466 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4467 if (data == NULL__null)
4468 return false;
4469 else
4470 return data->GetInterrupted ();
4471}
4472
4473void
4474Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4475{
4476 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4477 if (data != NULL__null)
4478 data->SetInterrupted(new_value);
4479}
4480
4481bool
4482Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4483{
4484 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4485 if (data)
4486 {
4487 data->SetUpdateStateOnRemoval();
4488 return true;
4489 }
4490 return false;
4491}
4492
4493lldb::TargetSP
4494Process::CalculateTarget ()
4495{
4496 return m_target.shared_from_this();
4497}
4498
4499void
4500Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
4501{
4502 exe_ctx.SetTargetPtr (&m_target);
4503 exe_ctx.SetProcessPtr (this);
4504 exe_ctx.SetThreadPtr(NULL__null);
4505 exe_ctx.SetFramePtr (NULL__null);
4506}
4507
4508//uint32_t
4509//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4510//{
4511// return 0;
4512//}
4513//
4514//ArchSpec
4515//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4516//{
4517// return Host::GetArchSpecForExistingProcess (pid);
4518//}
4519//
4520//ArchSpec
4521//Process::GetArchSpecForExistingProcess (const char *process_name)
4522//{
4523// return Host::GetArchSpecForExistingProcess (process_name);
4524//}
4525//
4526void
4527Process::AppendSTDOUT (const char * s, size_t len)
4528{
4529 Mutex::Locker locker (m_stdio_communication_mutex);
4530 m_stdout_data.append (s, len);
4531 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
4532}
4533
4534void
4535Process::AppendSTDERR (const char * s, size_t len)
4536{
4537 Mutex::Locker locker (m_stdio_communication_mutex);
4538 m_stderr_data.append (s, len);
4539 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
4540}
4541
4542void
4543Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
4544{
4545 Mutex::Locker locker (m_profile_data_comm_mutex);
4546 m_profile_data.push_back(one_profile_data);
4547 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4548}
4549
4550size_t
4551Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4552{
4553 Mutex::Locker locker(m_profile_data_comm_mutex);
4554 if (m_profile_data.empty())
4555 return 0;
4556
4557 std::string &one_profile_data = m_profile_data.front();
4558 size_t bytes_available = one_profile_data.size();
4559 if (bytes_available > 0)
4560 {
4561 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
4562 if (log)
4563 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64"l" "u" ")",
4564 static_cast<void*>(buf),
4565 static_cast<uint64_t>(buf_size));
4566 if (bytes_available > buf_size)
4567 {
4568 memcpy(buf, one_profile_data.c_str(), buf_size);
4569 one_profile_data.erase(0, buf_size);
4570 bytes_available = buf_size;
4571 }
4572 else
4573 {
4574 memcpy(buf, one_profile_data.c_str(), bytes_available);
4575 m_profile_data.erase(m_profile_data.begin());
4576 }
4577 }
4578 return bytes_available;
4579}
4580
4581
4582//------------------------------------------------------------------
4583// Process STDIO
4584//------------------------------------------------------------------
4585
4586size_t
4587Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4588{
4589 Mutex::Locker locker(m_stdio_communication_mutex);
4590 size_t bytes_available = m_stdout_data.size();
4591 if (bytes_available > 0)
4592 {
4593 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
4594 if (log)
4595 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64"l" "u" ")",
4596 static_cast<void*>(buf),
4597 static_cast<uint64_t>(buf_size));
4598 if (bytes_available > buf_size)
4599 {
4600 memcpy(buf, m_stdout_data.c_str(), buf_size);
4601 m_stdout_data.erase(0, buf_size);
4602 bytes_available = buf_size;
4603 }
4604 else
4605 {
4606 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4607 m_stdout_data.clear();
4608 }
4609 }
4610 return bytes_available;
4611}
4612
4613
4614size_t
4615Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4616{
4617 Mutex::Locker locker(m_stdio_communication_mutex);
4618 size_t bytes_available = m_stderr_data.size();
4619 if (bytes_available > 0)
4620 {
4621 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
4622 if (log)
4623 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64"l" "u" ")",
4624 static_cast<void*>(buf),
4625 static_cast<uint64_t>(buf_size));
4626 if (bytes_available > buf_size)
4627 {
4628 memcpy(buf, m_stderr_data.c_str(), buf_size);
4629 m_stderr_data.erase(0, buf_size);
4630 bytes_available = buf_size;
4631 }
4632 else
4633 {
4634 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4635 m_stderr_data.clear();
4636 }
4637 }
4638 return bytes_available;
4639}
4640
4641void
4642Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4643{
4644 Process *process = (Process *) baton;
4645 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4646}
4647
4648class IOHandlerProcessSTDIO :
4649 public IOHandler
4650{
4651public:
4652 IOHandlerProcessSTDIO (Process *process,
4653 int write_fd) :
4654 IOHandler(process->GetTarget().GetDebugger()),
4655 m_process (process),
4656 m_read_file (),
4657 m_write_file (write_fd, false),
4658 m_pipe ()
4659 {
4660 m_read_file.SetDescriptor(GetInputFD(), false);
4661 }
4662
4663 virtual
4664 ~IOHandlerProcessSTDIO ()
4665 {
4666
4667 }
4668
4669 bool
4670 OpenPipes ()
4671 {
4672 if (m_pipe.IsValid())
4673 return true;
4674 return m_pipe.Open();
4675 }
4676
4677 void
4678 ClosePipes()
4679 {
4680 m_pipe.Close();
4681 }
4682
4683 // Each IOHandler gets to run until it is done. It should read data
4684 // from the "in" and place output into "out" and "err and return
4685 // when done.
4686 virtual void
4687 Run ()
4688 {
4689 if (m_read_file.IsValid() && m_write_file.IsValid())
4690 {
4691 SetIsDone(false);
4692 if (OpenPipes())
4693 {
4694 const int read_fd = m_read_file.GetDescriptor();
4695 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4696 TerminalState terminal_state;
4697 terminal_state.Save (read_fd, false);
4698 Terminal terminal(read_fd);
4699 terminal.SetCanonical(false);
4700 terminal.SetEcho(false);
4701// FD_ZERO, FD_SET are not supported on windows
4702#ifndef _WIN32
4703 while (!GetIsDone())
4704 {
4705 fd_set read_fdset;
4706 FD_ZERO (&read_fdset)do { int __d0, __d1; __asm__ __volatile__ ("cld; rep; " "stosq"
: "=c" (__d0), "=D" (__d1) : "a" (0), "0" (sizeof (fd_set) /
sizeof (__fd_mask)), "1" (&((&read_fdset)->fds_bits
)[0]) : "memory"); } while (0)
;
4707 FD_SET (read_fd, &read_fdset)((void) (((&read_fdset)->fds_bits)[__extension__ ({ long
int __d = (read_fd); (__builtin_constant_p (__d) ? (0 <= __d
&& __d < 1024 ? (__d / (8 * (int) sizeof (__fd_mask
))) : __fdelt_warn (__d)) : __fdelt_chk (__d)); })] |= ((__fd_mask
) 1 << ((read_fd) % (8 * (int) sizeof (__fd_mask))))))
;
4708 FD_SET (pipe_read_fd, &read_fdset)((void) (((&read_fdset)->fds_bits)[__extension__ ({ long
int __d = (pipe_read_fd); (__builtin_constant_p (__d) ? (0 <=
__d && __d < 1024 ? (__d / (8 * (int) sizeof (__fd_mask
))) : __fdelt_warn (__d)) : __fdelt_chk (__d)); })] |= ((__fd_mask
) 1 << ((pipe_read_fd) % (8 * (int) sizeof (__fd_mask))
))))
;
4709 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4710 int num_set_fds = select (nfds, &read_fdset, NULL__null, NULL__null, NULL__null);
4711 if (num_set_fds < 0)
4712 {
4713 const int select_errno = errno(*__errno_location ());
4714
4715 if (select_errno != EINTR4)
4716 SetIsDone(true);
4717 }
4718 else if (num_set_fds > 0)
4719 {
4720 char ch = 0;
4721 size_t n;
4722 if (FD_ISSET (read_fd, &read_fdset)((((&read_fdset)->fds_bits)[__extension__ ({ long int __d
= (read_fd); (__builtin_constant_p (__d) ? (0 <= __d &&
__d < 1024 ? (__d / (8 * (int) sizeof (__fd_mask))) : __fdelt_warn
(__d)) : __fdelt_chk (__d)); })] & ((__fd_mask) 1 <<
((read_fd) % (8 * (int) sizeof (__fd_mask))))) != 0)
)
4723 {
4724 n = 1;
4725 if (m_read_file.Read(&ch, n).Success() && n == 1)
4726 {
4727 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4728 SetIsDone(true);
4729 }
4730 else
4731 SetIsDone(true);
4732 }
4733 if (FD_ISSET (pipe_read_fd, &read_fdset)((((&read_fdset)->fds_bits)[__extension__ ({ long int __d
= (pipe_read_fd); (__builtin_constant_p (__d) ? (0 <= __d
&& __d < 1024 ? (__d / (8 * (int) sizeof (__fd_mask
))) : __fdelt_warn (__d)) : __fdelt_chk (__d)); })] & ((__fd_mask
) 1 << ((pipe_read_fd) % (8 * (int) sizeof (__fd_mask))
))) != 0)
)
4734 {
4735 // Consume the interrupt byte
4736 if (m_pipe.Read (&ch, 1) == 1)
4737 {
4738 switch (ch)
4739 {
4740 case 'q':
4741 SetIsDone(true);
4742 break;
4743 case 'i':
4744 if (StateIsRunningState(m_process->GetState()))
4745 m_process->Halt();
4746 break;
4747 }
4748 }
4749 }
4750 }
4751 }
4752#endif
4753 terminal_state.Restore();
4754
4755 }
4756 else
4757 SetIsDone(true);
4758 }
4759 else
4760 SetIsDone(true);
4761 }
4762
4763 // Hide any characters that have been displayed so far so async
4764 // output can be displayed. Refresh() will be called after the
4765 // output has been displayed.
4766 virtual void
4767 Hide ()
4768 {
4769
4770 }
4771 // Called when the async output has been received in order to update
4772 // the input reader (refresh the prompt and redisplay any current
4773 // line(s) that are being edited
4774 virtual void
4775 Refresh ()
4776 {
4777
4778 }
4779
4780 virtual void
4781 Cancel ()
4782 {
4783 char ch = 'q'; // Send 'q' for quit
4784 m_pipe.Write (&ch, 1);
4785 }
4786
4787 virtual bool
4788 Interrupt ()
4789 {
4790 // Do only things that are safe to do in an interrupt context (like in
4791 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4792 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4793 // that was written to the pipe and then call m_process->Halt() from a
4794 // much safer location in code.
4795 if (m_active)
4796 {
4797 char ch = 'i'; // Send 'i' for interrupt
4798 return m_pipe.Write (&ch, 1) == 1;
4799 }
4800 else
4801 {
4802 // This IOHandler might be pushed on the stack, but not being run currently
4803 // so do the right thing if we aren't actively watching for STDIN by sending
4804 // the interrupt to the process. Otherwise the write to the pipe above would
4805 // do nothing. This can happen when the command interpreter is running and
4806 // gets a "expression ...". It will be on the IOHandler thread and sending
4807 // the input is complete to the delegate which will cause the expression to
4808 // run, which will push the process IO handler, but not run it.
4809
4810 if (StateIsRunningState(m_process->GetState()))
4811 {
4812 m_process->SendAsyncInterrupt();
4813 return true;
4814 }
4815 }
4816 return false;
4817 }
4818
4819 virtual void
4820 GotEOF()
4821 {
4822
4823 }
4824
4825protected:
4826 Process *m_process;
4827 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4828 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
4829 Pipe m_pipe;
4830};
4831
4832void
4833Process::SetSTDIOFileDescriptor (int fd)
4834{
4835 // First set up the Read Thread for reading/handling process I/O
4836
4837 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
4838
4839 if (conn_ap.get())
4840 {
4841 m_stdio_communication.SetConnection (conn_ap.release());
4842 if (m_stdio_communication.IsConnected())
4843 {
4844 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4845 m_stdio_communication.StartReadThread();
4846
4847 // Now read thread is set up, set up input reader.
4848
4849 if (!m_process_input_reader.get())
4850 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
4851 }
4852 }
4853}
4854
4855bool
4856Process::ProcessIOHandlerIsActive ()
4857{
4858 IOHandlerSP io_handler_sp (m_process_input_reader);
4859 if (io_handler_sp)
4860 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4861 return false;
4862}
4863bool
4864Process::PushProcessIOHandler ()
4865{
4866 IOHandlerSP io_handler_sp (m_process_input_reader);
4867 if (io_handler_sp)
4868 {
4869 io_handler_sp->SetIsDone(false);
4870 m_target.GetDebugger().PushIOHandler (io_handler_sp);
4871 return true;
4872 }
4873 return false;
4874}
4875
4876bool
4877Process::PopProcessIOHandler ()
4878{
4879 IOHandlerSP io_handler_sp (m_process_input_reader);
4880 if (io_handler_sp)
4881 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4882 return false;
4883}
4884
4885// The process needs to know about installed plug-ins
4886void
4887Process::SettingsInitialize ()
4888{
4889 Thread::SettingsInitialize ();
4890}
4891
4892void
4893Process::SettingsTerminate ()
4894{
4895 Thread::SettingsTerminate ();
4896}
4897
4898ExpressionResults
4899Process::RunThreadPlan (ExecutionContext &exe_ctx,
4900 lldb::ThreadPlanSP &thread_plan_sp,
4901 const EvaluateExpressionOptions &options,
4902 Stream &errors)
4903{
4904 ExpressionResults return_value = eExpressionSetupError;
4905
4906 if (thread_plan_sp.get() == NULL__null)
4907 {
4908 errors.Printf("RunThreadPlan called with empty thread plan.");
4909 return eExpressionSetupError;
4910 }
4911
4912 if (!thread_plan_sp->ValidatePlan(NULL__null))
4913 {
4914 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4915 return eExpressionSetupError;
4916 }
4917
4918 if (exe_ctx.GetProcessPtr() != this)
4919 {
4920 errors.Printf("RunThreadPlan called on wrong process.");
4921 return eExpressionSetupError;
4922 }
4923
4924 Thread *thread = exe_ctx.GetThreadPtr();
4925 if (thread == NULL__null)
4926 {
4927 errors.Printf("RunThreadPlan called with invalid thread.");
4928 return eExpressionSetupError;
4929 }
4930
4931 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4932 // For that to be true the plan can't be private - since private plans suppress themselves in the
4933 // GetCompletedPlan call.
4934
4935 bool orig_plan_private = thread_plan_sp->GetPrivate();
4936 thread_plan_sp->SetPrivate(false);
4937
4938 if (m_private_state.GetValue() != eStateStopped)
4939 {
4940 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
4941 return eExpressionSetupError;
4942 }
4943
4944 // Save the thread & frame from the exe_ctx for restoration after we run
4945 const uint32_t thread_idx_id = thread->GetIndexID();
4946 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4947 if (!selected_frame_sp)
4948 {
4949 thread->SetSelectedFrame(0);
4950 selected_frame_sp = thread->GetSelectedFrame();
4951 if (!selected_frame_sp)
4952 {
4953 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4954 return eExpressionSetupError;
4955 }
4956 }
4957
4958 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4959
4960 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4961 // so we should arrange to reset them as well.
4962
4963 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4964
4965 uint32_t selected_tid;
4966 StackID selected_stack_id;
4967 if (selected_thread_sp)
4968 {
4969 selected_tid = selected_thread_sp->GetIndexID();
4970 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4971 }
4972 else
4973 {
4974 selected_tid = LLDB_INVALID_THREAD_ID0;
4975 }
4976
4977 HostThread backup_private_state_thread;
4978 lldb::StateType old_state;
4979 lldb::ThreadPlanSP stopper_base_plan_sp;
4980
4981 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP(1u << 7) | LIBLLDB_LOG_PROCESS(1u << 1)));
4982 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
4983 {
4984 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4985 // we are the thread that is generating public events.
4986 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
4987 // we are fielding public events here.
4988 if (log)
4989 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4990
4991 backup_private_state_thread = m_private_state_thread;
4992
4993 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4994 // returning control here.
4995 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4996 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4997 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4998 // do just what we want.
4999 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5000 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5001 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5002 old_state = m_public_state.GetValue();
5003 m_public_state.SetValueNoLock(eStateStopped);
5004
5005 // Now spin up the private state thread:
5006 StartPrivateStateThread(true);
5007 }
5008
5009 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
5010
5011 if (options.GetDebug())
5012 {
5013 // In this case, we aren't actually going to run, we just want to stop right away.
5014 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5015 // FIXME: To make this prettier we should invent some stop reason for this, but that
5016 // is only cosmetic, and this functionality is only of use to lldb developers who can
5017 // live with not pretty...
5018 thread->Flush();
5019 return eExpressionStoppedForDebug;
5020 }
5021
5022 Listener listener("lldb.process.listener.run-thread-plan");
5023
5024 lldb::EventSP event_to_broadcast_sp;
5025
5026 {
5027 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5028 // restored on exit to the function.
5029 //
5030 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5031 // is put into event_to_broadcast_sp for rebroadcasting.
5032
5033 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
5034
5035 if (log)
5036 {
5037 StreamString s;
5038 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5039 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64"l" "x" " to run thread plan \"%s\".",
5040 thread->GetIndexID(),
5041 thread->GetID(),
5042 s.GetData());
5043 }
5044
5045 bool got_event;
5046 lldb::EventSP event_sp;
5047 lldb::StateType stop_state = lldb::eStateInvalid;
5048
5049 TimeValue* timeout_ptr = NULL__null;
5050 TimeValue real_timeout;
5051
5052 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
5053 bool do_resume = true;
5054 bool handle_running_event = true;
5055 const uint64_t default_one_thread_timeout_usec = 250000;
5056
5057 // This is just for accounting:
5058 uint32_t num_resumes = 0;
5059
5060 uint32_t timeout_usec = options.GetTimeoutUsec();
5061 uint32_t one_thread_timeout_usec;
5062 uint32_t all_threads_timeout_usec = 0;
5063
5064 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5065 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5066 // first timeout already.
5067
5068 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5069 {
5070 before_first_timeout = false;
5071 one_thread_timeout_usec = 0;
5072 all_threads_timeout_usec = timeout_usec;
5073 }
5074 else
5075 {
5076 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
5077
5078 // If the overall wait is forever, then we only need to set the one thread timeout:
5079 if (timeout_usec == 0)
5080 {
5081 if (option_one_thread_timeout != 0)
5082 one_thread_timeout_usec = option_one_thread_timeout;
5083 else
5084 one_thread_timeout_usec = default_one_thread_timeout_usec;
5085 }
5086 else
5087 {
5088 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5089 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5090 uint64_t computed_one_thread_timeout;
5091 if (option_one_thread_timeout != 0)
5092 {
5093 if (timeout_usec < option_one_thread_timeout)
5094 {
5095 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
5096 return eExpressionSetupError;
5097 }
5098 computed_one_thread_timeout = option_one_thread_timeout;
5099 }
5100 else
5101 {
5102 computed_one_thread_timeout = timeout_usec / 2;
5103 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5104 computed_one_thread_timeout = default_one_thread_timeout_usec;
5105 }
5106 one_thread_timeout_usec = computed_one_thread_timeout;
5107 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5108
5109 }
5110 }
5111
5112 if (log)
5113 log->Printf ("Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32"u" " - all threads: %" PRIu32"u" ".\n",
5114 options.GetStopOthers(),
5115 options.GetTryAllThreads(),
5116 before_first_timeout,
5117 one_thread_timeout_usec,
5118 all_threads_timeout_usec);
5119
5120 // This isn't going to work if there are unfetched events on the queue.
5121 // Are there cases where we might want to run the remaining events here, and then try to
5122 // call the function? That's probably being too tricky for our own good.
5123
5124 Event *other_events = listener.PeekAtNextEvent();
5125 if (other_events != NULL__null)
5126 {
5127 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
5128 return eExpressionSetupError;
5129 }
5130
5131 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5132 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5133 // event coalescing to cause us to lose OUR running event...
5134 ForceNextEventDelivery();
5135
5136 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5137 // So don't call return anywhere within it.
5138
5139#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5140 // It's pretty much impossible to write test cases for things like:
5141 // One thread timeout expires, I go to halt, but the process already stopped
5142 // on the function call stop breakpoint. Turning on this define will make us not
5143 // fetch the first event till after the halt. So if you run a quick function, it will have
5144 // completed, and the completion event will be waiting, when you interrupt for halt.
5145 // The expression evaluation should still succeed.
5146 bool miss_first_event = true;
5147#endif
5148 TimeValue one_thread_timeout;
5149 TimeValue final_timeout;
5150
5151
5152 while (1)
5153 {
5154 // We usually want to resume the process if we get to the top of the loop.
5155 // The only exception is if we get two running events with no intervening
5156 // stop, which can happen, we will just wait for then next stop event.
5157 if (log)
5158 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5159 do_resume,
5160 handle_running_event,
5161 before_first_timeout);
5162
5163 if (do_resume || handle_running_event)
5164 {
5165 // Do the initial resume and wait for the running event before going further.
5166
5167 if (do_resume)
5168 {
5169 num_resumes++;
5170 Error resume_error = PrivateResume ();
5171 if (!resume_error.Success())
5172 {
5173 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5174 num_resumes,
5175 resume_error.AsCString());
5176 return_value = eExpressionSetupError;
5177 break;
5178 }
5179 }
5180
5181 TimeValue resume_timeout = TimeValue::Now();
5182 resume_timeout.OffsetWithMicroSeconds(500000);
5183
5184 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
5185 if (!got_event)
5186 {
5187 if (log)
5188 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5189 num_resumes);
5190
5191 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
5192 return_value = eExpressionSetupError;
5193 break;
5194 }
5195
5196 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5197
5198 if (stop_state != eStateRunning)
5199 {
5200 bool restarted = false;
5201
5202 if (stop_state == eStateStopped)
5203 {
5204 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5205 if (log)
5206 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5207 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5208 num_resumes,
5209 StateAsCString(stop_state),
5210 restarted,
5211 do_resume,
5212 handle_running_event);
5213 }
5214
5215 if (restarted)
5216 {
5217 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5218 // event here. But if I do, the best thing is to Halt and then get out of here.
5219 Halt();
5220 }
5221
5222 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5223 StateAsCString(stop_state));
5224 return_value = eExpressionSetupError;
5225 break;
5226 }
5227
5228 if (log)
5229 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5230 // We need to call the function synchronously, so spin waiting for it to return.
5231 // If we get interrupted while executing, we're going to lose our context, and
5232 // won't be able to gather the result at this point.
5233 // We set the timeout AFTER the resume, since the resume takes some time and we
5234 // don't want to charge that to the timeout.
5235 }
5236 else
5237 {
5238 if (log)
5239 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
5240 }
5241
5242 if (before_first_timeout)
5243 {
5244 if (options.GetTryAllThreads())
5245 {
5246 one_thread_timeout = TimeValue::Now();
5247 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
5248 timeout_ptr = &one_thread_timeout;
5249 }
5250 else
5251 {
5252 if (timeout_usec == 0)
5253 timeout_ptr = NULL__null;
5254 else
5255 {
5256 final_timeout = TimeValue::Now();
5257 final_timeout.OffsetWithMicroSeconds (timeout_usec);
5258 timeout_ptr = &final_timeout;
5259 }
5260 }
5261 }
5262 else
5263 {
5264 if (timeout_usec == 0)
5265 timeout_ptr = NULL__null;
5266 else
5267 {
5268 final_timeout = TimeValue::Now();
5269 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
5270 timeout_ptr = &final_timeout;
5271 }
5272 }
5273
5274 do_resume = true;
5275 handle_running_event = true;
5276
5277 // Now wait for the process to stop again:
5278 event_sp.reset();
5279
5280 if (log)
5281 {
5282 if (timeout_ptr)
5283 {
5284 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64"l" "u" " - endpoint is %" PRIu64"l" "u",
5285 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5286 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
5287 }
5288 else
5289 {
5290 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5291 }
5292 }
5293
5294#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5295 // See comment above...
5296 if (miss_first_event)
5297 {
5298 usleep(1000);
5299 miss_first_event = false;
5300 got_event = false;
5301 }
5302 else
5303#endif
5304 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5305
5306 if (got_event)
5307 {
5308 if (event_sp.get())
5309 {
5310 bool keep_going = false;
5311 if (event_sp->GetType() == eBroadcastBitInterrupt)
5312 {
5313 Halt();
5314 return_value = eExpressionInterrupted;
5315 errors.Printf ("Execution halted by user interrupt.");
5316 if (log)
5317 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
5318 break;
5319 }
5320 else
5321 {
5322 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5323 if (log)
5324 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5325
5326 switch (stop_state)
5327 {
5328 case lldb::eStateStopped:
5329 {
5330 // We stopped, figure out what we are going to do now.
5331 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5332 if (!thread_sp)
5333 {
5334 // Ooh, our thread has vanished. Unlikely that this was successful execution...
5335 if (log)
5336 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5337 return_value = eExpressionInterrupted;
5338 }
5339 else
5340 {
5341 // If we were restarted, we just need to go back up to fetch another event.
5342 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5343 {
5344 if (log)
5345 {
5346 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5347 }
5348 keep_going = true;
5349 do_resume = false;
5350 handle_running_event = true;
5351
5352 }
5353 else
5354 {
5355 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5356 StopReason stop_reason = eStopReasonInvalid;
5357 if (stop_info_sp)
5358 stop_reason = stop_info_sp->GetStopReason();
5359
5360 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5361 // it is OUR plan that is complete?
5362 if (stop_reason == eStopReasonPlanComplete)
5363 {
5364 if (log)
5365 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5366 // Now mark this plan as private so it doesn't get reported as the stop reason
5367 // after this point.
5368 if (thread_plan_sp)
5369 thread_plan_sp->SetPrivate (orig_plan_private);
5370 return_value = eExpressionCompleted;
5371 }
5372 else
5373 {
5374 // Something restarted the target, so just wait for it to stop for real.
5375 if (stop_reason == eStopReasonBreakpoint)
5376 {
5377 if (log)
5378 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
5379 return_value = eExpressionHitBreakpoint;
5380 if (!options.DoesIgnoreBreakpoints())
5381 {
5382 event_to_broadcast_sp = event_sp;
5383 }
5384 }
5385 else
5386 {
5387 if (log)
5388 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
5389 if (!options.DoesUnwindOnError())
5390 event_to_broadcast_sp = event_sp;
5391 return_value = eExpressionInterrupted;
5392 }
5393 }
5394 }
5395 }
5396 }
5397 break;
5398
5399 case lldb::eStateRunning:
5400 // This shouldn't really happen, but sometimes we do get two running events without an
5401 // intervening stop, and in that case we should just go back to waiting for the stop.
5402 do_resume = false;
5403 keep_going = true;
5404 handle_running_event = false;
5405 break;
5406
5407 default:
5408 if (log)
5409 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5410
5411 if (stop_state == eStateExited)
5412 event_to_broadcast_sp = event_sp;
5413
5414 errors.Printf ("Execution stopped with unexpected state.\n");
5415 return_value = eExpressionInterrupted;
5416 break;
5417 }
5418 }
5419
5420 if (keep_going)
5421 continue;
5422 else
5423 break;
5424 }
5425 else
5426 {
5427 if (log)
5428 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5429 return_value = eExpressionInterrupted;
5430 break;
5431 }
5432 }
5433 else
5434 {
5435 // If we didn't get an event that means we've timed out...
5436 // We will interrupt the process here. Depending on what we were asked to do we will
5437 // either exit, or try with all threads running for the same timeout.
5438
5439 if (log) {
5440 if (options.GetTryAllThreads())
5441 {
5442 if (before_first_timeout)
5443 {
5444 if (timeout_usec != 0)
5445 {
5446 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5447 "running for %" PRIu32"u" " usec with all threads enabled.",
5448 all_threads_timeout_usec);
5449 }
5450 else
5451 {
5452 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5453 "running forever with all threads enabled.");
5454 }
5455 }
5456 else
5457 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
5458 "and timeout: %u timed out, abandoning execution.",
5459 timeout_usec);
5460 }
5461 else
5462 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
5463 "abandoning execution.",
5464 timeout_usec);
5465 }
5466
5467 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5468 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5469 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5470 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5471 // stopped event. That's what this while loop does.
5472
5473 bool back_to_top = true;
5474 uint32_t try_halt_again = 0;
5475 bool do_halt = true;
5476 const uint32_t num_retries = 5;
5477 while (try_halt_again < num_retries)
5478 {
5479 Error halt_error;
5480 if (do_halt)
5481 {
5482 if (log)
5483 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5484 halt_error = Halt();
5485 }
5486 if (halt_error.Success())
5487 {
5488 if (log)
5489 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5490
5491 real_timeout = TimeValue::Now();
5492 real_timeout.OffsetWithMicroSeconds(500000);
5493
5494 got_event = listener.WaitForEvent(&real_timeout, event_sp);
5495
5496 if (got_event)
5497 {
5498 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5499 if (log)
5500 {
5501 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5502 if (stop_state == lldb::eStateStopped
5503 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5504 log->PutCString (" Event was the Halt interruption event.");
5505 }
5506
5507 if (stop_state == lldb::eStateStopped)
5508 {
5509 // Between the time we initiated the Halt and the time we delivered it, the process could have
5510 // already finished its job. Check that here:
5511
5512 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5513 {
5514 if (log)
5515 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5516 "Exiting wait loop.");
5517 return_value = eExpressionCompleted;
5518 back_to_top = false;
5519 break;
5520 }
5521
5522 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5523 {
5524 if (log)
5525 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5526 "Exiting wait loop.");
5527 try_halt_again++;
5528 do_halt = false;
5529 continue;
5530 }
5531
5532 if (!options.GetTryAllThreads())
5533 {
5534 if (log)
5535 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5536 return_value = eExpressionInterrupted;
5537 back_to_top = false;
5538 break;
5539 }
5540
5541 if (before_first_timeout)
5542 {
5543 // Set all the other threads to run, and return to the top of the loop, which will continue;
5544 before_first_timeout = false;
5545 thread_plan_sp->SetStopOthers (false);
5546 if (log)
5547 log->PutCString ("Process::RunThreadPlan(): about to resume.");
5548
5549 back_to_top = true;
5550 break;
5551 }
5552 else
5553 {
5554 // Running all threads failed, so return Interrupted.
5555 if (log)
5556 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5557 return_value = eExpressionInterrupted;
5558 back_to_top = false;
5559 break;
5560 }
5561 }
5562 }
5563 else
5564 { if (log)
5565 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5566 "I'm getting out of here passing Interrupted.");
5567 return_value = eExpressionInterrupted;
5568 back_to_top = false;
5569 break;
5570 }
5571 }
5572 else
5573 {
5574 try_halt_again++;
5575 continue;
5576 }
5577 }
5578
5579 if (!back_to_top || try_halt_again > num_retries)
5580 break;
5581 else
5582 continue;
5583 }
5584 } // END WAIT LOOP
5585
5586 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5587 if (backup_private_state_thread.IsJoinable())
5588 {
5589 StopPrivateStateThread();
5590 Error error;
5591 m_private_state_thread = backup_private_state_thread;
5592 if (stopper_base_plan_sp)
5593 {
5594 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5595 }
5596 m_public_state.SetValueNoLock(old_state);
5597
5598 }
5599
5600 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5601 // could happen:
5602 // 1) The execution successfully completed
5603 // 2) We hit a breakpoint, and ignore_breakpoints was true
5604 // 3) We got some other error, and discard_on_error was true
5605 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5606 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
5607
5608 if (return_value == eExpressionCompleted
5609 || should_unwind)
5610 {
5611 thread_plan_sp->RestoreThreadState();
5612 }
5613
5614 // Now do some processing on the results of the run:
5615 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
5616 {
5617 if (log)
5618 {
5619 StreamString s;
5620 if (event_sp)
5621 event_sp->Dump (&s);
5622 else
5623 {
5624 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5625 }
5626
5627 StreamString ts;
5628
5629 const char *event_explanation = NULL__null;
5630
5631 do
5632 {
5633 if (!event_sp)
5634 {
5635 event_explanation = "<no event>";
5636 break;
5637 }
5638 else if (event_sp->GetType() == eBroadcastBitInterrupt)
5639 {
5640 event_explanation = "<user interrupt>";
5641 break;
5642 }
5643 else
5644 {
5645 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5646
5647 if (!event_data)
5648 {
5649 event_explanation = "<no event data>";
5650 break;
5651 }
5652
5653 Process *process = event_data->GetProcessSP().get();
5654
5655 if (!process)
5656 {
5657 event_explanation = "<no process>";
5658 break;
5659 }
5660
5661 ThreadList &thread_list = process->GetThreadList();
5662
5663 uint32_t num_threads = thread_list.GetSize();
5664 uint32_t thread_index;
5665
5666 ts.Printf("<%u threads> ", num_threads);
5667
5668 for (thread_index = 0;
5669 thread_index < num_threads;
5670 ++thread_index)
5671 {
5672 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5673
5674 if (!thread)
5675 {
5676 ts.Printf("<?> ");
5677 continue;
5678 }
5679
5680 ts.Printf("<0x%4.4" PRIx64"l" "x" " ", thread->GetID());
5681 RegisterContext *register_context = thread->GetRegisterContext().get();
5682
5683 if (register_context)
5684 ts.Printf("[ip 0x%" PRIx64"l" "x" "] ", register_context->GetPC());
5685 else
5686 ts.Printf("[ip unknown] ");
5687
5688 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5689 if (stop_info_sp)
5690 {
5691 const char *stop_desc = stop_info_sp->GetDescription();
5692 if (stop_desc)
5693 ts.PutCString (stop_desc);
5694 }
5695 ts.Printf(">");
5696 }
5697
5698 event_explanation = ts.GetData();
5699 }
5700 } while (0);
5701
5702 if (event_explanation)
5703 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
5704 else
5705 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5706 }
5707
5708 if (should_unwind)
5709 {
5710 if (log)
5711 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5712 static_cast<void*>(thread_plan_sp.get()));
5713 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5714 thread_plan_sp->SetPrivate (orig_plan_private);
5715 }
5716 else
5717 {
5718 if (log)
5719 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5720 static_cast<void*>(thread_plan_sp.get()));
5721 }
5722 }
5723 else if (return_value == eExpressionSetupError)
5724 {
5725 if (log)
5726 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5727
5728 if (options.DoesUnwindOnError())
5729 {
5730 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5731 thread_plan_sp->SetPrivate (orig_plan_private);
5732 }
5733 }
5734 else
5735 {
5736 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5737 {
5738 if (log)
5739 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5740 return_value = eExpressionCompleted;
5741 }
5742 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5743 {
5744 if (log)
5745 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5746 return_value = eExpressionDiscarded;
5747 }
5748 else
5749 {
5750 if (log)
5751 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
5752 if (options.DoesUnwindOnError() && thread_plan_sp)
5753 {
5754 if (log)
5755 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
5756 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5757 thread_plan_sp->SetPrivate (orig_plan_private);
5758 }
5759 }
5760 }
5761
5762 // Thread we ran the function in may have gone away because we ran the target
5763 // Check that it's still there, and if it is put it back in the context. Also restore the
5764 // frame in the context if it is still present.
5765 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5766 if (thread)
5767 {
5768 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5769 }
5770
5771 // Also restore the current process'es selected frame & thread, since this function calling may
5772 // be done behind the user's back.
5773
5774 if (selected_tid != LLDB_INVALID_THREAD_ID0)
5775 {
5776 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5777 {
5778 // We were able to restore the selected thread, now restore the frame:
5779 Mutex::Locker lock(GetThreadList().GetMutex());
5780 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5781 if (old_frame_sp)
5782 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
5783 }
5784 }
5785 }
5786
5787 // If the process exited during the run of the thread plan, notify everyone.
5788
5789 if (event_to_broadcast_sp)
5790 {
5791 if (log)
5792 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5793 BroadcastEvent(event_to_broadcast_sp);
5794 }
5795
5796 return return_value;
5797}
5798
5799const char *
5800Process::ExecutionResultAsCString (ExpressionResults result)
5801{
5802 const char *result_name;
5803
5804 switch (result)
5805 {
5806 case eExpressionCompleted:
5807 result_name = "eExpressionCompleted";
5808 break;
5809 case eExpressionDiscarded:
5810 result_name = "eExpressionDiscarded";
5811 break;
5812 case eExpressionInterrupted:
5813 result_name = "eExpressionInterrupted";
5814 break;
5815 case eExpressionHitBreakpoint:
5816 result_name = "eExpressionHitBreakpoint";
5817 break;
5818 case eExpressionSetupError:
5819 result_name = "eExpressionSetupError";
5820 break;
5821 case eExpressionParseError:
5822 result_name = "eExpressionParseError";
5823 break;
5824 case eExpressionResultUnavailable:
5825 result_name = "eExpressionResultUnavailable";
5826 break;
5827 case eExpressionTimedOut:
5828 result_name = "eExpressionTimedOut";
5829 break;
5830 case eExpressionStoppedForDebug:
5831 result_name = "eExpressionStoppedForDebug";
5832 break;
5833 }
5834 return result_name;
5835}
5836
5837void
5838Process::GetStatus (Stream &strm)
5839{
5840 const StateType state = GetState();
5841 if (StateIsStoppedState(state, false))
5842 {
5843 if (state == eStateExited)
5844 {
5845 int exit_status = GetExitStatus();
5846 const char *exit_description = GetExitDescription();
5847 strm.Printf ("Process %" PRIu64"l" "u" " exited with status = %i (0x%8.8x) %s\n",
5848 GetID(),
5849 exit_status,
5850 exit_status,
5851 exit_description ? exit_description : "");
5852 }
5853 else
5854 {
5855 if (state == eStateConnected)
5856 strm.Printf ("Connected to remote target.\n");
5857 else
5858 strm.Printf ("Process %" PRIu64"l" "u" " %s\n", GetID(), StateAsCString (state));
5859 }
5860 }
5861 else
5862 {
5863 strm.Printf ("Process %" PRIu64"l" "u" " is running.\n", GetID());
5864 }
5865}
5866
5867size_t
5868Process::GetThreadStatus (Stream &strm,
5869 bool only_threads_with_stop_reason,
5870 uint32_t start_frame,
5871 uint32_t num_frames,
5872 uint32_t num_frames_with_source)
5873{
5874 size_t num_thread_infos_dumped = 0;
5875
5876 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5877 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5878 // ID's, and look them up one by one:
5879
5880 uint32_t num_threads;
5881 std::vector<uint32_t> thread_index_array;
5882 //Scope for thread list locker;
5883 {
5884 Mutex::Locker locker (GetThreadList().GetMutex());
5885 ThreadList &curr_thread_list = GetThreadList();
5886 num_threads = curr_thread_list.GetSize();
5887 uint32_t idx;
5888 thread_index_array.resize(num_threads);
5889 for (idx = 0; idx < num_threads; ++idx)
5890 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5891 }
5892
5893 for (uint32_t i = 0; i < num_threads; i++)
5894 {
5895 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5896 if (thread_sp)
5897 {
5898 if (only_threads_with_stop_reason)
5899 {
5900 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5901 if (stop_info_sp.get() == NULL__null || !stop_info_sp->IsValid())
5902 continue;
5903 }
5904 thread_sp->GetStatus (strm,
5905 start_frame,
5906 num_frames,
5907 num_frames_with_source);
5908 ++num_thread_infos_dumped;
5909 }
5910 else
5911 {
5912 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
5913 if (log)
5914 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64"l" "u" " vanished while running Thread::GetStatus.");
5915
5916 }
5917 }
5918 return num_thread_infos_dumped;
5919}
5920
5921void
5922Process::AddInvalidMemoryRegion (const LoadRange &region)
5923{
5924 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5925}
5926
5927bool
5928Process::RemoveInvalidMemoryRange (const LoadRange &region)
5929{
5930 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5931}
5932
5933void
5934Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5935{
5936 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5937}
5938
5939bool
5940Process::RunPreResumeActions ()
5941{
5942 bool result = true;
5943 while (!m_pre_resume_actions.empty())
5944 {
5945 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5946 m_pre_resume_actions.pop_back();
5947 bool this_result = action.callback (action.baton);
5948 if (result == true) result = this_result;
5949 }
5950 return result;
5951}
5952
5953void
5954Process::ClearPreResumeActions ()
5955{
5956 m_pre_resume_actions.clear();
5957}
5958
5959void
5960Process::Flush ()
5961{
5962 m_thread_list.Flush();
5963 m_extended_thread_list.Flush();
5964 m_extended_thread_stop_id = 0;
5965 m_queue_list.Clear();
5966 m_queue_list_stop_id = 0;
5967}
5968
5969void
5970Process::DidExec ()
5971{
5972 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS(1u << 1)));
5973 if (log)
5974 log->Printf ("Process::%s()", __FUNCTION__);
5975
5976 Target &target = GetTarget();
5977 target.CleanupProcess ();
5978 target.ClearModules(false);
5979 m_dynamic_checkers_ap.reset();
5980 m_abi_sp.reset();
5981 m_system_runtime_ap.reset();
5982 m_os_ap.reset();
5983 m_dyld_ap.reset();
5984 m_jit_loaders_ap.reset();
5985 m_image_tokens.clear();
5986 m_allocated_memory_cache.Clear();
5987 m_language_runtimes.clear();
5988 m_instrumentation_runtimes.clear();
5989 m_thread_list.DiscardThreadPlans();
5990 m_memory_cache.Clear(true);
5991 DoDidExec();
5992 CompleteAttach ();
5993 // Flush the process (threads and all stack frames) after running CompleteAttach()
5994 // in case the dynamic loader loaded things in new locations.
5995 Flush();
5996
5997 // After we figure out what was loaded/unloaded in CompleteAttach,
5998 // we need to let the target know so it can do any cleanup it needs to.
5999 target.DidExec();
6000}
6001
6002addr_t
6003Process::ResolveIndirectFunction(const Address *address, Error &error)
6004{
6005 if (address == nullptr)
6006 {
6007 error.SetErrorString("Invalid address argument");
6008 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
6009 }
6010
6011 addr_t function_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
6012
6013 addr_t addr = address->GetLoadAddress(&GetTarget());
6014 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6015 if (iter != m_resolved_indirect_addresses.end())
6016 {
6017 function_addr = (*iter).second;
6018 }
6019 else
6020 {
6021 if (!InferiorCall(this, address, function_addr))
6022 {
6023 Symbol *symbol = address->CalculateSymbolContextSymbol();
6024 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6025 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6026 function_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
6027 }
6028 else
6029 {
6030 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6031 }
6032 }
6033 return function_addr;
6034}
6035
6036void
6037Process::ModulesDidLoad (ModuleList &module_list)
6038{
6039 SystemRuntime *sys_runtime = GetSystemRuntime();
6040 if (sys_runtime)
6041 {
6042 sys_runtime->ModulesDidLoad (module_list);
6043 }
6044
6045 GetJITLoaders().ModulesDidLoad (module_list);
6046
6047 // Give runtimes a chance to be created.
6048 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6049
6050 // Tell runtimes about new modules.
6051 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6052 {
6053 InstrumentationRuntimeSP runtime = pos->second;
6054 runtime->ModulesDidLoad(module_list);
6055 }
6056
6057}
6058
6059ThreadCollectionSP
6060Process::GetHistoryThreads(lldb::addr_t addr)
6061{
6062 ThreadCollectionSP threads;
6063
6064 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6065
6066 if (! memory_history.get()) {
6067 return threads;
6068 }
6069
6070 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6071
6072 return threads;
6073}
6074
6075InstrumentationRuntimeSP
6076Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6077{
6078 InstrumentationRuntimeCollection::iterator pos;
6079 pos = m_instrumentation_runtimes.find (type);
6080 if (pos == m_instrumentation_runtimes.end())
6081 {
6082 return InstrumentationRuntimeSP();
6083 }
6084 else
6085 return (*pos).second;
6086}