1254721Semaste//===-- Process.cpp ---------------------------------------------*- C++ -*-===// 2254721Semaste// 3254721Semaste// The LLVM Compiler Infrastructure 4254721Semaste// 5254721Semaste// This file is distributed under the University of Illinois Open Source 6254721Semaste// License. See LICENSE.TXT for details. 7254721Semaste// 8254721Semaste//===----------------------------------------------------------------------===// 9254721Semaste 10254721Semaste#include "lldb/lldb-python.h" 11254721Semaste 12254721Semaste#include "lldb/Target/Process.h" 13254721Semaste 14254721Semaste#include "lldb/lldb-private-log.h" 15254721Semaste 16254721Semaste#include "lldb/Breakpoint/StoppointCallbackContext.h" 17254721Semaste#include "lldb/Breakpoint/BreakpointLocation.h" 18254721Semaste#include "lldb/Core/Event.h" 19254721Semaste#include "lldb/Core/ConnectionFileDescriptor.h" 20254721Semaste#include "lldb/Core/Debugger.h" 21254721Semaste#include "lldb/Core/Log.h" 22254721Semaste#include "lldb/Core/Module.h" 23269024Semaste#include "lldb/Symbol/Symbol.h" 24254721Semaste#include "lldb/Core/PluginManager.h" 25254721Semaste#include "lldb/Core/State.h" 26269024Semaste#include "lldb/Core/StreamFile.h" 27254721Semaste#include "lldb/Expression/ClangUserExpression.h" 28254721Semaste#include "lldb/Interpreter/CommandInterpreter.h" 29254721Semaste#include "lldb/Host/Host.h" 30269024Semaste#include "lldb/Host/Terminal.h" 31254721Semaste#include "lldb/Target/ABI.h" 32254721Semaste#include "lldb/Target/DynamicLoader.h" 33254721Semaste#include "lldb/Target/OperatingSystem.h" 34254721Semaste#include "lldb/Target/LanguageRuntime.h" 35254721Semaste#include "lldb/Target/CPPLanguageRuntime.h" 36254721Semaste#include "lldb/Target/ObjCLanguageRuntime.h" 37254721Semaste#include "lldb/Target/Platform.h" 38254721Semaste#include "lldb/Target/RegisterContext.h" 39254721Semaste#include "lldb/Target/StopInfo.h" 40263363Semaste#include "lldb/Target/SystemRuntime.h" 41254721Semaste#include "lldb/Target/Target.h" 42254721Semaste#include "lldb/Target/TargetList.h" 43254721Semaste#include "lldb/Target/Thread.h" 44254721Semaste#include "lldb/Target/ThreadPlan.h" 45254721Semaste#include "lldb/Target/ThreadPlanBase.h" 46269024Semaste#include "Plugins/Process/Utility/InferiorCallPOSIX.h" 47254721Semaste 48263363Semaste#ifndef LLDB_DISABLE_POSIX 49263363Semaste#include <spawn.h> 50263363Semaste#endif 51263363Semaste 52254721Semasteusing namespace lldb; 53254721Semasteusing namespace lldb_private; 54254721Semaste 55254721Semaste 56254721Semaste// Comment out line below to disable memory caching, overriding the process setting 57254721Semaste// target.process.disable-memory-cache 58254721Semaste#define ENABLE_MEMORY_CACHING 59254721Semaste 60254721Semaste#ifdef ENABLE_MEMORY_CACHING 61254721Semaste#define DISABLE_MEM_CACHE_DEFAULT false 62254721Semaste#else 63254721Semaste#define DISABLE_MEM_CACHE_DEFAULT true 64254721Semaste#endif 65254721Semaste 66254721Semasteclass ProcessOptionValueProperties : public OptionValueProperties 67254721Semaste{ 68254721Semastepublic: 69254721Semaste ProcessOptionValueProperties (const ConstString &name) : 70254721Semaste OptionValueProperties (name) 71254721Semaste { 72254721Semaste } 73254721Semaste 74254721Semaste // This constructor is used when creating ProcessOptionValueProperties when it 75254721Semaste // is part of a new lldb_private::Process instance. It will copy all current 76254721Semaste // global property values as needed 77254721Semaste ProcessOptionValueProperties (ProcessProperties *global_properties) : 78254721Semaste OptionValueProperties(*global_properties->GetValueProperties()) 79254721Semaste { 80254721Semaste } 81254721Semaste 82254721Semaste virtual const Property * 83254721Semaste GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const 84254721Semaste { 85254721Semaste // When gettings the value for a key from the process options, we will always 86254721Semaste // try and grab the setting from the current process if there is one. Else we just 87254721Semaste // use the one from this instance. 88254721Semaste if (exe_ctx) 89254721Semaste { 90254721Semaste Process *process = exe_ctx->GetProcessPtr(); 91254721Semaste if (process) 92254721Semaste { 93254721Semaste ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get()); 94254721Semaste if (this != instance_properties) 95254721Semaste return instance_properties->ProtectedGetPropertyAtIndex (idx); 96254721Semaste } 97254721Semaste } 98254721Semaste return ProtectedGetPropertyAtIndex (idx); 99254721Semaste } 100254721Semaste}; 101254721Semaste 102254721Semastestatic PropertyDefinition 103254721Semasteg_properties[] = 104254721Semaste{ 105254721Semaste { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." }, 106254721Semaste { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. " 107254721Semaste "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" }, 108254721Semaste { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." }, 109254721Semaste { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." }, 110254721Semaste { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." }, 111254721Semaste { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." }, 112254721Semaste { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." }, 113254721Semaste { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL } 114254721Semaste}; 115254721Semaste 116254721Semasteenum { 117254721Semaste ePropertyDisableMemCache, 118254721Semaste ePropertyExtraStartCommand, 119254721Semaste ePropertyIgnoreBreakpointsInExpressions, 120254721Semaste ePropertyUnwindOnErrorInExpressions, 121254721Semaste ePropertyPythonOSPluginPath, 122254721Semaste ePropertyStopOnSharedLibraryEvents, 123254721Semaste ePropertyDetachKeepsStopped 124254721Semaste}; 125254721Semaste 126254721SemasteProcessProperties::ProcessProperties (bool is_global) : 127254721Semaste Properties () 128254721Semaste{ 129254721Semaste if (is_global) 130254721Semaste { 131254721Semaste m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process"))); 132254721Semaste m_collection_sp->Initialize(g_properties); 133254721Semaste m_collection_sp->AppendProperty(ConstString("thread"), 134254721Semaste ConstString("Settings specific to threads."), 135254721Semaste true, 136254721Semaste Thread::GetGlobalProperties()->GetValueProperties()); 137254721Semaste } 138254721Semaste else 139254721Semaste m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get())); 140254721Semaste} 141254721Semaste 142254721SemasteProcessProperties::~ProcessProperties() 143254721Semaste{ 144254721Semaste} 145254721Semaste 146254721Semastebool 147254721SemasteProcessProperties::GetDisableMemoryCache() const 148254721Semaste{ 149254721Semaste const uint32_t idx = ePropertyDisableMemCache; 150254721Semaste return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 151254721Semaste} 152254721Semaste 153254721SemasteArgs 154254721SemasteProcessProperties::GetExtraStartupCommands () const 155254721Semaste{ 156254721Semaste Args args; 157254721Semaste const uint32_t idx = ePropertyExtraStartCommand; 158254721Semaste m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args); 159254721Semaste return args; 160254721Semaste} 161254721Semaste 162254721Semastevoid 163254721SemasteProcessProperties::SetExtraStartupCommands (const Args &args) 164254721Semaste{ 165254721Semaste const uint32_t idx = ePropertyExtraStartCommand; 166254721Semaste m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args); 167254721Semaste} 168254721Semaste 169254721SemasteFileSpec 170254721SemasteProcessProperties::GetPythonOSPluginPath () const 171254721Semaste{ 172254721Semaste const uint32_t idx = ePropertyPythonOSPluginPath; 173254721Semaste return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx); 174254721Semaste} 175254721Semaste 176254721Semastevoid 177254721SemasteProcessProperties::SetPythonOSPluginPath (const FileSpec &file) 178254721Semaste{ 179254721Semaste const uint32_t idx = ePropertyPythonOSPluginPath; 180254721Semaste m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file); 181254721Semaste} 182254721Semaste 183254721Semaste 184254721Semastebool 185254721SemasteProcessProperties::GetIgnoreBreakpointsInExpressions () const 186254721Semaste{ 187254721Semaste const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; 188254721Semaste return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 189254721Semaste} 190254721Semaste 191254721Semastevoid 192254721SemasteProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore) 193254721Semaste{ 194254721Semaste const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; 195254721Semaste m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore); 196254721Semaste} 197254721Semaste 198254721Semastebool 199254721SemasteProcessProperties::GetUnwindOnErrorInExpressions () const 200254721Semaste{ 201254721Semaste const uint32_t idx = ePropertyUnwindOnErrorInExpressions; 202254721Semaste return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 203254721Semaste} 204254721Semaste 205254721Semastevoid 206254721SemasteProcessProperties::SetUnwindOnErrorInExpressions (bool ignore) 207254721Semaste{ 208254721Semaste const uint32_t idx = ePropertyUnwindOnErrorInExpressions; 209254721Semaste m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore); 210254721Semaste} 211254721Semaste 212254721Semastebool 213254721SemasteProcessProperties::GetStopOnSharedLibraryEvents () const 214254721Semaste{ 215254721Semaste const uint32_t idx = ePropertyStopOnSharedLibraryEvents; 216254721Semaste return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 217254721Semaste} 218254721Semaste 219254721Semastevoid 220254721SemasteProcessProperties::SetStopOnSharedLibraryEvents (bool stop) 221254721Semaste{ 222254721Semaste const uint32_t idx = ePropertyStopOnSharedLibraryEvents; 223254721Semaste m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop); 224254721Semaste} 225254721Semaste 226254721Semastebool 227254721SemasteProcessProperties::GetDetachKeepsStopped () const 228254721Semaste{ 229254721Semaste const uint32_t idx = ePropertyDetachKeepsStopped; 230254721Semaste return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 231254721Semaste} 232254721Semaste 233254721Semastevoid 234254721SemasteProcessProperties::SetDetachKeepsStopped (bool stop) 235254721Semaste{ 236254721Semaste const uint32_t idx = ePropertyDetachKeepsStopped; 237254721Semaste m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop); 238254721Semaste} 239254721Semaste 240254721Semastevoid 241254721SemasteProcessInstanceInfo::Dump (Stream &s, Platform *platform) const 242254721Semaste{ 243254721Semaste const char *cstr; 244254721Semaste if (m_pid != LLDB_INVALID_PROCESS_ID) 245254721Semaste s.Printf (" pid = %" PRIu64 "\n", m_pid); 246254721Semaste 247254721Semaste if (m_parent_pid != LLDB_INVALID_PROCESS_ID) 248254721Semaste s.Printf (" parent = %" PRIu64 "\n", m_parent_pid); 249254721Semaste 250254721Semaste if (m_executable) 251254721Semaste { 252254721Semaste s.Printf (" name = %s\n", m_executable.GetFilename().GetCString()); 253254721Semaste s.PutCString (" file = "); 254254721Semaste m_executable.Dump(&s); 255254721Semaste s.EOL(); 256254721Semaste } 257254721Semaste const uint32_t argc = m_arguments.GetArgumentCount(); 258254721Semaste if (argc > 0) 259254721Semaste { 260254721Semaste for (uint32_t i=0; i<argc; i++) 261254721Semaste { 262254721Semaste const char *arg = m_arguments.GetArgumentAtIndex(i); 263254721Semaste if (i < 10) 264254721Semaste s.Printf (" arg[%u] = %s\n", i, arg); 265254721Semaste else 266254721Semaste s.Printf ("arg[%u] = %s\n", i, arg); 267254721Semaste } 268254721Semaste } 269254721Semaste 270254721Semaste const uint32_t envc = m_environment.GetArgumentCount(); 271254721Semaste if (envc > 0) 272254721Semaste { 273254721Semaste for (uint32_t i=0; i<envc; i++) 274254721Semaste { 275254721Semaste const char *env = m_environment.GetArgumentAtIndex(i); 276254721Semaste if (i < 10) 277254721Semaste s.Printf (" env[%u] = %s\n", i, env); 278254721Semaste else 279254721Semaste s.Printf ("env[%u] = %s\n", i, env); 280254721Semaste } 281254721Semaste } 282254721Semaste 283254721Semaste if (m_arch.IsValid()) 284254721Semaste s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str()); 285254721Semaste 286254721Semaste if (m_uid != UINT32_MAX) 287254721Semaste { 288254721Semaste cstr = platform->GetUserName (m_uid); 289254721Semaste s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : ""); 290254721Semaste } 291254721Semaste if (m_gid != UINT32_MAX) 292254721Semaste { 293254721Semaste cstr = platform->GetGroupName (m_gid); 294254721Semaste s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : ""); 295254721Semaste } 296254721Semaste if (m_euid != UINT32_MAX) 297254721Semaste { 298254721Semaste cstr = platform->GetUserName (m_euid); 299254721Semaste s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : ""); 300254721Semaste } 301254721Semaste if (m_egid != UINT32_MAX) 302254721Semaste { 303254721Semaste cstr = platform->GetGroupName (m_egid); 304254721Semaste s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : ""); 305254721Semaste } 306254721Semaste} 307254721Semaste 308254721Semastevoid 309254721SemasteProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose) 310254721Semaste{ 311254721Semaste const char *label; 312254721Semaste if (show_args || verbose) 313254721Semaste label = "ARGUMENTS"; 314254721Semaste else 315254721Semaste label = "NAME"; 316254721Semaste 317254721Semaste if (verbose) 318254721Semaste { 319254721Semaste s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label); 320254721Semaste s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n"); 321254721Semaste } 322254721Semaste else 323254721Semaste { 324254721Semaste s.Printf ("PID PARENT USER ARCH %s\n", label); 325254721Semaste s.PutCString ("====== ====== ========== ======= ============================\n"); 326254721Semaste } 327254721Semaste} 328254721Semaste 329254721Semastevoid 330254721SemasteProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const 331254721Semaste{ 332254721Semaste if (m_pid != LLDB_INVALID_PROCESS_ID) 333254721Semaste { 334254721Semaste const char *cstr; 335254721Semaste s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid); 336254721Semaste 337254721Semaste 338254721Semaste if (verbose) 339254721Semaste { 340254721Semaste cstr = platform->GetUserName (m_uid); 341254721Semaste if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 342254721Semaste s.Printf ("%-10s ", cstr); 343254721Semaste else 344254721Semaste s.Printf ("%-10u ", m_uid); 345254721Semaste 346254721Semaste cstr = platform->GetGroupName (m_gid); 347254721Semaste if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 348254721Semaste s.Printf ("%-10s ", cstr); 349254721Semaste else 350254721Semaste s.Printf ("%-10u ", m_gid); 351254721Semaste 352254721Semaste cstr = platform->GetUserName (m_euid); 353254721Semaste if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 354254721Semaste s.Printf ("%-10s ", cstr); 355254721Semaste else 356254721Semaste s.Printf ("%-10u ", m_euid); 357254721Semaste 358254721Semaste cstr = platform->GetGroupName (m_egid); 359254721Semaste if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 360254721Semaste s.Printf ("%-10s ", cstr); 361254721Semaste else 362254721Semaste s.Printf ("%-10u ", m_egid); 363254721Semaste s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : ""); 364254721Semaste } 365254721Semaste else 366254721Semaste { 367254721Semaste s.Printf ("%-10s %-7d %s ", 368254721Semaste platform->GetUserName (m_euid), 369254721Semaste (int)m_arch.GetTriple().getArchName().size(), 370254721Semaste m_arch.GetTriple().getArchName().data()); 371254721Semaste } 372254721Semaste 373254721Semaste if (verbose || show_args) 374254721Semaste { 375254721Semaste const uint32_t argc = m_arguments.GetArgumentCount(); 376254721Semaste if (argc > 0) 377254721Semaste { 378254721Semaste for (uint32_t i=0; i<argc; i++) 379254721Semaste { 380254721Semaste if (i > 0) 381254721Semaste s.PutChar (' '); 382254721Semaste s.PutCString (m_arguments.GetArgumentAtIndex(i)); 383254721Semaste } 384254721Semaste } 385254721Semaste } 386254721Semaste else 387254721Semaste { 388254721Semaste s.PutCString (GetName()); 389254721Semaste } 390254721Semaste 391254721Semaste s.EOL(); 392254721Semaste } 393254721Semaste} 394254721Semaste 395254721Semaste 396254721Semastevoid 397254721SemasteProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable) 398254721Semaste{ 399254721Semaste m_arguments.SetArguments (argv); 400254721Semaste 401254721Semaste // Is the first argument the executable? 402254721Semaste if (first_arg_is_executable) 403254721Semaste { 404254721Semaste const char *first_arg = m_arguments.GetArgumentAtIndex (0); 405254721Semaste if (first_arg) 406254721Semaste { 407254721Semaste // Yes the first argument is an executable, set it as the executable 408254721Semaste // in the launch options. Don't resolve the file path as the path 409254721Semaste // could be a remote platform path 410254721Semaste const bool resolve = false; 411254721Semaste m_executable.SetFile(first_arg, resolve); 412254721Semaste } 413254721Semaste } 414254721Semaste} 415254721Semastevoid 416254721SemasteProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable) 417254721Semaste{ 418254721Semaste // Copy all arguments 419254721Semaste m_arguments = args; 420254721Semaste 421254721Semaste // Is the first argument the executable? 422254721Semaste if (first_arg_is_executable) 423254721Semaste { 424254721Semaste const char *first_arg = m_arguments.GetArgumentAtIndex (0); 425254721Semaste if (first_arg) 426254721Semaste { 427254721Semaste // Yes the first argument is an executable, set it as the executable 428254721Semaste // in the launch options. Don't resolve the file path as the path 429254721Semaste // could be a remote platform path 430254721Semaste const bool resolve = false; 431254721Semaste m_executable.SetFile(first_arg, resolve); 432254721Semaste } 433254721Semaste } 434254721Semaste} 435254721Semaste 436254721Semastevoid 437254721SemasteProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty) 438254721Semaste{ 439254721Semaste // If notthing was specified, then check the process for any default 440254721Semaste // settings that were set with "settings set" 441254721Semaste if (m_file_actions.empty()) 442254721Semaste { 443254721Semaste if (m_flags.Test(eLaunchFlagDisableSTDIO)) 444254721Semaste { 445254721Semaste AppendSuppressFileAction (STDIN_FILENO , true, false); 446254721Semaste AppendSuppressFileAction (STDOUT_FILENO, false, true); 447254721Semaste AppendSuppressFileAction (STDERR_FILENO, false, true); 448254721Semaste } 449254721Semaste else 450254721Semaste { 451254721Semaste // Check for any values that might have gotten set with any of: 452254721Semaste // (lldb) settings set target.input-path 453254721Semaste // (lldb) settings set target.output-path 454254721Semaste // (lldb) settings set target.error-path 455254721Semaste FileSpec in_path; 456254721Semaste FileSpec out_path; 457254721Semaste FileSpec err_path; 458254721Semaste if (target) 459254721Semaste { 460254721Semaste in_path = target->GetStandardInputPath(); 461254721Semaste out_path = target->GetStandardOutputPath(); 462254721Semaste err_path = target->GetStandardErrorPath(); 463254721Semaste } 464254721Semaste 465254721Semaste if (in_path || out_path || err_path) 466254721Semaste { 467254721Semaste char path[PATH_MAX]; 468254721Semaste if (in_path && in_path.GetPath(path, sizeof(path))) 469254721Semaste AppendOpenFileAction(STDIN_FILENO, path, true, false); 470254721Semaste 471254721Semaste if (out_path && out_path.GetPath(path, sizeof(path))) 472254721Semaste AppendOpenFileAction(STDOUT_FILENO, path, false, true); 473254721Semaste 474254721Semaste if (err_path && err_path.GetPath(path, sizeof(path))) 475254721Semaste AppendOpenFileAction(STDERR_FILENO, path, false, true); 476254721Semaste } 477254721Semaste else if (default_to_use_pty) 478254721Semaste { 479254721Semaste if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0)) 480254721Semaste { 481254721Semaste const char *slave_path = m_pty.GetSlaveName (NULL, 0); 482254721Semaste AppendOpenFileAction(STDIN_FILENO, slave_path, true, false); 483254721Semaste AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true); 484254721Semaste AppendOpenFileAction(STDERR_FILENO, slave_path, false, true); 485254721Semaste } 486254721Semaste } 487254721Semaste } 488254721Semaste } 489254721Semaste} 490254721Semaste 491254721Semaste 492254721Semastebool 493254721SemasteProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, 494254721Semaste bool localhost, 495254721Semaste bool will_debug, 496263363Semaste bool first_arg_is_full_shell_command, 497263363Semaste int32_t num_resumes) 498254721Semaste{ 499254721Semaste error.Clear(); 500254721Semaste 501254721Semaste if (GetFlags().Test (eLaunchFlagLaunchInShell)) 502254721Semaste { 503254721Semaste const char *shell_executable = GetShell(); 504254721Semaste if (shell_executable) 505254721Semaste { 506254721Semaste char shell_resolved_path[PATH_MAX]; 507254721Semaste 508254721Semaste if (localhost) 509254721Semaste { 510254721Semaste FileSpec shell_filespec (shell_executable, true); 511254721Semaste 512254721Semaste if (!shell_filespec.Exists()) 513254721Semaste { 514254721Semaste // Resolve the path in case we just got "bash", "sh" or "tcsh" 515254721Semaste if (!shell_filespec.ResolveExecutableLocation ()) 516254721Semaste { 517254721Semaste error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable); 518254721Semaste return false; 519254721Semaste } 520254721Semaste } 521254721Semaste shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path)); 522254721Semaste shell_executable = shell_resolved_path; 523254721Semaste } 524254721Semaste 525254721Semaste const char **argv = GetArguments().GetConstArgumentVector (); 526254721Semaste if (argv == NULL || argv[0] == NULL) 527254721Semaste return false; 528254721Semaste Args shell_arguments; 529254721Semaste std::string safe_arg; 530254721Semaste shell_arguments.AppendArgument (shell_executable); 531254721Semaste shell_arguments.AppendArgument ("-c"); 532254721Semaste StreamString shell_command; 533254721Semaste if (will_debug) 534254721Semaste { 535254721Semaste // Add a modified PATH environment variable in case argv[0] 536254721Semaste // is a relative path 537254721Semaste const char *argv0 = argv[0]; 538254721Semaste if (argv0 && (argv0[0] != '/' && argv0[0] != '~')) 539254721Semaste { 540254721Semaste // We have a relative path to our executable which may not work if 541254721Semaste // we just try to run "a.out" (without it being converted to "./a.out") 542254721Semaste const char *working_dir = GetWorkingDirectory(); 543254721Semaste // Be sure to put quotes around PATH's value in case any paths have spaces... 544254721Semaste std::string new_path("PATH=\""); 545254721Semaste const size_t empty_path_len = new_path.size(); 546254721Semaste 547254721Semaste if (working_dir && working_dir[0]) 548254721Semaste { 549254721Semaste new_path += working_dir; 550254721Semaste } 551254721Semaste else 552254721Semaste { 553254721Semaste char current_working_dir[PATH_MAX]; 554254721Semaste const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir)); 555254721Semaste if (cwd && cwd[0]) 556254721Semaste new_path += cwd; 557254721Semaste } 558254721Semaste const char *curr_path = getenv("PATH"); 559254721Semaste if (curr_path) 560254721Semaste { 561254721Semaste if (new_path.size() > empty_path_len) 562254721Semaste new_path += ':'; 563254721Semaste new_path += curr_path; 564254721Semaste } 565254721Semaste new_path += "\" "; 566254721Semaste shell_command.PutCString(new_path.c_str()); 567254721Semaste } 568254721Semaste 569254721Semaste shell_command.PutCString ("exec"); 570254721Semaste 571254721Semaste // Only Apple supports /usr/bin/arch being able to specify the architecture 572254721Semaste if (GetArchitecture().IsValid()) 573254721Semaste { 574254721Semaste shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName()); 575254721Semaste // Set the resume count to 2: 576254721Semaste // 1 - stop in shell 577254721Semaste // 2 - stop in /usr/bin/arch 578254721Semaste // 3 - then we will stop in our program 579263363Semaste SetResumeCount(num_resumes + 1); 580254721Semaste } 581254721Semaste else 582254721Semaste { 583254721Semaste // Set the resume count to 1: 584254721Semaste // 1 - stop in shell 585254721Semaste // 2 - then we will stop in our program 586263363Semaste SetResumeCount(num_resumes); 587254721Semaste } 588254721Semaste } 589254721Semaste 590254721Semaste if (first_arg_is_full_shell_command) 591254721Semaste { 592254721Semaste // There should only be one argument that is the shell command itself to be used as is 593254721Semaste if (argv[0] && !argv[1]) 594254721Semaste shell_command.Printf("%s", argv[0]); 595254721Semaste else 596254721Semaste return false; 597254721Semaste } 598254721Semaste else 599254721Semaste { 600254721Semaste for (size_t i=0; argv[i] != NULL; ++i) 601254721Semaste { 602254721Semaste const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg); 603254721Semaste shell_command.Printf(" %s", arg); 604254721Semaste } 605254721Semaste } 606254721Semaste shell_arguments.AppendArgument (shell_command.GetString().c_str()); 607254721Semaste m_executable.SetFile(shell_executable, false); 608254721Semaste m_arguments = shell_arguments; 609254721Semaste return true; 610254721Semaste } 611254721Semaste else 612254721Semaste { 613254721Semaste error.SetErrorString ("invalid shell path"); 614254721Semaste } 615254721Semaste } 616254721Semaste else 617254721Semaste { 618254721Semaste error.SetErrorString ("not launching in shell"); 619254721Semaste } 620254721Semaste return false; 621254721Semaste} 622254721Semaste 623254721Semaste 624254721Semastebool 625254721SemasteProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write) 626254721Semaste{ 627254721Semaste if ((read || write) && fd >= 0 && path && path[0]) 628254721Semaste { 629254721Semaste m_action = eFileActionOpen; 630254721Semaste m_fd = fd; 631254721Semaste if (read && write) 632254721Semaste m_arg = O_NOCTTY | O_CREAT | O_RDWR; 633254721Semaste else if (read) 634254721Semaste m_arg = O_NOCTTY | O_RDONLY; 635254721Semaste else 636254721Semaste m_arg = O_NOCTTY | O_CREAT | O_WRONLY; 637254721Semaste m_path.assign (path); 638254721Semaste return true; 639254721Semaste } 640254721Semaste else 641254721Semaste { 642254721Semaste Clear(); 643254721Semaste } 644254721Semaste return false; 645254721Semaste} 646254721Semaste 647254721Semastebool 648254721SemasteProcessLaunchInfo::FileAction::Close (int fd) 649254721Semaste{ 650254721Semaste Clear(); 651254721Semaste if (fd >= 0) 652254721Semaste { 653254721Semaste m_action = eFileActionClose; 654254721Semaste m_fd = fd; 655254721Semaste } 656254721Semaste return m_fd >= 0; 657254721Semaste} 658254721Semaste 659254721Semaste 660254721Semastebool 661254721SemasteProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd) 662254721Semaste{ 663254721Semaste Clear(); 664254721Semaste if (fd >= 0 && dup_fd >= 0) 665254721Semaste { 666254721Semaste m_action = eFileActionDuplicate; 667254721Semaste m_fd = fd; 668254721Semaste m_arg = dup_fd; 669254721Semaste } 670254721Semaste return m_fd >= 0; 671254721Semaste} 672254721Semaste 673254721Semaste 674254721Semaste 675263363Semaste#ifndef LLDB_DISABLE_POSIX 676254721Semastebool 677263363SemasteProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions, 678254721Semaste const FileAction *info, 679254721Semaste Log *log, 680254721Semaste Error& error) 681254721Semaste{ 682254721Semaste if (info == NULL) 683254721Semaste return false; 684254721Semaste 685263363Semaste posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions); 686263363Semaste 687254721Semaste switch (info->m_action) 688254721Semaste { 689254721Semaste case eFileActionNone: 690254721Semaste error.Clear(); 691254721Semaste break; 692254721Semaste 693254721Semaste case eFileActionClose: 694254721Semaste if (info->m_fd == -1) 695254721Semaste error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)"); 696254721Semaste else 697254721Semaste { 698254721Semaste error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd), 699254721Semaste eErrorTypePOSIX); 700254721Semaste if (log && (error.Fail() || log)) 701254721Semaste error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)", 702254721Semaste file_actions, info->m_fd); 703254721Semaste } 704254721Semaste break; 705254721Semaste 706254721Semaste case eFileActionDuplicate: 707254721Semaste if (info->m_fd == -1) 708254721Semaste error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)"); 709254721Semaste else if (info->m_arg == -1) 710254721Semaste error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)"); 711254721Semaste else 712254721Semaste { 713254721Semaste error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg), 714254721Semaste eErrorTypePOSIX); 715254721Semaste if (log && (error.Fail() || log)) 716254721Semaste error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)", 717254721Semaste file_actions, info->m_fd, info->m_arg); 718254721Semaste } 719254721Semaste break; 720254721Semaste 721254721Semaste case eFileActionOpen: 722254721Semaste if (info->m_fd == -1) 723254721Semaste error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)"); 724254721Semaste else 725254721Semaste { 726254721Semaste int oflag = info->m_arg; 727254721Semaste 728254721Semaste mode_t mode = 0; 729254721Semaste 730254721Semaste if (oflag & O_CREAT) 731254721Semaste mode = 0640; 732254721Semaste 733254721Semaste error.SetError (::posix_spawn_file_actions_addopen (file_actions, 734254721Semaste info->m_fd, 735254721Semaste info->m_path.c_str(), 736254721Semaste oflag, 737254721Semaste mode), 738254721Semaste eErrorTypePOSIX); 739254721Semaste if (error.Fail() || log) 740254721Semaste error.PutToLog(log, 741254721Semaste "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)", 742254721Semaste file_actions, info->m_fd, info->m_path.c_str(), oflag, mode); 743254721Semaste } 744254721Semaste break; 745254721Semaste } 746254721Semaste return error.Success(); 747254721Semaste} 748263363Semaste#endif 749254721Semaste 750254721SemasteError 751254721SemasteProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg) 752254721Semaste{ 753254721Semaste Error error; 754254721Semaste const int short_option = m_getopt_table[option_idx].val; 755254721Semaste 756254721Semaste switch (short_option) 757254721Semaste { 758254721Semaste case 's': // Stop at program entry point 759254721Semaste launch_info.GetFlags().Set (eLaunchFlagStopAtEntry); 760254721Semaste break; 761254721Semaste 762254721Semaste case 'i': // STDIN for read only 763254721Semaste { 764254721Semaste ProcessLaunchInfo::FileAction action; 765254721Semaste if (action.Open (STDIN_FILENO, option_arg, true, false)) 766254721Semaste launch_info.AppendFileAction (action); 767254721Semaste } 768254721Semaste break; 769254721Semaste 770254721Semaste case 'o': // Open STDOUT for write only 771254721Semaste { 772254721Semaste ProcessLaunchInfo::FileAction action; 773254721Semaste if (action.Open (STDOUT_FILENO, option_arg, false, true)) 774254721Semaste launch_info.AppendFileAction (action); 775254721Semaste } 776254721Semaste break; 777254721Semaste 778254721Semaste case 'e': // STDERR for write only 779254721Semaste { 780254721Semaste ProcessLaunchInfo::FileAction action; 781254721Semaste if (action.Open (STDERR_FILENO, option_arg, false, true)) 782254721Semaste launch_info.AppendFileAction (action); 783254721Semaste } 784254721Semaste break; 785254721Semaste 786254721Semaste 787254721Semaste case 'p': // Process plug-in name 788254721Semaste launch_info.SetProcessPluginName (option_arg); 789254721Semaste break; 790254721Semaste 791254721Semaste case 'n': // Disable STDIO 792254721Semaste { 793254721Semaste ProcessLaunchInfo::FileAction action; 794254721Semaste if (action.Open (STDIN_FILENO, "/dev/null", true, false)) 795254721Semaste launch_info.AppendFileAction (action); 796254721Semaste if (action.Open (STDOUT_FILENO, "/dev/null", false, true)) 797254721Semaste launch_info.AppendFileAction (action); 798254721Semaste if (action.Open (STDERR_FILENO, "/dev/null", false, true)) 799254721Semaste launch_info.AppendFileAction (action); 800254721Semaste } 801254721Semaste break; 802254721Semaste 803254721Semaste case 'w': 804254721Semaste launch_info.SetWorkingDirectory (option_arg); 805254721Semaste break; 806254721Semaste 807254721Semaste case 't': // Open process in new terminal window 808254721Semaste launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY); 809254721Semaste break; 810254721Semaste 811254721Semaste case 'a': 812254721Semaste if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get())) 813254721Semaste launch_info.GetArchitecture().SetTriple (option_arg); 814254721Semaste break; 815254721Semaste 816254721Semaste case 'A': 817254721Semaste launch_info.GetFlags().Set (eLaunchFlagDisableASLR); 818254721Semaste break; 819254721Semaste 820254721Semaste case 'c': 821254721Semaste if (option_arg && option_arg[0]) 822254721Semaste launch_info.SetShell (option_arg); 823254721Semaste else 824263363Semaste launch_info.SetShell (LLDB_DEFAULT_SHELL); 825254721Semaste break; 826254721Semaste 827254721Semaste case 'v': 828254721Semaste launch_info.GetEnvironmentEntries().AppendArgument(option_arg); 829254721Semaste break; 830254721Semaste 831254721Semaste default: 832254721Semaste error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option); 833254721Semaste break; 834254721Semaste 835254721Semaste } 836254721Semaste return error; 837254721Semaste} 838254721Semaste 839254721SemasteOptionDefinition 840254721SemasteProcessLaunchCommandOptions::g_option_table[] = 841254721Semaste{ 842263363Semaste{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, 843263363Semaste{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."}, 844263363Semaste{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 845263363Semaste{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."}, 846263363Semaste{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."}, 847263363Semaste{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."}, 848263363Semaste{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."}, 849254721Semaste 850263363Semaste{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."}, 851263363Semaste{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."}, 852263363Semaste{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."}, 853254721Semaste 854263363Semaste{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."}, 855254721Semaste 856263363Semaste{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."}, 857254721Semaste 858254721Semaste{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } 859254721Semaste}; 860254721Semaste 861254721Semaste 862254721Semaste 863254721Semastebool 864254721SemasteProcessInstanceInfoMatch::NameMatches (const char *process_name) const 865254721Semaste{ 866254721Semaste if (m_name_match_type == eNameMatchIgnore || process_name == NULL) 867254721Semaste return true; 868254721Semaste const char *match_name = m_match_info.GetName(); 869254721Semaste if (!match_name) 870254721Semaste return true; 871254721Semaste 872254721Semaste return lldb_private::NameMatches (process_name, m_name_match_type, match_name); 873254721Semaste} 874254721Semaste 875254721Semastebool 876254721SemasteProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const 877254721Semaste{ 878254721Semaste if (!NameMatches (proc_info.GetName())) 879254721Semaste return false; 880254721Semaste 881254721Semaste if (m_match_info.ProcessIDIsValid() && 882254721Semaste m_match_info.GetProcessID() != proc_info.GetProcessID()) 883254721Semaste return false; 884254721Semaste 885254721Semaste if (m_match_info.ParentProcessIDIsValid() && 886254721Semaste m_match_info.GetParentProcessID() != proc_info.GetParentProcessID()) 887254721Semaste return false; 888254721Semaste 889254721Semaste if (m_match_info.UserIDIsValid () && 890254721Semaste m_match_info.GetUserID() != proc_info.GetUserID()) 891254721Semaste return false; 892254721Semaste 893254721Semaste if (m_match_info.GroupIDIsValid () && 894254721Semaste m_match_info.GetGroupID() != proc_info.GetGroupID()) 895254721Semaste return false; 896254721Semaste 897254721Semaste if (m_match_info.EffectiveUserIDIsValid () && 898254721Semaste m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID()) 899254721Semaste return false; 900254721Semaste 901254721Semaste if (m_match_info.EffectiveGroupIDIsValid () && 902254721Semaste m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID()) 903254721Semaste return false; 904254721Semaste 905254721Semaste if (m_match_info.GetArchitecture().IsValid() && 906254721Semaste !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture())) 907254721Semaste return false; 908254721Semaste return true; 909254721Semaste} 910254721Semaste 911254721Semastebool 912254721SemasteProcessInstanceInfoMatch::MatchAllProcesses () const 913254721Semaste{ 914254721Semaste if (m_name_match_type != eNameMatchIgnore) 915254721Semaste return false; 916254721Semaste 917254721Semaste if (m_match_info.ProcessIDIsValid()) 918254721Semaste return false; 919254721Semaste 920254721Semaste if (m_match_info.ParentProcessIDIsValid()) 921254721Semaste return false; 922254721Semaste 923254721Semaste if (m_match_info.UserIDIsValid ()) 924254721Semaste return false; 925254721Semaste 926254721Semaste if (m_match_info.GroupIDIsValid ()) 927254721Semaste return false; 928254721Semaste 929254721Semaste if (m_match_info.EffectiveUserIDIsValid ()) 930254721Semaste return false; 931254721Semaste 932254721Semaste if (m_match_info.EffectiveGroupIDIsValid ()) 933254721Semaste return false; 934254721Semaste 935254721Semaste if (m_match_info.GetArchitecture().IsValid()) 936254721Semaste return false; 937254721Semaste 938254721Semaste if (m_match_all_users) 939254721Semaste return false; 940254721Semaste 941254721Semaste return true; 942254721Semaste 943254721Semaste} 944254721Semaste 945254721Semastevoid 946254721SemasteProcessInstanceInfoMatch::Clear() 947254721Semaste{ 948254721Semaste m_match_info.Clear(); 949254721Semaste m_name_match_type = eNameMatchIgnore; 950254721Semaste m_match_all_users = false; 951254721Semaste} 952254721Semaste 953254721SemasteProcessSP 954254721SemasteProcess::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path) 955254721Semaste{ 956254721Semaste static uint32_t g_process_unique_id = 0; 957254721Semaste 958254721Semaste ProcessSP process_sp; 959254721Semaste ProcessCreateInstance create_callback = NULL; 960254721Semaste if (plugin_name) 961254721Semaste { 962254721Semaste ConstString const_plugin_name(plugin_name); 963254721Semaste create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name); 964254721Semaste if (create_callback) 965254721Semaste { 966254721Semaste process_sp = create_callback(target, listener, crash_file_path); 967254721Semaste if (process_sp) 968254721Semaste { 969254721Semaste if (process_sp->CanDebug(target, true)) 970254721Semaste { 971254721Semaste process_sp->m_process_unique_id = ++g_process_unique_id; 972254721Semaste } 973254721Semaste else 974254721Semaste process_sp.reset(); 975254721Semaste } 976254721Semaste } 977254721Semaste } 978254721Semaste else 979254721Semaste { 980254721Semaste for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx) 981254721Semaste { 982254721Semaste process_sp = create_callback(target, listener, crash_file_path); 983254721Semaste if (process_sp) 984254721Semaste { 985254721Semaste if (process_sp->CanDebug(target, false)) 986254721Semaste { 987254721Semaste process_sp->m_process_unique_id = ++g_process_unique_id; 988254721Semaste break; 989254721Semaste } 990254721Semaste else 991254721Semaste process_sp.reset(); 992254721Semaste } 993254721Semaste } 994254721Semaste } 995254721Semaste return process_sp; 996254721Semaste} 997254721Semaste 998254721SemasteConstString & 999254721SemasteProcess::GetStaticBroadcasterClass () 1000254721Semaste{ 1001254721Semaste static ConstString class_name ("lldb.process"); 1002254721Semaste return class_name; 1003254721Semaste} 1004254721Semaste 1005254721Semaste//---------------------------------------------------------------------- 1006254721Semaste// Process constructor 1007254721Semaste//---------------------------------------------------------------------- 1008254721SemasteProcess::Process(Target &target, Listener &listener) : 1009254721Semaste ProcessProperties (false), 1010254721Semaste UserID (LLDB_INVALID_PROCESS_ID), 1011254721Semaste Broadcaster (&(target.GetDebugger()), "lldb.process"), 1012254721Semaste m_target (target), 1013254721Semaste m_public_state (eStateUnloaded), 1014254721Semaste m_private_state (eStateUnloaded), 1015254721Semaste m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"), 1016254721Semaste m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"), 1017254721Semaste m_private_state_listener ("lldb.process.internal_state_listener"), 1018254721Semaste m_private_state_control_wait(), 1019254721Semaste m_private_state_thread (LLDB_INVALID_HOST_THREAD), 1020254721Semaste m_mod_id (), 1021254721Semaste m_process_unique_id(0), 1022254721Semaste m_thread_index_id (0), 1023254721Semaste m_thread_id_to_index_id_map (), 1024254721Semaste m_exit_status (-1), 1025254721Semaste m_exit_string (), 1026254721Semaste m_thread_mutex (Mutex::eMutexTypeRecursive), 1027254721Semaste m_thread_list_real (this), 1028254721Semaste m_thread_list (this), 1029263367Semaste m_extended_thread_list (this), 1030263367Semaste m_extended_thread_stop_id (0), 1031269024Semaste m_queue_list (this), 1032269024Semaste m_queue_list_stop_id (0), 1033254721Semaste m_notifications (), 1034254721Semaste m_image_tokens (), 1035254721Semaste m_listener (listener), 1036254721Semaste m_breakpoint_site_list (), 1037254721Semaste m_dynamic_checkers_ap (), 1038254721Semaste m_unix_signals (), 1039254721Semaste m_abi_sp (), 1040254721Semaste m_process_input_reader (), 1041254721Semaste m_stdio_communication ("process.stdio"), 1042254721Semaste m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), 1043254721Semaste m_stdout_data (), 1044254721Semaste m_stderr_data (), 1045254721Semaste m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive), 1046254721Semaste m_profile_data (), 1047254721Semaste m_memory_cache (*this), 1048254721Semaste m_allocated_memory_cache (*this), 1049254721Semaste m_should_detach (false), 1050254721Semaste m_next_event_action_ap(), 1051254721Semaste m_public_run_lock (), 1052254721Semaste m_private_run_lock (), 1053254721Semaste m_currently_handling_event(false), 1054254721Semaste m_finalize_called(false), 1055254721Semaste m_clear_thread_plans_on_stop (false), 1056269024Semaste m_force_next_event_delivery(false), 1057254721Semaste m_last_broadcast_state (eStateInvalid), 1058254721Semaste m_destroy_in_process (false), 1059254721Semaste m_can_jit(eCanJITDontKnow) 1060254721Semaste{ 1061254721Semaste CheckInWithManager (); 1062254721Semaste 1063254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 1064254721Semaste if (log) 1065254721Semaste log->Printf ("%p Process::Process()", this); 1066254721Semaste 1067254721Semaste SetEventName (eBroadcastBitStateChanged, "state-changed"); 1068254721Semaste SetEventName (eBroadcastBitInterrupt, "interrupt"); 1069254721Semaste SetEventName (eBroadcastBitSTDOUT, "stdout-available"); 1070254721Semaste SetEventName (eBroadcastBitSTDERR, "stderr-available"); 1071254721Semaste SetEventName (eBroadcastBitProfileData, "profile-data-available"); 1072254721Semaste 1073254721Semaste m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" ); 1074254721Semaste m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" ); 1075254721Semaste m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume"); 1076254721Semaste 1077254721Semaste listener.StartListeningForEvents (this, 1078254721Semaste eBroadcastBitStateChanged | 1079254721Semaste eBroadcastBitInterrupt | 1080254721Semaste eBroadcastBitSTDOUT | 1081254721Semaste eBroadcastBitSTDERR | 1082254721Semaste eBroadcastBitProfileData); 1083254721Semaste 1084254721Semaste m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster, 1085254721Semaste eBroadcastBitStateChanged | 1086254721Semaste eBroadcastBitInterrupt); 1087254721Semaste 1088254721Semaste m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster, 1089254721Semaste eBroadcastInternalStateControlStop | 1090254721Semaste eBroadcastInternalStateControlPause | 1091254721Semaste eBroadcastInternalStateControlResume); 1092254721Semaste} 1093254721Semaste 1094254721Semaste//---------------------------------------------------------------------- 1095254721Semaste// Destructor 1096254721Semaste//---------------------------------------------------------------------- 1097254721SemasteProcess::~Process() 1098254721Semaste{ 1099254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 1100254721Semaste if (log) 1101254721Semaste log->Printf ("%p Process::~Process()", this); 1102254721Semaste StopPrivateStateThread(); 1103254721Semaste} 1104254721Semaste 1105254721Semasteconst ProcessPropertiesSP & 1106254721SemasteProcess::GetGlobalProperties() 1107254721Semaste{ 1108254721Semaste static ProcessPropertiesSP g_settings_sp; 1109254721Semaste if (!g_settings_sp) 1110254721Semaste g_settings_sp.reset (new ProcessProperties (true)); 1111254721Semaste return g_settings_sp; 1112254721Semaste} 1113254721Semaste 1114254721Semastevoid 1115254721SemasteProcess::Finalize() 1116254721Semaste{ 1117254721Semaste switch (GetPrivateState()) 1118254721Semaste { 1119254721Semaste case eStateConnected: 1120254721Semaste case eStateAttaching: 1121254721Semaste case eStateLaunching: 1122254721Semaste case eStateStopped: 1123254721Semaste case eStateRunning: 1124254721Semaste case eStateStepping: 1125254721Semaste case eStateCrashed: 1126254721Semaste case eStateSuspended: 1127254721Semaste if (GetShouldDetach()) 1128254721Semaste { 1129254721Semaste // FIXME: This will have to be a process setting: 1130254721Semaste bool keep_stopped = false; 1131254721Semaste Detach(keep_stopped); 1132254721Semaste } 1133254721Semaste else 1134254721Semaste Destroy(); 1135254721Semaste break; 1136254721Semaste 1137254721Semaste case eStateInvalid: 1138254721Semaste case eStateUnloaded: 1139254721Semaste case eStateDetached: 1140254721Semaste case eStateExited: 1141254721Semaste break; 1142254721Semaste } 1143254721Semaste 1144254721Semaste // Clear our broadcaster before we proceed with destroying 1145254721Semaste Broadcaster::Clear(); 1146254721Semaste 1147254721Semaste // Do any cleanup needed prior to being destructed... Subclasses 1148254721Semaste // that override this method should call this superclass method as well. 1149254721Semaste 1150254721Semaste // We need to destroy the loader before the derived Process class gets destroyed 1151254721Semaste // since it is very likely that undoing the loader will require access to the real process. 1152254721Semaste m_dynamic_checkers_ap.reset(); 1153254721Semaste m_abi_sp.reset(); 1154254721Semaste m_os_ap.reset(); 1155263363Semaste m_system_runtime_ap.reset(); 1156254721Semaste m_dyld_ap.reset(); 1157254721Semaste m_thread_list_real.Destroy(); 1158254721Semaste m_thread_list.Destroy(); 1159263367Semaste m_extended_thread_list.Destroy(); 1160269024Semaste m_queue_list.Clear(); 1161269024Semaste m_queue_list_stop_id = 0; 1162254721Semaste std::vector<Notifications> empty_notifications; 1163254721Semaste m_notifications.swap(empty_notifications); 1164254721Semaste m_image_tokens.clear(); 1165254721Semaste m_memory_cache.Clear(); 1166254721Semaste m_allocated_memory_cache.Clear(); 1167254721Semaste m_language_runtimes.clear(); 1168254721Semaste m_next_event_action_ap.reset(); 1169254721Semaste//#ifdef LLDB_CONFIGURATION_DEBUG 1170254721Semaste// StreamFile s(stdout, false); 1171254721Semaste// EventSP event_sp; 1172254721Semaste// while (m_private_state_listener.GetNextEvent(event_sp)) 1173254721Semaste// { 1174254721Semaste// event_sp->Dump (&s); 1175254721Semaste// s.EOL(); 1176254721Semaste// } 1177254721Semaste//#endif 1178254721Semaste // We have to be very careful here as the m_private_state_listener might 1179254721Semaste // contain events that have ProcessSP values in them which can keep this 1180254721Semaste // process around forever. These events need to be cleared out. 1181254721Semaste m_private_state_listener.Clear(); 1182254721Semaste m_public_run_lock.TrySetRunning(); // This will do nothing if already locked 1183254721Semaste m_public_run_lock.SetStopped(); 1184254721Semaste m_private_run_lock.TrySetRunning(); // This will do nothing if already locked 1185254721Semaste m_private_run_lock.SetStopped(); 1186254721Semaste m_finalize_called = true; 1187254721Semaste} 1188254721Semaste 1189254721Semastevoid 1190254721SemasteProcess::RegisterNotificationCallbacks (const Notifications& callbacks) 1191254721Semaste{ 1192254721Semaste m_notifications.push_back(callbacks); 1193254721Semaste if (callbacks.initialize != NULL) 1194254721Semaste callbacks.initialize (callbacks.baton, this); 1195254721Semaste} 1196254721Semaste 1197254721Semastebool 1198254721SemasteProcess::UnregisterNotificationCallbacks(const Notifications& callbacks) 1199254721Semaste{ 1200254721Semaste std::vector<Notifications>::iterator pos, end = m_notifications.end(); 1201254721Semaste for (pos = m_notifications.begin(); pos != end; ++pos) 1202254721Semaste { 1203254721Semaste if (pos->baton == callbacks.baton && 1204254721Semaste pos->initialize == callbacks.initialize && 1205254721Semaste pos->process_state_changed == callbacks.process_state_changed) 1206254721Semaste { 1207254721Semaste m_notifications.erase(pos); 1208254721Semaste return true; 1209254721Semaste } 1210254721Semaste } 1211254721Semaste return false; 1212254721Semaste} 1213254721Semaste 1214254721Semastevoid 1215254721SemasteProcess::SynchronouslyNotifyStateChanged (StateType state) 1216254721Semaste{ 1217254721Semaste std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end(); 1218254721Semaste for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos) 1219254721Semaste { 1220254721Semaste if (notification_pos->process_state_changed) 1221254721Semaste notification_pos->process_state_changed (notification_pos->baton, this, state); 1222254721Semaste } 1223254721Semaste} 1224254721Semaste 1225254721Semaste// FIXME: We need to do some work on events before the general Listener sees them. 1226254721Semaste// For instance if we are continuing from a breakpoint, we need to ensure that we do 1227254721Semaste// the little "insert real insn, step & stop" trick. But we can't do that when the 1228254721Semaste// event is delivered by the broadcaster - since that is done on the thread that is 1229254721Semaste// waiting for new events, so if we needed more than one event for our handling, we would 1230254721Semaste// stall. So instead we do it when we fetch the event off of the queue. 1231254721Semaste// 1232254721Semaste 1233254721SemasteStateType 1234254721SemasteProcess::GetNextEvent (EventSP &event_sp) 1235254721Semaste{ 1236254721Semaste StateType state = eStateInvalid; 1237254721Semaste 1238254721Semaste if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp) 1239254721Semaste state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 1240254721Semaste 1241254721Semaste return state; 1242254721Semaste} 1243254721Semaste 1244254721Semaste 1245254721SemasteStateType 1246269024SemasteProcess::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener) 1247254721Semaste{ 1248254721Semaste // We can't just wait for a "stopped" event, because the stopped event may have restarted the target. 1249254721Semaste // We have to actually check each event, and in the case of a stopped event check the restarted flag 1250254721Semaste // on the event. 1251254721Semaste if (event_sp_ptr) 1252254721Semaste event_sp_ptr->reset(); 1253254721Semaste StateType state = GetState(); 1254254721Semaste // If we are exited or detached, we won't ever get back to any 1255254721Semaste // other valid state... 1256254721Semaste if (state == eStateDetached || state == eStateExited) 1257254721Semaste return state; 1258254721Semaste 1259263363Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1260263363Semaste if (log) 1261263363Semaste log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout); 1262263363Semaste 1263263363Semaste if (!wait_always && 1264263363Semaste StateIsStoppedState(state, true) && 1265263363Semaste StateIsStoppedState(GetPrivateState(), true)) { 1266263363Semaste if (log) 1267263363Semaste log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.", 1268263363Semaste __FUNCTION__); 1269263363Semaste return state; 1270263363Semaste } 1271263363Semaste 1272254721Semaste while (state != eStateInvalid) 1273254721Semaste { 1274254721Semaste EventSP event_sp; 1275269024Semaste state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener); 1276254721Semaste if (event_sp_ptr && event_sp) 1277254721Semaste *event_sp_ptr = event_sp; 1278254721Semaste 1279254721Semaste switch (state) 1280254721Semaste { 1281254721Semaste case eStateCrashed: 1282254721Semaste case eStateDetached: 1283254721Semaste case eStateExited: 1284254721Semaste case eStateUnloaded: 1285269024Semaste // We need to toggle the run lock as this won't get done in 1286269024Semaste // SetPublicState() if the process is hijacked. 1287269024Semaste if (hijack_listener) 1288269024Semaste m_public_run_lock.SetStopped(); 1289254721Semaste return state; 1290254721Semaste case eStateStopped: 1291254721Semaste if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 1292254721Semaste continue; 1293254721Semaste else 1294269024Semaste { 1295269024Semaste // We need to toggle the run lock as this won't get done in 1296269024Semaste // SetPublicState() if the process is hijacked. 1297269024Semaste if (hijack_listener) 1298269024Semaste m_public_run_lock.SetStopped(); 1299254721Semaste return state; 1300269024Semaste } 1301254721Semaste default: 1302254721Semaste continue; 1303254721Semaste } 1304254721Semaste } 1305254721Semaste return state; 1306254721Semaste} 1307254721Semaste 1308254721Semaste 1309254721SemasteStateType 1310254721SemasteProcess::WaitForState 1311254721Semaste( 1312254721Semaste const TimeValue *timeout, 1313269024Semaste const StateType *match_states, 1314269024Semaste const uint32_t num_match_states 1315254721Semaste) 1316254721Semaste{ 1317254721Semaste EventSP event_sp; 1318254721Semaste uint32_t i; 1319254721Semaste StateType state = GetState(); 1320254721Semaste while (state != eStateInvalid) 1321254721Semaste { 1322254721Semaste // If we are exited or detached, we won't ever get back to any 1323254721Semaste // other valid state... 1324254721Semaste if (state == eStateDetached || state == eStateExited) 1325254721Semaste return state; 1326254721Semaste 1327269024Semaste state = WaitForStateChangedEvents (timeout, event_sp, NULL); 1328254721Semaste 1329254721Semaste for (i=0; i<num_match_states; ++i) 1330254721Semaste { 1331254721Semaste if (match_states[i] == state) 1332254721Semaste return state; 1333254721Semaste } 1334254721Semaste } 1335254721Semaste return state; 1336254721Semaste} 1337254721Semaste 1338254721Semastebool 1339254721SemasteProcess::HijackProcessEvents (Listener *listener) 1340254721Semaste{ 1341254721Semaste if (listener != NULL) 1342254721Semaste { 1343254721Semaste return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt); 1344254721Semaste } 1345254721Semaste else 1346254721Semaste return false; 1347254721Semaste} 1348254721Semaste 1349254721Semastevoid 1350254721SemasteProcess::RestoreProcessEvents () 1351254721Semaste{ 1352254721Semaste RestoreBroadcaster(); 1353254721Semaste} 1354254721Semaste 1355254721Semastebool 1356254721SemasteProcess::HijackPrivateProcessEvents (Listener *listener) 1357254721Semaste{ 1358254721Semaste if (listener != NULL) 1359254721Semaste { 1360254721Semaste return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt); 1361254721Semaste } 1362254721Semaste else 1363254721Semaste return false; 1364254721Semaste} 1365254721Semaste 1366254721Semastevoid 1367254721SemasteProcess::RestorePrivateProcessEvents () 1368254721Semaste{ 1369254721Semaste m_private_state_broadcaster.RestoreBroadcaster(); 1370254721Semaste} 1371254721Semaste 1372254721SemasteStateType 1373269024SemasteProcess::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener) 1374254721Semaste{ 1375254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1376254721Semaste 1377254721Semaste if (log) 1378254721Semaste log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1379254721Semaste 1380269024Semaste Listener *listener = hijack_listener; 1381269024Semaste if (listener == NULL) 1382269024Semaste listener = &m_listener; 1383269024Semaste 1384254721Semaste StateType state = eStateInvalid; 1385269024Semaste if (listener->WaitForEventForBroadcasterWithType (timeout, 1386269024Semaste this, 1387269024Semaste eBroadcastBitStateChanged | eBroadcastBitInterrupt, 1388269024Semaste event_sp)) 1389254721Semaste { 1390254721Semaste if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1391254721Semaste state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1392254721Semaste else if (log) 1393254721Semaste log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__); 1394254721Semaste } 1395254721Semaste 1396254721Semaste if (log) 1397254721Semaste log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 1398254721Semaste __FUNCTION__, 1399254721Semaste timeout, 1400254721Semaste StateAsCString(state)); 1401254721Semaste return state; 1402254721Semaste} 1403254721Semaste 1404254721SemasteEvent * 1405254721SemasteProcess::PeekAtStateChangedEvents () 1406254721Semaste{ 1407254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1408254721Semaste 1409254721Semaste if (log) 1410254721Semaste log->Printf ("Process::%s...", __FUNCTION__); 1411254721Semaste 1412254721Semaste Event *event_ptr; 1413254721Semaste event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this, 1414254721Semaste eBroadcastBitStateChanged); 1415254721Semaste if (log) 1416254721Semaste { 1417254721Semaste if (event_ptr) 1418254721Semaste { 1419254721Semaste log->Printf ("Process::%s (event_ptr) => %s", 1420254721Semaste __FUNCTION__, 1421254721Semaste StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr))); 1422254721Semaste } 1423254721Semaste else 1424254721Semaste { 1425254721Semaste log->Printf ("Process::%s no events found", 1426254721Semaste __FUNCTION__); 1427254721Semaste } 1428254721Semaste } 1429254721Semaste return event_ptr; 1430254721Semaste} 1431254721Semaste 1432254721SemasteStateType 1433254721SemasteProcess::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp) 1434254721Semaste{ 1435254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1436254721Semaste 1437254721Semaste if (log) 1438254721Semaste log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1439254721Semaste 1440254721Semaste StateType state = eStateInvalid; 1441254721Semaste if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout, 1442254721Semaste &m_private_state_broadcaster, 1443254721Semaste eBroadcastBitStateChanged | eBroadcastBitInterrupt, 1444254721Semaste event_sp)) 1445254721Semaste if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1446254721Semaste state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1447254721Semaste 1448254721Semaste // This is a bit of a hack, but when we wait here we could very well return 1449254721Semaste // to the command-line, and that could disable the log, which would render the 1450254721Semaste // log we got above invalid. 1451254721Semaste if (log) 1452254721Semaste { 1453254721Semaste if (state == eStateInvalid) 1454254721Semaste log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout); 1455254721Semaste else 1456254721Semaste log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state)); 1457254721Semaste } 1458254721Semaste return state; 1459254721Semaste} 1460254721Semaste 1461254721Semastebool 1462254721SemasteProcess::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only) 1463254721Semaste{ 1464254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1465254721Semaste 1466254721Semaste if (log) 1467254721Semaste log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1468254721Semaste 1469254721Semaste if (control_only) 1470254721Semaste return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp); 1471254721Semaste else 1472254721Semaste return m_private_state_listener.WaitForEvent(timeout, event_sp); 1473254721Semaste} 1474254721Semaste 1475254721Semastebool 1476254721SemasteProcess::IsRunning () const 1477254721Semaste{ 1478254721Semaste return StateIsRunningState (m_public_state.GetValue()); 1479254721Semaste} 1480254721Semaste 1481254721Semasteint 1482254721SemasteProcess::GetExitStatus () 1483254721Semaste{ 1484254721Semaste if (m_public_state.GetValue() == eStateExited) 1485254721Semaste return m_exit_status; 1486254721Semaste return -1; 1487254721Semaste} 1488254721Semaste 1489254721Semaste 1490254721Semasteconst char * 1491254721SemasteProcess::GetExitDescription () 1492254721Semaste{ 1493254721Semaste if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 1494254721Semaste return m_exit_string.c_str(); 1495254721Semaste return NULL; 1496254721Semaste} 1497254721Semaste 1498254721Semastebool 1499254721SemasteProcess::SetExitStatus (int status, const char *cstr) 1500254721Semaste{ 1501254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1502254721Semaste if (log) 1503254721Semaste log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", 1504254721Semaste status, status, 1505254721Semaste cstr ? "\"" : "", 1506254721Semaste cstr ? cstr : "NULL", 1507254721Semaste cstr ? "\"" : ""); 1508254721Semaste 1509254721Semaste // We were already in the exited state 1510254721Semaste if (m_private_state.GetValue() == eStateExited) 1511254721Semaste { 1512254721Semaste if (log) 1513254721Semaste log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited"); 1514254721Semaste return false; 1515254721Semaste } 1516254721Semaste 1517254721Semaste m_exit_status = status; 1518254721Semaste if (cstr) 1519254721Semaste m_exit_string = cstr; 1520254721Semaste else 1521254721Semaste m_exit_string.clear(); 1522254721Semaste 1523254721Semaste DidExit (); 1524254721Semaste 1525254721Semaste SetPrivateState (eStateExited); 1526269024Semaste CancelWatchForSTDIN (true); 1527254721Semaste return true; 1528254721Semaste} 1529254721Semaste 1530254721Semaste// This static callback can be used to watch for local child processes on 1531254721Semaste// the current host. The the child process exits, the process will be 1532254721Semaste// found in the global target list (we want to be completely sure that the 1533254721Semaste// lldb_private::Process doesn't go away before we can deliver the signal. 1534254721Semastebool 1535254721SemasteProcess::SetProcessExitStatus (void *callback_baton, 1536254721Semaste lldb::pid_t pid, 1537254721Semaste bool exited, 1538254721Semaste int signo, // Zero for no signal 1539254721Semaste int exit_status // Exit value of process if signal is zero 1540254721Semaste) 1541254721Semaste{ 1542254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 1543254721Semaste if (log) 1544254721Semaste log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n", 1545254721Semaste callback_baton, 1546254721Semaste pid, 1547254721Semaste exited, 1548254721Semaste signo, 1549254721Semaste exit_status); 1550254721Semaste 1551254721Semaste if (exited) 1552254721Semaste { 1553254721Semaste TargetSP target_sp(Debugger::FindTargetWithProcessID (pid)); 1554254721Semaste if (target_sp) 1555254721Semaste { 1556254721Semaste ProcessSP process_sp (target_sp->GetProcessSP()); 1557254721Semaste if (process_sp) 1558254721Semaste { 1559254721Semaste const char *signal_cstr = NULL; 1560254721Semaste if (signo) 1561254721Semaste signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 1562254721Semaste 1563254721Semaste process_sp->SetExitStatus (exit_status, signal_cstr); 1564254721Semaste } 1565254721Semaste } 1566254721Semaste return true; 1567254721Semaste } 1568254721Semaste return false; 1569254721Semaste} 1570254721Semaste 1571254721Semaste 1572254721Semastevoid 1573254721SemasteProcess::UpdateThreadListIfNeeded () 1574254721Semaste{ 1575254721Semaste const uint32_t stop_id = GetStopID(); 1576254721Semaste if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID()) 1577254721Semaste { 1578254721Semaste const StateType state = GetPrivateState(); 1579254721Semaste if (StateIsStoppedState (state, true)) 1580254721Semaste { 1581254721Semaste Mutex::Locker locker (m_thread_list.GetMutex ()); 1582254721Semaste // m_thread_list does have its own mutex, but we need to 1583254721Semaste // hold onto the mutex between the call to UpdateThreadList(...) 1584254721Semaste // and the os->UpdateThreadList(...) so it doesn't change on us 1585254721Semaste ThreadList &old_thread_list = m_thread_list; 1586254721Semaste ThreadList real_thread_list(this); 1587254721Semaste ThreadList new_thread_list(this); 1588254721Semaste // Always update the thread list with the protocol specific 1589254721Semaste // thread list, but only update if "true" is returned 1590254721Semaste if (UpdateThreadList (m_thread_list_real, real_thread_list)) 1591254721Semaste { 1592254721Semaste // Don't call into the OperatingSystem to update the thread list if we are shutting down, since 1593254721Semaste // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is 1594254721Semaste // shutting us down, causing a deadlock. 1595254721Semaste if (!m_destroy_in_process) 1596254721Semaste { 1597254721Semaste OperatingSystem *os = GetOperatingSystem (); 1598254721Semaste if (os) 1599254721Semaste { 1600254721Semaste // Clear any old backing threads where memory threads might have been 1601254721Semaste // backed by actual threads from the lldb_private::Process subclass 1602254721Semaste size_t num_old_threads = old_thread_list.GetSize(false); 1603254721Semaste for (size_t i=0; i<num_old_threads; ++i) 1604254721Semaste old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread(); 1605254721Semaste 1606254721Semaste // Now let the OperatingSystem plug-in update the thread list 1607254721Semaste os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in 1608254721Semaste real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass 1609254721Semaste new_thread_list); // The new thread list that we will show to the user that gets filled in 1610254721Semaste } 1611254721Semaste else 1612254721Semaste { 1613254721Semaste // No OS plug-in, the new thread list is the same as the real thread list 1614254721Semaste new_thread_list = real_thread_list; 1615254721Semaste } 1616254721Semaste } 1617254721Semaste 1618254721Semaste m_thread_list_real.Update(real_thread_list); 1619254721Semaste m_thread_list.Update (new_thread_list); 1620254721Semaste m_thread_list.SetStopID (stop_id); 1621263367Semaste 1622263367Semaste if (GetLastNaturalStopID () != m_extended_thread_stop_id) 1623263367Semaste { 1624263367Semaste // Clear any extended threads that we may have accumulated previously 1625263367Semaste m_extended_thread_list.Clear(); 1626263367Semaste m_extended_thread_stop_id = GetLastNaturalStopID (); 1627269024Semaste 1628269024Semaste m_queue_list.Clear(); 1629269024Semaste m_queue_list_stop_id = GetLastNaturalStopID (); 1630263367Semaste } 1631254721Semaste } 1632254721Semaste } 1633254721Semaste } 1634254721Semaste} 1635254721Semaste 1636269024Semastevoid 1637269024SemasteProcess::UpdateQueueListIfNeeded () 1638269024Semaste{ 1639269024Semaste if (m_system_runtime_ap.get()) 1640269024Semaste { 1641269024Semaste if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID()) 1642269024Semaste { 1643269024Semaste const StateType state = GetPrivateState(); 1644269024Semaste if (StateIsStoppedState (state, true)) 1645269024Semaste { 1646269024Semaste m_system_runtime_ap->PopulateQueueList (m_queue_list); 1647269024Semaste m_queue_list_stop_id = GetLastNaturalStopID(); 1648269024Semaste } 1649269024Semaste } 1650269024Semaste } 1651269024Semaste} 1652269024Semaste 1653254721SemasteThreadSP 1654254721SemasteProcess::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context) 1655254721Semaste{ 1656254721Semaste OperatingSystem *os = GetOperatingSystem (); 1657254721Semaste if (os) 1658254721Semaste return os->CreateThread(tid, context); 1659254721Semaste return ThreadSP(); 1660254721Semaste} 1661254721Semaste 1662254721Semasteuint32_t 1663254721SemasteProcess::GetNextThreadIndexID (uint64_t thread_id) 1664254721Semaste{ 1665254721Semaste return AssignIndexIDToThread(thread_id); 1666254721Semaste} 1667254721Semaste 1668254721Semastebool 1669254721SemasteProcess::HasAssignedIndexIDToThread(uint64_t thread_id) 1670254721Semaste{ 1671254721Semaste std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id); 1672254721Semaste if (iterator == m_thread_id_to_index_id_map.end()) 1673254721Semaste { 1674254721Semaste return false; 1675254721Semaste } 1676254721Semaste else 1677254721Semaste { 1678254721Semaste return true; 1679254721Semaste } 1680254721Semaste} 1681254721Semaste 1682254721Semasteuint32_t 1683254721SemasteProcess::AssignIndexIDToThread(uint64_t thread_id) 1684254721Semaste{ 1685254721Semaste uint32_t result = 0; 1686254721Semaste std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id); 1687254721Semaste if (iterator == m_thread_id_to_index_id_map.end()) 1688254721Semaste { 1689254721Semaste result = ++m_thread_index_id; 1690254721Semaste m_thread_id_to_index_id_map[thread_id] = result; 1691254721Semaste } 1692254721Semaste else 1693254721Semaste { 1694254721Semaste result = iterator->second; 1695254721Semaste } 1696254721Semaste 1697254721Semaste return result; 1698254721Semaste} 1699254721Semaste 1700254721SemasteStateType 1701254721SemasteProcess::GetState() 1702254721Semaste{ 1703254721Semaste // If any other threads access this we will need a mutex for it 1704254721Semaste return m_public_state.GetValue (); 1705254721Semaste} 1706254721Semaste 1707254721Semastevoid 1708254721SemasteProcess::SetPublicState (StateType new_state, bool restarted) 1709254721Semaste{ 1710254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1711254721Semaste if (log) 1712254721Semaste log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted); 1713254721Semaste const StateType old_state = m_public_state.GetValue(); 1714254721Semaste m_public_state.SetValue (new_state); 1715254721Semaste 1716254721Semaste // On the transition from Run to Stopped, we unlock the writer end of the 1717254721Semaste // run lock. The lock gets locked in Resume, which is the public API 1718254721Semaste // to tell the program to run. 1719254721Semaste if (!IsHijackedForEvent(eBroadcastBitStateChanged)) 1720254721Semaste { 1721254721Semaste if (new_state == eStateDetached) 1722254721Semaste { 1723254721Semaste if (log) 1724254721Semaste log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state)); 1725254721Semaste m_public_run_lock.SetStopped(); 1726254721Semaste } 1727254721Semaste else 1728254721Semaste { 1729254721Semaste const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1730254721Semaste const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1731254721Semaste if ((old_state_is_stopped != new_state_is_stopped)) 1732254721Semaste { 1733254721Semaste if (new_state_is_stopped && !restarted) 1734254721Semaste { 1735254721Semaste if (log) 1736254721Semaste log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state)); 1737254721Semaste m_public_run_lock.SetStopped(); 1738254721Semaste } 1739254721Semaste } 1740254721Semaste } 1741254721Semaste } 1742254721Semaste} 1743254721Semaste 1744254721SemasteError 1745254721SemasteProcess::Resume () 1746254721Semaste{ 1747254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1748254721Semaste if (log) 1749254721Semaste log->Printf("Process::Resume -- locking run lock"); 1750254721Semaste if (!m_public_run_lock.TrySetRunning()) 1751254721Semaste { 1752254721Semaste Error error("Resume request failed - process still running."); 1753254721Semaste if (log) 1754254721Semaste log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming."); 1755254721Semaste return error; 1756254721Semaste } 1757254721Semaste return PrivateResume(); 1758254721Semaste} 1759254721Semaste 1760254721SemasteStateType 1761254721SemasteProcess::GetPrivateState () 1762254721Semaste{ 1763254721Semaste return m_private_state.GetValue(); 1764254721Semaste} 1765254721Semaste 1766254721Semastevoid 1767254721SemasteProcess::SetPrivateState (StateType new_state) 1768254721Semaste{ 1769254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1770254721Semaste bool state_changed = false; 1771254721Semaste 1772254721Semaste if (log) 1773254721Semaste log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 1774254721Semaste 1775254721Semaste Mutex::Locker thread_locker(m_thread_list.GetMutex()); 1776254721Semaste Mutex::Locker locker(m_private_state.GetMutex()); 1777254721Semaste 1778254721Semaste const StateType old_state = m_private_state.GetValueNoLock (); 1779254721Semaste state_changed = old_state != new_state; 1780254721Semaste 1781254721Semaste const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1782254721Semaste const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1783254721Semaste if (old_state_is_stopped != new_state_is_stopped) 1784254721Semaste { 1785254721Semaste if (new_state_is_stopped) 1786254721Semaste m_private_run_lock.SetStopped(); 1787254721Semaste else 1788254721Semaste m_private_run_lock.SetRunning(); 1789254721Semaste } 1790254721Semaste 1791254721Semaste if (state_changed) 1792254721Semaste { 1793254721Semaste m_private_state.SetValueNoLock (new_state); 1794254721Semaste if (StateIsStoppedState(new_state, false)) 1795254721Semaste { 1796254721Semaste // Note, this currently assumes that all threads in the list 1797254721Semaste // stop when the process stops. In the future we will want to 1798254721Semaste // support a debugging model where some threads continue to run 1799254721Semaste // while others are stopped. When that happens we will either need 1800254721Semaste // a way for the thread list to identify which threads are stopping 1801254721Semaste // or create a special thread list containing only threads which 1802254721Semaste // actually stopped. 1803254721Semaste // 1804254721Semaste // The process plugin is responsible for managing the actual 1805254721Semaste // behavior of the threads and should have stopped any threads 1806254721Semaste // that are going to stop before we get here. 1807254721Semaste m_thread_list.DidStop(); 1808254721Semaste 1809254721Semaste m_mod_id.BumpStopID(); 1810254721Semaste m_memory_cache.Clear(); 1811254721Semaste if (log) 1812254721Semaste log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID()); 1813254721Semaste } 1814254721Semaste // Use our target to get a shared pointer to ourselves... 1815254721Semaste if (m_finalize_called && PrivateStateThreadIsValid() == false) 1816254721Semaste BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)); 1817254721Semaste else 1818254721Semaste m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)); 1819254721Semaste } 1820254721Semaste else 1821254721Semaste { 1822254721Semaste if (log) 1823254721Semaste log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state)); 1824254721Semaste } 1825254721Semaste} 1826254721Semaste 1827254721Semastevoid 1828254721SemasteProcess::SetRunningUserExpression (bool on) 1829254721Semaste{ 1830254721Semaste m_mod_id.SetRunningUserExpression (on); 1831254721Semaste} 1832254721Semaste 1833254721Semasteaddr_t 1834254721SemasteProcess::GetImageInfoAddress() 1835254721Semaste{ 1836254721Semaste return LLDB_INVALID_ADDRESS; 1837254721Semaste} 1838254721Semaste 1839254721Semaste//---------------------------------------------------------------------- 1840254721Semaste// LoadImage 1841254721Semaste// 1842254721Semaste// This function provides a default implementation that works for most 1843254721Semaste// unix variants. Any Process subclasses that need to do shared library 1844254721Semaste// loading differently should override LoadImage and UnloadImage and 1845254721Semaste// do what is needed. 1846254721Semaste//---------------------------------------------------------------------- 1847254721Semasteuint32_t 1848254721SemasteProcess::LoadImage (const FileSpec &image_spec, Error &error) 1849254721Semaste{ 1850254721Semaste char path[PATH_MAX]; 1851254721Semaste image_spec.GetPath(path, sizeof(path)); 1852254721Semaste 1853254721Semaste DynamicLoader *loader = GetDynamicLoader(); 1854254721Semaste if (loader) 1855254721Semaste { 1856254721Semaste error = loader->CanLoadImage(); 1857254721Semaste if (error.Fail()) 1858254721Semaste return LLDB_INVALID_IMAGE_TOKEN; 1859254721Semaste } 1860254721Semaste 1861254721Semaste if (error.Success()) 1862254721Semaste { 1863254721Semaste ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1864254721Semaste 1865254721Semaste if (thread_sp) 1866254721Semaste { 1867254721Semaste StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1868254721Semaste 1869254721Semaste if (frame_sp) 1870254721Semaste { 1871254721Semaste ExecutionContext exe_ctx; 1872254721Semaste frame_sp->CalculateExecutionContext (exe_ctx); 1873263363Semaste EvaluateExpressionOptions expr_options; 1874263363Semaste expr_options.SetUnwindOnError(true); 1875263363Semaste expr_options.SetIgnoreBreakpoints(true); 1876263363Semaste expr_options.SetExecutionPolicy(eExecutionPolicyAlways); 1877254721Semaste StreamString expr; 1878254721Semaste expr.Printf("dlopen (\"%s\", 2)", path); 1879254721Semaste const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n"; 1880254721Semaste lldb::ValueObjectSP result_valobj_sp; 1881263363Semaste Error expr_error; 1882254721Semaste ClangUserExpression::Evaluate (exe_ctx, 1883263363Semaste expr_options, 1884254721Semaste expr.GetData(), 1885254721Semaste prefix, 1886254721Semaste result_valobj_sp, 1887263363Semaste expr_error); 1888263363Semaste if (expr_error.Success()) 1889254721Semaste { 1890263363Semaste error = result_valobj_sp->GetError(); 1891263363Semaste if (error.Success()) 1892254721Semaste { 1893263363Semaste Scalar scalar; 1894263363Semaste if (result_valobj_sp->ResolveValue (scalar)) 1895254721Semaste { 1896263363Semaste addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 1897263363Semaste if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS) 1898263363Semaste { 1899263363Semaste uint32_t image_token = m_image_tokens.size(); 1900263363Semaste m_image_tokens.push_back (image_ptr); 1901263363Semaste return image_token; 1902263363Semaste } 1903254721Semaste } 1904254721Semaste } 1905254721Semaste } 1906254721Semaste } 1907254721Semaste } 1908254721Semaste } 1909254721Semaste if (!error.AsCString()) 1910254721Semaste error.SetErrorStringWithFormat("unable to load '%s'", path); 1911254721Semaste return LLDB_INVALID_IMAGE_TOKEN; 1912254721Semaste} 1913254721Semaste 1914254721Semaste//---------------------------------------------------------------------- 1915254721Semaste// UnloadImage 1916254721Semaste// 1917254721Semaste// This function provides a default implementation that works for most 1918254721Semaste// unix variants. Any Process subclasses that need to do shared library 1919254721Semaste// loading differently should override LoadImage and UnloadImage and 1920254721Semaste// do what is needed. 1921254721Semaste//---------------------------------------------------------------------- 1922254721SemasteError 1923254721SemasteProcess::UnloadImage (uint32_t image_token) 1924254721Semaste{ 1925254721Semaste Error error; 1926254721Semaste if (image_token < m_image_tokens.size()) 1927254721Semaste { 1928254721Semaste const addr_t image_addr = m_image_tokens[image_token]; 1929254721Semaste if (image_addr == LLDB_INVALID_ADDRESS) 1930254721Semaste { 1931254721Semaste error.SetErrorString("image already unloaded"); 1932254721Semaste } 1933254721Semaste else 1934254721Semaste { 1935254721Semaste DynamicLoader *loader = GetDynamicLoader(); 1936254721Semaste if (loader) 1937254721Semaste error = loader->CanLoadImage(); 1938254721Semaste 1939254721Semaste if (error.Success()) 1940254721Semaste { 1941254721Semaste ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1942254721Semaste 1943254721Semaste if (thread_sp) 1944254721Semaste { 1945254721Semaste StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1946254721Semaste 1947254721Semaste if (frame_sp) 1948254721Semaste { 1949254721Semaste ExecutionContext exe_ctx; 1950254721Semaste frame_sp->CalculateExecutionContext (exe_ctx); 1951263363Semaste EvaluateExpressionOptions expr_options; 1952263363Semaste expr_options.SetUnwindOnError(true); 1953263363Semaste expr_options.SetIgnoreBreakpoints(true); 1954263363Semaste expr_options.SetExecutionPolicy(eExecutionPolicyAlways); 1955254721Semaste StreamString expr; 1956254721Semaste expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr); 1957254721Semaste const char *prefix = "extern \"C\" int dlclose(void* handle);\n"; 1958254721Semaste lldb::ValueObjectSP result_valobj_sp; 1959263363Semaste Error expr_error; 1960254721Semaste ClangUserExpression::Evaluate (exe_ctx, 1961263363Semaste expr_options, 1962254721Semaste expr.GetData(), 1963254721Semaste prefix, 1964254721Semaste result_valobj_sp, 1965263363Semaste expr_error); 1966254721Semaste if (result_valobj_sp->GetError().Success()) 1967254721Semaste { 1968254721Semaste Scalar scalar; 1969254721Semaste if (result_valobj_sp->ResolveValue (scalar)) 1970254721Semaste { 1971254721Semaste if (scalar.UInt(1)) 1972254721Semaste { 1973254721Semaste error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData()); 1974254721Semaste } 1975254721Semaste else 1976254721Semaste { 1977254721Semaste m_image_tokens[image_token] = LLDB_INVALID_ADDRESS; 1978254721Semaste } 1979254721Semaste } 1980254721Semaste } 1981254721Semaste else 1982254721Semaste { 1983254721Semaste error = result_valobj_sp->GetError(); 1984254721Semaste } 1985254721Semaste } 1986254721Semaste } 1987254721Semaste } 1988254721Semaste } 1989254721Semaste } 1990254721Semaste else 1991254721Semaste { 1992254721Semaste error.SetErrorString("invalid image token"); 1993254721Semaste } 1994254721Semaste return error; 1995254721Semaste} 1996254721Semaste 1997254721Semasteconst lldb::ABISP & 1998254721SemasteProcess::GetABI() 1999254721Semaste{ 2000254721Semaste if (!m_abi_sp) 2001254721Semaste m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture()); 2002254721Semaste return m_abi_sp; 2003254721Semaste} 2004254721Semaste 2005254721SemasteLanguageRuntime * 2006254721SemasteProcess::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null) 2007254721Semaste{ 2008254721Semaste LanguageRuntimeCollection::iterator pos; 2009254721Semaste pos = m_language_runtimes.find (language); 2010254721Semaste if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) 2011254721Semaste { 2012254721Semaste lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language)); 2013254721Semaste 2014254721Semaste m_language_runtimes[language] = runtime_sp; 2015254721Semaste return runtime_sp.get(); 2016254721Semaste } 2017254721Semaste else 2018254721Semaste return (*pos).second.get(); 2019254721Semaste} 2020254721Semaste 2021254721SemasteCPPLanguageRuntime * 2022254721SemasteProcess::GetCPPLanguageRuntime (bool retry_if_null) 2023254721Semaste{ 2024254721Semaste LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null); 2025254721Semaste if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus) 2026254721Semaste return static_cast<CPPLanguageRuntime *> (runtime); 2027254721Semaste return NULL; 2028254721Semaste} 2029254721Semaste 2030254721SemasteObjCLanguageRuntime * 2031254721SemasteProcess::GetObjCLanguageRuntime (bool retry_if_null) 2032254721Semaste{ 2033254721Semaste LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null); 2034254721Semaste if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC) 2035254721Semaste return static_cast<ObjCLanguageRuntime *> (runtime); 2036254721Semaste return NULL; 2037254721Semaste} 2038254721Semaste 2039254721Semastebool 2040254721SemasteProcess::IsPossibleDynamicValue (ValueObject& in_value) 2041254721Semaste{ 2042254721Semaste if (in_value.IsDynamic()) 2043254721Semaste return false; 2044254721Semaste LanguageType known_type = in_value.GetObjectRuntimeLanguage(); 2045254721Semaste 2046254721Semaste if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) 2047254721Semaste { 2048254721Semaste LanguageRuntime *runtime = GetLanguageRuntime (known_type); 2049254721Semaste return runtime ? runtime->CouldHaveDynamicValue(in_value) : false; 2050254721Semaste } 2051254721Semaste 2052254721Semaste LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus); 2053254721Semaste if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value)) 2054254721Semaste return true; 2055254721Semaste 2056254721Semaste LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC); 2057254721Semaste return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false; 2058254721Semaste} 2059254721Semaste 2060254721SemasteBreakpointSiteList & 2061254721SemasteProcess::GetBreakpointSiteList() 2062254721Semaste{ 2063254721Semaste return m_breakpoint_site_list; 2064254721Semaste} 2065254721Semaste 2066254721Semasteconst BreakpointSiteList & 2067254721SemasteProcess::GetBreakpointSiteList() const 2068254721Semaste{ 2069254721Semaste return m_breakpoint_site_list; 2070254721Semaste} 2071254721Semaste 2072254721Semaste 2073254721Semastevoid 2074254721SemasteProcess::DisableAllBreakpointSites () 2075254721Semaste{ 2076254721Semaste m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void { 2077254721Semaste// bp_site->SetEnabled(true); 2078254721Semaste DisableBreakpointSite(bp_site); 2079254721Semaste }); 2080254721Semaste} 2081254721Semaste 2082254721SemasteError 2083254721SemasteProcess::ClearBreakpointSiteByID (lldb::user_id_t break_id) 2084254721Semaste{ 2085254721Semaste Error error (DisableBreakpointSiteByID (break_id)); 2086254721Semaste 2087254721Semaste if (error.Success()) 2088254721Semaste m_breakpoint_site_list.Remove(break_id); 2089254721Semaste 2090254721Semaste return error; 2091254721Semaste} 2092254721Semaste 2093254721SemasteError 2094254721SemasteProcess::DisableBreakpointSiteByID (lldb::user_id_t break_id) 2095254721Semaste{ 2096254721Semaste Error error; 2097254721Semaste BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 2098254721Semaste if (bp_site_sp) 2099254721Semaste { 2100254721Semaste if (bp_site_sp->IsEnabled()) 2101254721Semaste error = DisableBreakpointSite (bp_site_sp.get()); 2102254721Semaste } 2103254721Semaste else 2104254721Semaste { 2105254721Semaste error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id); 2106254721Semaste } 2107254721Semaste 2108254721Semaste return error; 2109254721Semaste} 2110254721Semaste 2111254721SemasteError 2112254721SemasteProcess::EnableBreakpointSiteByID (lldb::user_id_t break_id) 2113254721Semaste{ 2114254721Semaste Error error; 2115254721Semaste BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 2116254721Semaste if (bp_site_sp) 2117254721Semaste { 2118254721Semaste if (!bp_site_sp->IsEnabled()) 2119254721Semaste error = EnableBreakpointSite (bp_site_sp.get()); 2120254721Semaste } 2121254721Semaste else 2122254721Semaste { 2123254721Semaste error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id); 2124254721Semaste } 2125254721Semaste return error; 2126254721Semaste} 2127254721Semaste 2128254721Semastelldb::break_id_t 2129254721SemasteProcess::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware) 2130254721Semaste{ 2131269024Semaste addr_t load_addr = LLDB_INVALID_ADDRESS; 2132269024Semaste 2133269024Semaste bool show_error = true; 2134269024Semaste switch (GetState()) 2135269024Semaste { 2136269024Semaste case eStateInvalid: 2137269024Semaste case eStateUnloaded: 2138269024Semaste case eStateConnected: 2139269024Semaste case eStateAttaching: 2140269024Semaste case eStateLaunching: 2141269024Semaste case eStateDetached: 2142269024Semaste case eStateExited: 2143269024Semaste show_error = false; 2144269024Semaste break; 2145269024Semaste 2146269024Semaste case eStateStopped: 2147269024Semaste case eStateRunning: 2148269024Semaste case eStateStepping: 2149269024Semaste case eStateCrashed: 2150269024Semaste case eStateSuspended: 2151269024Semaste show_error = IsAlive(); 2152269024Semaste break; 2153269024Semaste } 2154269024Semaste 2155269024Semaste // Reset the IsIndirect flag here, in case the location changes from 2156269024Semaste // pointing to a indirect symbol to a regular symbol. 2157269024Semaste owner->SetIsIndirect (false); 2158269024Semaste 2159269024Semaste if (owner->ShouldResolveIndirectFunctions()) 2160269024Semaste { 2161269024Semaste Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol(); 2162269024Semaste if (symbol && symbol->IsIndirect()) 2163269024Semaste { 2164269024Semaste Error error; 2165269024Semaste load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error); 2166269024Semaste if (!error.Success() && show_error) 2167269024Semaste { 2168269024Semaste m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n", 2169269024Semaste symbol->GetAddress().GetLoadAddress(&m_target), 2170269024Semaste owner->GetBreakpoint().GetID(), 2171269024Semaste owner->GetID(), 2172269024Semaste error.AsCString() ? error.AsCString() : "unkown error"); 2173269024Semaste return LLDB_INVALID_BREAK_ID; 2174269024Semaste } 2175269024Semaste Address resolved_address(load_addr); 2176269024Semaste load_addr = resolved_address.GetOpcodeLoadAddress (&m_target); 2177269024Semaste owner->SetIsIndirect(true); 2178269024Semaste } 2179269024Semaste else 2180269024Semaste load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target); 2181269024Semaste } 2182269024Semaste else 2183269024Semaste load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target); 2184269024Semaste 2185254721Semaste if (load_addr != LLDB_INVALID_ADDRESS) 2186254721Semaste { 2187254721Semaste BreakpointSiteSP bp_site_sp; 2188254721Semaste 2189254721Semaste // Look up this breakpoint site. If it exists, then add this new owner, otherwise 2190254721Semaste // create a new breakpoint site and add it. 2191254721Semaste 2192254721Semaste bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr); 2193254721Semaste 2194254721Semaste if (bp_site_sp) 2195254721Semaste { 2196254721Semaste bp_site_sp->AddOwner (owner); 2197254721Semaste owner->SetBreakpointSite (bp_site_sp); 2198254721Semaste return bp_site_sp->GetID(); 2199254721Semaste } 2200254721Semaste else 2201254721Semaste { 2202254721Semaste bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware)); 2203254721Semaste if (bp_site_sp) 2204254721Semaste { 2205263363Semaste Error error = EnableBreakpointSite (bp_site_sp.get()); 2206263363Semaste if (error.Success()) 2207254721Semaste { 2208254721Semaste owner->SetBreakpointSite (bp_site_sp); 2209254721Semaste return m_breakpoint_site_list.Add (bp_site_sp); 2210254721Semaste } 2211263363Semaste else 2212263363Semaste { 2213263367Semaste if (show_error) 2214263367Semaste { 2215263367Semaste // Report error for setting breakpoint... 2216269024Semaste m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n", 2217269024Semaste load_addr, 2218269024Semaste owner->GetBreakpoint().GetID(), 2219269024Semaste owner->GetID(), 2220269024Semaste error.AsCString() ? error.AsCString() : "unkown error"); 2221263367Semaste } 2222263363Semaste } 2223254721Semaste } 2224254721Semaste } 2225254721Semaste } 2226254721Semaste // We failed to enable the breakpoint 2227254721Semaste return LLDB_INVALID_BREAK_ID; 2228254721Semaste 2229254721Semaste} 2230254721Semaste 2231254721Semastevoid 2232254721SemasteProcess::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp) 2233254721Semaste{ 2234254721Semaste uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id); 2235254721Semaste if (num_owners == 0) 2236254721Semaste { 2237254721Semaste // Don't try to disable the site if we don't have a live process anymore. 2238254721Semaste if (IsAlive()) 2239254721Semaste DisableBreakpointSite (bp_site_sp.get()); 2240254721Semaste m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 2241254721Semaste } 2242254721Semaste} 2243254721Semaste 2244254721Semaste 2245254721Semastesize_t 2246254721SemasteProcess::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const 2247254721Semaste{ 2248254721Semaste size_t bytes_removed = 0; 2249254721Semaste BreakpointSiteList bp_sites_in_range; 2250254721Semaste 2251254721Semaste if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range)) 2252254721Semaste { 2253254721Semaste bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void { 2254254721Semaste if (bp_site->GetType() == BreakpointSite::eSoftware) 2255254721Semaste { 2256254721Semaste addr_t intersect_addr; 2257254721Semaste size_t intersect_size; 2258254721Semaste size_t opcode_offset; 2259254721Semaste if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset)) 2260254721Semaste { 2261254721Semaste assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 2262254721Semaste assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size); 2263254721Semaste assert(opcode_offset + intersect_size <= bp_site->GetByteSize()); 2264254721Semaste size_t buf_offset = intersect_addr - bp_addr; 2265254721Semaste ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size); 2266254721Semaste } 2267254721Semaste } 2268254721Semaste }); 2269254721Semaste } 2270254721Semaste return bytes_removed; 2271254721Semaste} 2272254721Semaste 2273254721Semaste 2274254721Semaste 2275254721Semastesize_t 2276254721SemasteProcess::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) 2277254721Semaste{ 2278254721Semaste PlatformSP platform_sp (m_target.GetPlatform()); 2279254721Semaste if (platform_sp) 2280254721Semaste return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site); 2281254721Semaste return 0; 2282254721Semaste} 2283254721Semaste 2284254721SemasteError 2285254721SemasteProcess::EnableSoftwareBreakpoint (BreakpointSite *bp_site) 2286254721Semaste{ 2287254721Semaste Error error; 2288254721Semaste assert (bp_site != NULL); 2289254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 2290254721Semaste const addr_t bp_addr = bp_site->GetLoadAddress(); 2291254721Semaste if (log) 2292254721Semaste log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr); 2293254721Semaste if (bp_site->IsEnabled()) 2294254721Semaste { 2295254721Semaste if (log) 2296254721Semaste log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr); 2297254721Semaste return error; 2298254721Semaste } 2299254721Semaste 2300254721Semaste if (bp_addr == LLDB_INVALID_ADDRESS) 2301254721Semaste { 2302254721Semaste error.SetErrorString("BreakpointSite contains an invalid load address."); 2303254721Semaste return error; 2304254721Semaste } 2305254721Semaste // Ask the lldb::Process subclass to fill in the correct software breakpoint 2306254721Semaste // trap for the breakpoint site 2307254721Semaste const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 2308254721Semaste 2309254721Semaste if (bp_opcode_size == 0) 2310254721Semaste { 2311254721Semaste error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr); 2312254721Semaste } 2313254721Semaste else 2314254721Semaste { 2315254721Semaste const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 2316254721Semaste 2317254721Semaste if (bp_opcode_bytes == NULL) 2318254721Semaste { 2319254721Semaste error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode."); 2320254721Semaste return error; 2321254721Semaste } 2322254721Semaste 2323254721Semaste // Save the original opcode by reading it 2324254721Semaste if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size) 2325254721Semaste { 2326254721Semaste // Write a software breakpoint in place of the original opcode 2327254721Semaste if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 2328254721Semaste { 2329254721Semaste uint8_t verify_bp_opcode_bytes[64]; 2330254721Semaste if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 2331254721Semaste { 2332254721Semaste if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0) 2333254721Semaste { 2334254721Semaste bp_site->SetEnabled(true); 2335254721Semaste bp_site->SetType (BreakpointSite::eSoftware); 2336254721Semaste if (log) 2337254721Semaste log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", 2338254721Semaste bp_site->GetID(), 2339254721Semaste (uint64_t)bp_addr); 2340254721Semaste } 2341254721Semaste else 2342254721Semaste error.SetErrorString("failed to verify the breakpoint trap in memory."); 2343254721Semaste } 2344254721Semaste else 2345254721Semaste error.SetErrorString("Unable to read memory to verify breakpoint trap."); 2346254721Semaste } 2347254721Semaste else 2348254721Semaste error.SetErrorString("Unable to write breakpoint trap to memory."); 2349254721Semaste } 2350254721Semaste else 2351254721Semaste error.SetErrorString("Unable to read memory at breakpoint address."); 2352254721Semaste } 2353254721Semaste if (log && error.Fail()) 2354254721Semaste log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s", 2355254721Semaste bp_site->GetID(), 2356254721Semaste (uint64_t)bp_addr, 2357254721Semaste error.AsCString()); 2358254721Semaste return error; 2359254721Semaste} 2360254721Semaste 2361254721SemasteError 2362254721SemasteProcess::DisableSoftwareBreakpoint (BreakpointSite *bp_site) 2363254721Semaste{ 2364254721Semaste Error error; 2365254721Semaste assert (bp_site != NULL); 2366254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 2367254721Semaste addr_t bp_addr = bp_site->GetLoadAddress(); 2368254721Semaste lldb::user_id_t breakID = bp_site->GetID(); 2369254721Semaste if (log) 2370254721Semaste log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr); 2371254721Semaste 2372254721Semaste if (bp_site->IsHardware()) 2373254721Semaste { 2374254721Semaste error.SetErrorString("Breakpoint site is a hardware breakpoint."); 2375254721Semaste } 2376254721Semaste else if (bp_site->IsEnabled()) 2377254721Semaste { 2378254721Semaste const size_t break_op_size = bp_site->GetByteSize(); 2379254721Semaste const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes(); 2380254721Semaste if (break_op_size > 0) 2381254721Semaste { 2382254721Semaste // Clear a software breakoint instruction 2383254721Semaste uint8_t curr_break_op[8]; 2384254721Semaste assert (break_op_size <= sizeof(curr_break_op)); 2385254721Semaste bool break_op_found = false; 2386254721Semaste 2387254721Semaste // Read the breakpoint opcode 2388254721Semaste if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size) 2389254721Semaste { 2390254721Semaste bool verify = false; 2391254721Semaste // Make sure we have the a breakpoint opcode exists at this address 2392254721Semaste if (::memcmp (curr_break_op, break_op, break_op_size) == 0) 2393254721Semaste { 2394254721Semaste break_op_found = true; 2395254721Semaste // We found a valid breakpoint opcode at this address, now restore 2396254721Semaste // the saved opcode. 2397254721Semaste if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size) 2398254721Semaste { 2399254721Semaste verify = true; 2400254721Semaste } 2401254721Semaste else 2402254721Semaste error.SetErrorString("Memory write failed when restoring original opcode."); 2403254721Semaste } 2404254721Semaste else 2405254721Semaste { 2406254721Semaste error.SetErrorString("Original breakpoint trap is no longer in memory."); 2407254721Semaste // Set verify to true and so we can check if the original opcode has already been restored 2408254721Semaste verify = true; 2409254721Semaste } 2410254721Semaste 2411254721Semaste if (verify) 2412254721Semaste { 2413254721Semaste uint8_t verify_opcode[8]; 2414254721Semaste assert (break_op_size < sizeof(verify_opcode)); 2415254721Semaste // Verify that our original opcode made it back to the inferior 2416254721Semaste if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size) 2417254721Semaste { 2418254721Semaste // compare the memory we just read with the original opcode 2419254721Semaste if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0) 2420254721Semaste { 2421254721Semaste // SUCCESS 2422254721Semaste bp_site->SetEnabled(false); 2423254721Semaste if (log) 2424254721Semaste log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr); 2425254721Semaste return error; 2426254721Semaste } 2427254721Semaste else 2428254721Semaste { 2429254721Semaste if (break_op_found) 2430254721Semaste error.SetErrorString("Failed to restore original opcode."); 2431254721Semaste } 2432254721Semaste } 2433254721Semaste else 2434254721Semaste error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored."); 2435254721Semaste } 2436254721Semaste } 2437254721Semaste else 2438254721Semaste error.SetErrorString("Unable to read memory that should contain the breakpoint trap."); 2439254721Semaste } 2440254721Semaste } 2441254721Semaste else 2442254721Semaste { 2443254721Semaste if (log) 2444254721Semaste log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr); 2445254721Semaste return error; 2446254721Semaste } 2447254721Semaste 2448254721Semaste if (log) 2449254721Semaste log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s", 2450254721Semaste bp_site->GetID(), 2451254721Semaste (uint64_t)bp_addr, 2452254721Semaste error.AsCString()); 2453254721Semaste return error; 2454254721Semaste 2455254721Semaste} 2456254721Semaste 2457254721Semaste// Uncomment to verify memory caching works after making changes to caching code 2458254721Semaste//#define VERIFY_MEMORY_READS 2459254721Semaste 2460254721Semastesize_t 2461254721SemasteProcess::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2462254721Semaste{ 2463263367Semaste error.Clear(); 2464254721Semaste if (!GetDisableMemoryCache()) 2465254721Semaste { 2466254721Semaste#if defined (VERIFY_MEMORY_READS) 2467254721Semaste // Memory caching is enabled, with debug verification 2468254721Semaste 2469254721Semaste if (buf && size) 2470254721Semaste { 2471254721Semaste // Uncomment the line below to make sure memory caching is working. 2472254721Semaste // I ran this through the test suite and got no assertions, so I am 2473254721Semaste // pretty confident this is working well. If any changes are made to 2474254721Semaste // memory caching, uncomment the line below and test your changes! 2475254721Semaste 2476254721Semaste // Verify all memory reads by using the cache first, then redundantly 2477254721Semaste // reading the same memory from the inferior and comparing to make sure 2478254721Semaste // everything is exactly the same. 2479254721Semaste std::string verify_buf (size, '\0'); 2480254721Semaste assert (verify_buf.size() == size); 2481254721Semaste const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error); 2482254721Semaste Error verify_error; 2483254721Semaste const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); 2484254721Semaste assert (cache_bytes_read == verify_bytes_read); 2485254721Semaste assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 2486254721Semaste assert (verify_error.Success() == error.Success()); 2487254721Semaste return cache_bytes_read; 2488254721Semaste } 2489254721Semaste return 0; 2490254721Semaste#else // !defined(VERIFY_MEMORY_READS) 2491254721Semaste // Memory caching is enabled, without debug verification 2492254721Semaste 2493254721Semaste return m_memory_cache.Read (addr, buf, size, error); 2494254721Semaste#endif // defined (VERIFY_MEMORY_READS) 2495254721Semaste } 2496254721Semaste else 2497254721Semaste { 2498254721Semaste // Memory caching is disabled 2499254721Semaste 2500254721Semaste return ReadMemoryFromInferior (addr, buf, size, error); 2501254721Semaste } 2502254721Semaste} 2503254721Semaste 2504254721Semastesize_t 2505254721SemasteProcess::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error) 2506254721Semaste{ 2507254721Semaste char buf[256]; 2508254721Semaste out_str.clear(); 2509254721Semaste addr_t curr_addr = addr; 2510254721Semaste while (1) 2511254721Semaste { 2512254721Semaste size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error); 2513254721Semaste if (length == 0) 2514254721Semaste break; 2515254721Semaste out_str.append(buf, length); 2516254721Semaste // If we got "length - 1" bytes, we didn't get the whole C string, we 2517254721Semaste // need to read some more characters 2518254721Semaste if (length == sizeof(buf) - 1) 2519254721Semaste curr_addr += length; 2520254721Semaste else 2521254721Semaste break; 2522254721Semaste } 2523254721Semaste return out_str.size(); 2524254721Semaste} 2525254721Semaste 2526254721Semaste 2527254721Semastesize_t 2528254721SemasteProcess::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error, 2529254721Semaste size_t type_width) 2530254721Semaste{ 2531254721Semaste size_t total_bytes_read = 0; 2532254721Semaste if (dst && max_bytes && type_width && max_bytes >= type_width) 2533254721Semaste { 2534254721Semaste // Ensure a null terminator independent of the number of bytes that is read. 2535254721Semaste memset (dst, 0, max_bytes); 2536254721Semaste size_t bytes_left = max_bytes - type_width; 2537254721Semaste 2538254721Semaste const char terminator[4] = {'\0', '\0', '\0', '\0'}; 2539254721Semaste assert(sizeof(terminator) >= type_width && 2540254721Semaste "Attempting to validate a string with more than 4 bytes per character!"); 2541254721Semaste 2542254721Semaste addr_t curr_addr = addr; 2543254721Semaste const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2544254721Semaste char *curr_dst = dst; 2545254721Semaste 2546254721Semaste error.Clear(); 2547254721Semaste while (bytes_left > 0 && error.Success()) 2548254721Semaste { 2549254721Semaste addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size); 2550254721Semaste addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 2551254721Semaste size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error); 2552254721Semaste 2553254721Semaste if (bytes_read == 0) 2554254721Semaste break; 2555254721Semaste 2556254721Semaste // Search for a null terminator of correct size and alignment in bytes_read 2557254721Semaste size_t aligned_start = total_bytes_read - total_bytes_read % type_width; 2558254721Semaste for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width) 2559254721Semaste if (::strncmp(&dst[i], terminator, type_width) == 0) 2560254721Semaste { 2561254721Semaste error.Clear(); 2562254721Semaste return i; 2563254721Semaste } 2564254721Semaste 2565254721Semaste total_bytes_read += bytes_read; 2566254721Semaste curr_dst += bytes_read; 2567254721Semaste curr_addr += bytes_read; 2568254721Semaste bytes_left -= bytes_read; 2569254721Semaste } 2570254721Semaste } 2571254721Semaste else 2572254721Semaste { 2573254721Semaste if (max_bytes) 2574254721Semaste error.SetErrorString("invalid arguments"); 2575254721Semaste } 2576254721Semaste return total_bytes_read; 2577254721Semaste} 2578254721Semaste 2579254721Semaste// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find 2580254721Semaste// null terminators. 2581254721Semastesize_t 2582254721SemasteProcess::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error) 2583254721Semaste{ 2584254721Semaste size_t total_cstr_len = 0; 2585254721Semaste if (dst && dst_max_len) 2586254721Semaste { 2587254721Semaste result_error.Clear(); 2588254721Semaste // NULL out everything just to be safe 2589254721Semaste memset (dst, 0, dst_max_len); 2590254721Semaste Error error; 2591254721Semaste addr_t curr_addr = addr; 2592254721Semaste const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2593254721Semaste size_t bytes_left = dst_max_len - 1; 2594254721Semaste char *curr_dst = dst; 2595254721Semaste 2596254721Semaste while (bytes_left > 0) 2597254721Semaste { 2598254721Semaste addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size); 2599254721Semaste addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 2600254721Semaste size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error); 2601254721Semaste 2602254721Semaste if (bytes_read == 0) 2603254721Semaste { 2604254721Semaste result_error = error; 2605254721Semaste dst[total_cstr_len] = '\0'; 2606254721Semaste break; 2607254721Semaste } 2608254721Semaste const size_t len = strlen(curr_dst); 2609254721Semaste 2610254721Semaste total_cstr_len += len; 2611254721Semaste 2612254721Semaste if (len < bytes_to_read) 2613254721Semaste break; 2614254721Semaste 2615254721Semaste curr_dst += bytes_read; 2616254721Semaste curr_addr += bytes_read; 2617254721Semaste bytes_left -= bytes_read; 2618254721Semaste } 2619254721Semaste } 2620254721Semaste else 2621254721Semaste { 2622254721Semaste if (dst == NULL) 2623254721Semaste result_error.SetErrorString("invalid arguments"); 2624254721Semaste else 2625254721Semaste result_error.Clear(); 2626254721Semaste } 2627254721Semaste return total_cstr_len; 2628254721Semaste} 2629254721Semaste 2630254721Semastesize_t 2631254721SemasteProcess::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error) 2632254721Semaste{ 2633254721Semaste if (buf == NULL || size == 0) 2634254721Semaste return 0; 2635254721Semaste 2636254721Semaste size_t bytes_read = 0; 2637254721Semaste uint8_t *bytes = (uint8_t *)buf; 2638254721Semaste 2639254721Semaste while (bytes_read < size) 2640254721Semaste { 2641254721Semaste const size_t curr_size = size - bytes_read; 2642254721Semaste const size_t curr_bytes_read = DoReadMemory (addr + bytes_read, 2643254721Semaste bytes + bytes_read, 2644254721Semaste curr_size, 2645254721Semaste error); 2646254721Semaste bytes_read += curr_bytes_read; 2647254721Semaste if (curr_bytes_read == curr_size || curr_bytes_read == 0) 2648254721Semaste break; 2649254721Semaste } 2650254721Semaste 2651254721Semaste // Replace any software breakpoint opcodes that fall into this range back 2652254721Semaste // into "buf" before we return 2653254721Semaste if (bytes_read > 0) 2654254721Semaste RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf); 2655254721Semaste return bytes_read; 2656254721Semaste} 2657254721Semaste 2658254721Semasteuint64_t 2659254721SemasteProcess::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error) 2660254721Semaste{ 2661254721Semaste Scalar scalar; 2662254721Semaste if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error)) 2663254721Semaste return scalar.ULongLong(fail_value); 2664254721Semaste return fail_value; 2665254721Semaste} 2666254721Semaste 2667254721Semasteaddr_t 2668254721SemasteProcess::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error) 2669254721Semaste{ 2670254721Semaste Scalar scalar; 2671254721Semaste if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error)) 2672254721Semaste return scalar.ULongLong(LLDB_INVALID_ADDRESS); 2673254721Semaste return LLDB_INVALID_ADDRESS; 2674254721Semaste} 2675254721Semaste 2676254721Semaste 2677254721Semastebool 2678254721SemasteProcess::WritePointerToMemory (lldb::addr_t vm_addr, 2679254721Semaste lldb::addr_t ptr_value, 2680254721Semaste Error &error) 2681254721Semaste{ 2682254721Semaste Scalar scalar; 2683254721Semaste const uint32_t addr_byte_size = GetAddressByteSize(); 2684254721Semaste if (addr_byte_size <= 4) 2685254721Semaste scalar = (uint32_t)ptr_value; 2686254721Semaste else 2687254721Semaste scalar = ptr_value; 2688254721Semaste return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size; 2689254721Semaste} 2690254721Semaste 2691254721Semastesize_t 2692254721SemasteProcess::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error) 2693254721Semaste{ 2694254721Semaste size_t bytes_written = 0; 2695254721Semaste const uint8_t *bytes = (const uint8_t *)buf; 2696254721Semaste 2697254721Semaste while (bytes_written < size) 2698254721Semaste { 2699254721Semaste const size_t curr_size = size - bytes_written; 2700254721Semaste const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written, 2701254721Semaste bytes + bytes_written, 2702254721Semaste curr_size, 2703254721Semaste error); 2704254721Semaste bytes_written += curr_bytes_written; 2705254721Semaste if (curr_bytes_written == curr_size || curr_bytes_written == 0) 2706254721Semaste break; 2707254721Semaste } 2708254721Semaste return bytes_written; 2709254721Semaste} 2710254721Semaste 2711254721Semastesize_t 2712254721SemasteProcess::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2713254721Semaste{ 2714254721Semaste#if defined (ENABLE_MEMORY_CACHING) 2715254721Semaste m_memory_cache.Flush (addr, size); 2716254721Semaste#endif 2717254721Semaste 2718254721Semaste if (buf == NULL || size == 0) 2719254721Semaste return 0; 2720254721Semaste 2721254721Semaste m_mod_id.BumpMemoryID(); 2722254721Semaste 2723254721Semaste // We need to write any data that would go where any current software traps 2724254721Semaste // (enabled software breakpoints) any software traps (breakpoints) that we 2725254721Semaste // may have placed in our tasks memory. 2726254721Semaste 2727254721Semaste BreakpointSiteList bp_sites_in_range; 2728254721Semaste 2729254721Semaste if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range)) 2730254721Semaste { 2731254721Semaste // No breakpoint sites overlap 2732254721Semaste if (bp_sites_in_range.IsEmpty()) 2733254721Semaste return WriteMemoryPrivate (addr, buf, size, error); 2734254721Semaste else 2735254721Semaste { 2736254721Semaste const uint8_t *ubuf = (const uint8_t *)buf; 2737254721Semaste uint64_t bytes_written = 0; 2738254721Semaste 2739254721Semaste bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void { 2740254721Semaste 2741254721Semaste if (error.Success()) 2742254721Semaste { 2743254721Semaste addr_t intersect_addr; 2744254721Semaste size_t intersect_size; 2745254721Semaste size_t opcode_offset; 2746254721Semaste const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset); 2747254721Semaste assert(intersects); 2748254721Semaste assert(addr <= intersect_addr && intersect_addr < addr + size); 2749254721Semaste assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); 2750254721Semaste assert(opcode_offset + intersect_size <= bp->GetByteSize()); 2751254721Semaste 2752254721Semaste // Check for bytes before this breakpoint 2753254721Semaste const addr_t curr_addr = addr + bytes_written; 2754254721Semaste if (intersect_addr > curr_addr) 2755254721Semaste { 2756254721Semaste // There are some bytes before this breakpoint that we need to 2757254721Semaste // just write to memory 2758254721Semaste size_t curr_size = intersect_addr - curr_addr; 2759254721Semaste size_t curr_bytes_written = WriteMemoryPrivate (curr_addr, 2760254721Semaste ubuf + bytes_written, 2761254721Semaste curr_size, 2762254721Semaste error); 2763254721Semaste bytes_written += curr_bytes_written; 2764254721Semaste if (curr_bytes_written != curr_size) 2765254721Semaste { 2766254721Semaste // We weren't able to write all of the requested bytes, we 2767254721Semaste // are done looping and will return the number of bytes that 2768254721Semaste // we have written so far. 2769254721Semaste if (error.Success()) 2770254721Semaste error.SetErrorToGenericError(); 2771254721Semaste } 2772254721Semaste } 2773254721Semaste // Now write any bytes that would cover up any software breakpoints 2774254721Semaste // directly into the breakpoint opcode buffer 2775254721Semaste ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); 2776254721Semaste bytes_written += intersect_size; 2777254721Semaste } 2778254721Semaste }); 2779254721Semaste 2780254721Semaste if (bytes_written < size) 2781254721Semaste bytes_written += WriteMemoryPrivate (addr + bytes_written, 2782254721Semaste ubuf + bytes_written, 2783254721Semaste size - bytes_written, 2784254721Semaste error); 2785254721Semaste } 2786254721Semaste } 2787254721Semaste else 2788254721Semaste { 2789254721Semaste return WriteMemoryPrivate (addr, buf, size, error); 2790254721Semaste } 2791254721Semaste 2792254721Semaste // Write any remaining bytes after the last breakpoint if we have any left 2793254721Semaste return 0; //bytes_written; 2794254721Semaste} 2795254721Semaste 2796254721Semastesize_t 2797254721SemasteProcess::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error) 2798254721Semaste{ 2799254721Semaste if (byte_size == UINT32_MAX) 2800254721Semaste byte_size = scalar.GetByteSize(); 2801254721Semaste if (byte_size > 0) 2802254721Semaste { 2803254721Semaste uint8_t buf[32]; 2804254721Semaste const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error); 2805254721Semaste if (mem_size > 0) 2806254721Semaste return WriteMemory(addr, buf, mem_size, error); 2807254721Semaste else 2808254721Semaste error.SetErrorString ("failed to get scalar as memory data"); 2809254721Semaste } 2810254721Semaste else 2811254721Semaste { 2812254721Semaste error.SetErrorString ("invalid scalar value"); 2813254721Semaste } 2814254721Semaste return 0; 2815254721Semaste} 2816254721Semaste 2817254721Semastesize_t 2818254721SemasteProcess::ReadScalarIntegerFromMemory (addr_t addr, 2819254721Semaste uint32_t byte_size, 2820254721Semaste bool is_signed, 2821254721Semaste Scalar &scalar, 2822254721Semaste Error &error) 2823254721Semaste{ 2824254721Semaste uint64_t uval = 0; 2825254721Semaste if (byte_size == 0) 2826254721Semaste { 2827254721Semaste error.SetErrorString ("byte size is zero"); 2828254721Semaste } 2829254721Semaste else if (byte_size & (byte_size - 1)) 2830254721Semaste { 2831254721Semaste error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size); 2832254721Semaste } 2833254721Semaste else if (byte_size <= sizeof(uval)) 2834254721Semaste { 2835254721Semaste const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error); 2836254721Semaste if (bytes_read == byte_size) 2837254721Semaste { 2838254721Semaste DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize()); 2839254721Semaste lldb::offset_t offset = 0; 2840254721Semaste if (byte_size <= 4) 2841254721Semaste scalar = data.GetMaxU32 (&offset, byte_size); 2842254721Semaste else 2843254721Semaste scalar = data.GetMaxU64 (&offset, byte_size); 2844254721Semaste if (is_signed) 2845254721Semaste scalar.SignExtend(byte_size * 8); 2846254721Semaste return bytes_read; 2847254721Semaste } 2848254721Semaste } 2849254721Semaste else 2850254721Semaste { 2851254721Semaste error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size); 2852254721Semaste } 2853254721Semaste return 0; 2854254721Semaste} 2855254721Semaste 2856254721Semaste#define USE_ALLOCATE_MEMORY_CACHE 1 2857254721Semasteaddr_t 2858254721SemasteProcess::AllocateMemory(size_t size, uint32_t permissions, Error &error) 2859254721Semaste{ 2860254721Semaste if (GetPrivateState() != eStateStopped) 2861254721Semaste return LLDB_INVALID_ADDRESS; 2862254721Semaste 2863254721Semaste#if defined (USE_ALLOCATE_MEMORY_CACHE) 2864254721Semaste return m_allocated_memory_cache.AllocateMemory(size, permissions, error); 2865254721Semaste#else 2866254721Semaste addr_t allocated_addr = DoAllocateMemory (size, permissions, error); 2867254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2868254721Semaste if (log) 2869263363Semaste log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)", 2870263363Semaste (uint64_t)size, 2871254721Semaste GetPermissionsAsCString (permissions), 2872254721Semaste (uint64_t)allocated_addr, 2873254721Semaste m_mod_id.GetStopID(), 2874254721Semaste m_mod_id.GetMemoryID()); 2875254721Semaste return allocated_addr; 2876254721Semaste#endif 2877254721Semaste} 2878254721Semaste 2879254721Semastebool 2880254721SemasteProcess::CanJIT () 2881254721Semaste{ 2882254721Semaste if (m_can_jit == eCanJITDontKnow) 2883254721Semaste { 2884254721Semaste Error err; 2885254721Semaste 2886254721Semaste uint64_t allocated_memory = AllocateMemory(8, 2887254721Semaste ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, 2888254721Semaste err); 2889254721Semaste 2890254721Semaste if (err.Success()) 2891254721Semaste m_can_jit = eCanJITYes; 2892254721Semaste else 2893254721Semaste m_can_jit = eCanJITNo; 2894254721Semaste 2895254721Semaste DeallocateMemory (allocated_memory); 2896254721Semaste } 2897254721Semaste 2898254721Semaste return m_can_jit == eCanJITYes; 2899254721Semaste} 2900254721Semaste 2901254721Semastevoid 2902254721SemasteProcess::SetCanJIT (bool can_jit) 2903254721Semaste{ 2904254721Semaste m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); 2905254721Semaste} 2906254721Semaste 2907254721SemasteError 2908254721SemasteProcess::DeallocateMemory (addr_t ptr) 2909254721Semaste{ 2910254721Semaste Error error; 2911254721Semaste#if defined (USE_ALLOCATE_MEMORY_CACHE) 2912254721Semaste if (!m_allocated_memory_cache.DeallocateMemory(ptr)) 2913254721Semaste { 2914254721Semaste error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr); 2915254721Semaste } 2916254721Semaste#else 2917254721Semaste error = DoDeallocateMemory (ptr); 2918254721Semaste 2919254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2920254721Semaste if (log) 2921254721Semaste log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)", 2922254721Semaste ptr, 2923254721Semaste error.AsCString("SUCCESS"), 2924254721Semaste m_mod_id.GetStopID(), 2925254721Semaste m_mod_id.GetMemoryID()); 2926254721Semaste#endif 2927254721Semaste return error; 2928254721Semaste} 2929254721Semaste 2930254721Semaste 2931254721SemasteModuleSP 2932254721SemasteProcess::ReadModuleFromMemory (const FileSpec& file_spec, 2933254721Semaste lldb::addr_t header_addr) 2934254721Semaste{ 2935254721Semaste ModuleSP module_sp (new Module (file_spec, ArchSpec())); 2936254721Semaste if (module_sp) 2937254721Semaste { 2938254721Semaste Error error; 2939254721Semaste ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error); 2940254721Semaste if (objfile) 2941254721Semaste return module_sp; 2942254721Semaste } 2943254721Semaste return ModuleSP(); 2944254721Semaste} 2945254721Semaste 2946254721SemasteError 2947254721SemasteProcess::EnableWatchpoint (Watchpoint *watchpoint, bool notify) 2948254721Semaste{ 2949254721Semaste Error error; 2950254721Semaste error.SetErrorString("watchpoints are not supported"); 2951254721Semaste return error; 2952254721Semaste} 2953254721Semaste 2954254721SemasteError 2955254721SemasteProcess::DisableWatchpoint (Watchpoint *watchpoint, bool notify) 2956254721Semaste{ 2957254721Semaste Error error; 2958254721Semaste error.SetErrorString("watchpoints are not supported"); 2959254721Semaste return error; 2960254721Semaste} 2961254721Semaste 2962254721SemasteStateType 2963254721SemasteProcess::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp) 2964254721Semaste{ 2965254721Semaste StateType state; 2966254721Semaste // Now wait for the process to launch and return control to us, and then 2967254721Semaste // call DidLaunch: 2968254721Semaste while (1) 2969254721Semaste { 2970254721Semaste event_sp.reset(); 2971254721Semaste state = WaitForStateChangedEventsPrivate (timeout, event_sp); 2972254721Semaste 2973254721Semaste if (StateIsStoppedState(state, false)) 2974254721Semaste break; 2975254721Semaste 2976254721Semaste // If state is invalid, then we timed out 2977254721Semaste if (state == eStateInvalid) 2978254721Semaste break; 2979254721Semaste 2980254721Semaste if (event_sp) 2981254721Semaste HandlePrivateEvent (event_sp); 2982254721Semaste } 2983254721Semaste return state; 2984254721Semaste} 2985254721Semaste 2986254721SemasteError 2987263367SemasteProcess::Launch (ProcessLaunchInfo &launch_info) 2988254721Semaste{ 2989254721Semaste Error error; 2990254721Semaste m_abi_sp.reset(); 2991254721Semaste m_dyld_ap.reset(); 2992263363Semaste m_system_runtime_ap.reset(); 2993254721Semaste m_os_ap.reset(); 2994254721Semaste m_process_input_reader.reset(); 2995254721Semaste 2996254721Semaste Module *exe_module = m_target.GetExecutableModulePointer(); 2997254721Semaste if (exe_module) 2998254721Semaste { 2999254721Semaste char local_exec_file_path[PATH_MAX]; 3000254721Semaste char platform_exec_file_path[PATH_MAX]; 3001254721Semaste exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path)); 3002254721Semaste exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path)); 3003254721Semaste if (exe_module->GetFileSpec().Exists()) 3004254721Semaste { 3005263367Semaste // Install anything that might need to be installed prior to launching. 3006263367Semaste // For host systems, this will do nothing, but if we are connected to a 3007263367Semaste // remote platform it will install any needed binaries 3008263367Semaste error = GetTarget().Install(&launch_info); 3009263367Semaste if (error.Fail()) 3010263367Semaste return error; 3011263367Semaste 3012254721Semaste if (PrivateStateThreadIsValid ()) 3013254721Semaste PausePrivateStateThread (); 3014254721Semaste 3015254721Semaste error = WillLaunch (exe_module); 3016254721Semaste if (error.Success()) 3017254721Semaste { 3018254721Semaste const bool restarted = false; 3019254721Semaste SetPublicState (eStateLaunching, restarted); 3020254721Semaste m_should_detach = false; 3021254721Semaste 3022254721Semaste if (m_public_run_lock.TrySetRunning()) 3023254721Semaste { 3024254721Semaste // Now launch using these arguments. 3025254721Semaste error = DoLaunch (exe_module, launch_info); 3026254721Semaste } 3027254721Semaste else 3028254721Semaste { 3029254721Semaste // This shouldn't happen 3030254721Semaste error.SetErrorString("failed to acquire process run lock"); 3031254721Semaste } 3032254721Semaste 3033254721Semaste if (error.Fail()) 3034254721Semaste { 3035254721Semaste if (GetID() != LLDB_INVALID_PROCESS_ID) 3036254721Semaste { 3037254721Semaste SetID (LLDB_INVALID_PROCESS_ID); 3038254721Semaste const char *error_string = error.AsCString(); 3039254721Semaste if (error_string == NULL) 3040254721Semaste error_string = "launch failed"; 3041254721Semaste SetExitStatus (-1, error_string); 3042254721Semaste } 3043254721Semaste } 3044254721Semaste else 3045254721Semaste { 3046254721Semaste EventSP event_sp; 3047254721Semaste TimeValue timeout_time; 3048254721Semaste timeout_time = TimeValue::Now(); 3049254721Semaste timeout_time.OffsetWithSeconds(10); 3050254721Semaste StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp); 3051254721Semaste 3052254721Semaste if (state == eStateInvalid || event_sp.get() == NULL) 3053254721Semaste { 3054254721Semaste // We were able to launch the process, but we failed to 3055254721Semaste // catch the initial stop. 3056254721Semaste SetExitStatus (0, "failed to catch stop after launch"); 3057254721Semaste Destroy(); 3058254721Semaste } 3059254721Semaste else if (state == eStateStopped || state == eStateCrashed) 3060254721Semaste { 3061254721Semaste 3062254721Semaste DidLaunch (); 3063254721Semaste 3064254721Semaste DynamicLoader *dyld = GetDynamicLoader (); 3065254721Semaste if (dyld) 3066254721Semaste dyld->DidLaunch(); 3067254721Semaste 3068263363Semaste SystemRuntime *system_runtime = GetSystemRuntime (); 3069263363Semaste if (system_runtime) 3070263363Semaste system_runtime->DidLaunch(); 3071263363Semaste 3072254721Semaste m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 3073254721Semaste // This delays passing the stopped event to listeners till DidLaunch gets 3074254721Semaste // a chance to complete... 3075254721Semaste HandlePrivateEvent (event_sp); 3076254721Semaste 3077254721Semaste if (PrivateStateThreadIsValid ()) 3078254721Semaste ResumePrivateStateThread (); 3079254721Semaste else 3080254721Semaste StartPrivateStateThread (); 3081254721Semaste } 3082254721Semaste else if (state == eStateExited) 3083254721Semaste { 3084254721Semaste // We exited while trying to launch somehow. Don't call DidLaunch as that's 3085254721Semaste // not likely to work, and return an invalid pid. 3086254721Semaste HandlePrivateEvent (event_sp); 3087254721Semaste } 3088254721Semaste } 3089254721Semaste } 3090254721Semaste } 3091254721Semaste else 3092254721Semaste { 3093254721Semaste error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path); 3094254721Semaste } 3095254721Semaste } 3096254721Semaste return error; 3097254721Semaste} 3098254721Semaste 3099254721Semaste 3100254721SemasteError 3101254721SemasteProcess::LoadCore () 3102254721Semaste{ 3103254721Semaste Error error = DoLoadCore(); 3104254721Semaste if (error.Success()) 3105254721Semaste { 3106254721Semaste if (PrivateStateThreadIsValid ()) 3107254721Semaste ResumePrivateStateThread (); 3108254721Semaste else 3109254721Semaste StartPrivateStateThread (); 3110254721Semaste 3111254721Semaste DynamicLoader *dyld = GetDynamicLoader (); 3112254721Semaste if (dyld) 3113254721Semaste dyld->DidAttach(); 3114254721Semaste 3115263363Semaste SystemRuntime *system_runtime = GetSystemRuntime (); 3116263363Semaste if (system_runtime) 3117263363Semaste system_runtime->DidAttach(); 3118263363Semaste 3119254721Semaste m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 3120254721Semaste // We successfully loaded a core file, now pretend we stopped so we can 3121254721Semaste // show all of the threads in the core file and explore the crashed 3122254721Semaste // state. 3123254721Semaste SetPrivateState (eStateStopped); 3124254721Semaste 3125254721Semaste } 3126254721Semaste return error; 3127254721Semaste} 3128254721Semaste 3129254721SemasteDynamicLoader * 3130254721SemasteProcess::GetDynamicLoader () 3131254721Semaste{ 3132254721Semaste if (m_dyld_ap.get() == NULL) 3133254721Semaste m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 3134254721Semaste return m_dyld_ap.get(); 3135254721Semaste} 3136254721Semaste 3137263363SemasteSystemRuntime * 3138263363SemasteProcess::GetSystemRuntime () 3139263363Semaste{ 3140263363Semaste if (m_system_runtime_ap.get() == NULL) 3141263363Semaste m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this)); 3142263363Semaste return m_system_runtime_ap.get(); 3143263363Semaste} 3144254721Semaste 3145263363Semaste 3146254721SemasteProcess::NextEventAction::EventActionResult 3147254721SemasteProcess::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp) 3148254721Semaste{ 3149254721Semaste StateType state = ProcessEventData::GetStateFromEvent (event_sp.get()); 3150254721Semaste switch (state) 3151254721Semaste { 3152254721Semaste case eStateRunning: 3153254721Semaste case eStateConnected: 3154254721Semaste return eEventActionRetry; 3155254721Semaste 3156254721Semaste case eStateStopped: 3157254721Semaste case eStateCrashed: 3158254721Semaste { 3159254721Semaste // During attach, prior to sending the eStateStopped event, 3160254721Semaste // lldb_private::Process subclasses must set the new process ID. 3161254721Semaste assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID); 3162254721Semaste // We don't want these events to be reported, so go set the ShouldReportStop here: 3163254721Semaste m_process->GetThreadList().SetShouldReportStop (eVoteNo); 3164254721Semaste 3165254721Semaste if (m_exec_count > 0) 3166254721Semaste { 3167254721Semaste --m_exec_count; 3168254721Semaste RequestResume(); 3169254721Semaste return eEventActionRetry; 3170254721Semaste } 3171254721Semaste else 3172254721Semaste { 3173254721Semaste m_process->CompleteAttach (); 3174254721Semaste return eEventActionSuccess; 3175254721Semaste } 3176254721Semaste } 3177254721Semaste break; 3178254721Semaste 3179254721Semaste default: 3180254721Semaste case eStateExited: 3181254721Semaste case eStateInvalid: 3182254721Semaste break; 3183254721Semaste } 3184254721Semaste 3185254721Semaste m_exit_string.assign ("No valid Process"); 3186254721Semaste return eEventActionExit; 3187254721Semaste} 3188254721Semaste 3189254721SemasteProcess::NextEventAction::EventActionResult 3190254721SemasteProcess::AttachCompletionHandler::HandleBeingInterrupted() 3191254721Semaste{ 3192254721Semaste return eEventActionSuccess; 3193254721Semaste} 3194254721Semaste 3195254721Semasteconst char * 3196254721SemasteProcess::AttachCompletionHandler::GetExitString () 3197254721Semaste{ 3198254721Semaste return m_exit_string.c_str(); 3199254721Semaste} 3200254721Semaste 3201254721SemasteError 3202254721SemasteProcess::Attach (ProcessAttachInfo &attach_info) 3203254721Semaste{ 3204254721Semaste m_abi_sp.reset(); 3205254721Semaste m_process_input_reader.reset(); 3206254721Semaste m_dyld_ap.reset(); 3207263363Semaste m_system_runtime_ap.reset(); 3208254721Semaste m_os_ap.reset(); 3209254721Semaste 3210254721Semaste lldb::pid_t attach_pid = attach_info.GetProcessID(); 3211254721Semaste Error error; 3212254721Semaste if (attach_pid == LLDB_INVALID_PROCESS_ID) 3213254721Semaste { 3214254721Semaste char process_name[PATH_MAX]; 3215254721Semaste 3216254721Semaste if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name))) 3217254721Semaste { 3218254721Semaste const bool wait_for_launch = attach_info.GetWaitForLaunch(); 3219254721Semaste 3220254721Semaste if (wait_for_launch) 3221254721Semaste { 3222254721Semaste error = WillAttachToProcessWithName(process_name, wait_for_launch); 3223254721Semaste if (error.Success()) 3224254721Semaste { 3225254721Semaste if (m_public_run_lock.TrySetRunning()) 3226254721Semaste { 3227254721Semaste m_should_detach = true; 3228254721Semaste const bool restarted = false; 3229254721Semaste SetPublicState (eStateAttaching, restarted); 3230254721Semaste // Now attach using these arguments. 3231269024Semaste error = DoAttachToProcessWithName (process_name, attach_info); 3232254721Semaste } 3233254721Semaste else 3234254721Semaste { 3235254721Semaste // This shouldn't happen 3236254721Semaste error.SetErrorString("failed to acquire process run lock"); 3237254721Semaste } 3238254721Semaste 3239254721Semaste if (error.Fail()) 3240254721Semaste { 3241254721Semaste if (GetID() != LLDB_INVALID_PROCESS_ID) 3242254721Semaste { 3243254721Semaste SetID (LLDB_INVALID_PROCESS_ID); 3244254721Semaste if (error.AsCString() == NULL) 3245254721Semaste error.SetErrorString("attach failed"); 3246254721Semaste 3247254721Semaste SetExitStatus(-1, error.AsCString()); 3248254721Semaste } 3249254721Semaste } 3250254721Semaste else 3251254721Semaste { 3252254721Semaste SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 3253254721Semaste StartPrivateStateThread(); 3254254721Semaste } 3255254721Semaste return error; 3256254721Semaste } 3257254721Semaste } 3258254721Semaste else 3259254721Semaste { 3260254721Semaste ProcessInstanceInfoList process_infos; 3261254721Semaste PlatformSP platform_sp (m_target.GetPlatform ()); 3262254721Semaste 3263254721Semaste if (platform_sp) 3264254721Semaste { 3265254721Semaste ProcessInstanceInfoMatch match_info; 3266254721Semaste match_info.GetProcessInfo() = attach_info; 3267254721Semaste match_info.SetNameMatchType (eNameMatchEquals); 3268254721Semaste platform_sp->FindProcesses (match_info, process_infos); 3269254721Semaste const uint32_t num_matches = process_infos.GetSize(); 3270254721Semaste if (num_matches == 1) 3271254721Semaste { 3272254721Semaste attach_pid = process_infos.GetProcessIDAtIndex(0); 3273254721Semaste // Fall through and attach using the above process ID 3274254721Semaste } 3275254721Semaste else 3276254721Semaste { 3277254721Semaste match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name)); 3278254721Semaste if (num_matches > 1) 3279254721Semaste error.SetErrorStringWithFormat ("more than one process named %s", process_name); 3280254721Semaste else 3281254721Semaste error.SetErrorStringWithFormat ("could not find a process named %s", process_name); 3282254721Semaste } 3283254721Semaste } 3284254721Semaste else 3285254721Semaste { 3286254721Semaste error.SetErrorString ("invalid platform, can't find processes by name"); 3287254721Semaste return error; 3288254721Semaste } 3289254721Semaste } 3290254721Semaste } 3291254721Semaste else 3292254721Semaste { 3293254721Semaste error.SetErrorString ("invalid process name"); 3294254721Semaste } 3295254721Semaste } 3296254721Semaste 3297254721Semaste if (attach_pid != LLDB_INVALID_PROCESS_ID) 3298254721Semaste { 3299254721Semaste error = WillAttachToProcessWithID(attach_pid); 3300254721Semaste if (error.Success()) 3301254721Semaste { 3302254721Semaste 3303254721Semaste if (m_public_run_lock.TrySetRunning()) 3304254721Semaste { 3305254721Semaste // Now attach using these arguments. 3306254721Semaste m_should_detach = true; 3307254721Semaste const bool restarted = false; 3308254721Semaste SetPublicState (eStateAttaching, restarted); 3309254721Semaste error = DoAttachToProcessWithID (attach_pid, attach_info); 3310254721Semaste } 3311254721Semaste else 3312254721Semaste { 3313254721Semaste // This shouldn't happen 3314254721Semaste error.SetErrorString("failed to acquire process run lock"); 3315254721Semaste } 3316254721Semaste 3317254721Semaste if (error.Success()) 3318254721Semaste { 3319254721Semaste 3320254721Semaste SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 3321254721Semaste StartPrivateStateThread(); 3322254721Semaste } 3323254721Semaste else 3324254721Semaste { 3325254721Semaste if (GetID() != LLDB_INVALID_PROCESS_ID) 3326254721Semaste { 3327254721Semaste SetID (LLDB_INVALID_PROCESS_ID); 3328254721Semaste const char *error_string = error.AsCString(); 3329254721Semaste if (error_string == NULL) 3330254721Semaste error_string = "attach failed"; 3331254721Semaste 3332254721Semaste SetExitStatus(-1, error_string); 3333254721Semaste } 3334254721Semaste } 3335254721Semaste } 3336254721Semaste } 3337254721Semaste return error; 3338254721Semaste} 3339254721Semaste 3340254721Semastevoid 3341254721SemasteProcess::CompleteAttach () 3342254721Semaste{ 3343254721Semaste // Let the process subclass figure out at much as it can about the process 3344254721Semaste // before we go looking for a dynamic loader plug-in. 3345254721Semaste DidAttach(); 3346254721Semaste 3347254721Semaste // We just attached. If we have a platform, ask it for the process architecture, and if it isn't 3348254721Semaste // the same as the one we've already set, switch architectures. 3349254721Semaste PlatformSP platform_sp (m_target.GetPlatform ()); 3350254721Semaste assert (platform_sp.get()); 3351254721Semaste if (platform_sp) 3352254721Semaste { 3353254721Semaste const ArchSpec &target_arch = m_target.GetArchitecture(); 3354254721Semaste if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL)) 3355254721Semaste { 3356254721Semaste ArchSpec platform_arch; 3357254721Semaste platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch); 3358254721Semaste if (platform_sp) 3359254721Semaste { 3360254721Semaste m_target.SetPlatform (platform_sp); 3361254721Semaste m_target.SetArchitecture(platform_arch); 3362254721Semaste } 3363254721Semaste } 3364254721Semaste else 3365254721Semaste { 3366254721Semaste ProcessInstanceInfo process_info; 3367254721Semaste platform_sp->GetProcessInfo (GetID(), process_info); 3368254721Semaste const ArchSpec &process_arch = process_info.GetArchitecture(); 3369254721Semaste if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch)) 3370254721Semaste m_target.SetArchitecture (process_arch); 3371254721Semaste } 3372254721Semaste } 3373254721Semaste 3374254721Semaste // We have completed the attach, now it is time to find the dynamic loader 3375254721Semaste // plug-in 3376254721Semaste DynamicLoader *dyld = GetDynamicLoader (); 3377254721Semaste if (dyld) 3378254721Semaste dyld->DidAttach(); 3379254721Semaste 3380263363Semaste SystemRuntime *system_runtime = GetSystemRuntime (); 3381263363Semaste if (system_runtime) 3382263363Semaste system_runtime->DidAttach(); 3383263363Semaste 3384254721Semaste m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 3385254721Semaste // Figure out which one is the executable, and set that in our target: 3386254721Semaste const ModuleList &target_modules = m_target.GetImages(); 3387254721Semaste Mutex::Locker modules_locker(target_modules.GetMutex()); 3388254721Semaste size_t num_modules = target_modules.GetSize(); 3389254721Semaste ModuleSP new_executable_module_sp; 3390254721Semaste 3391254721Semaste for (size_t i = 0; i < num_modules; i++) 3392254721Semaste { 3393254721Semaste ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i)); 3394254721Semaste if (module_sp && module_sp->IsExecutable()) 3395254721Semaste { 3396254721Semaste if (m_target.GetExecutableModulePointer() != module_sp.get()) 3397254721Semaste new_executable_module_sp = module_sp; 3398254721Semaste break; 3399254721Semaste } 3400254721Semaste } 3401254721Semaste if (new_executable_module_sp) 3402254721Semaste m_target.SetExecutableModule (new_executable_module_sp, false); 3403254721Semaste} 3404254721Semaste 3405254721SemasteError 3406254721SemasteProcess::ConnectRemote (Stream *strm, const char *remote_url) 3407254721Semaste{ 3408254721Semaste m_abi_sp.reset(); 3409254721Semaste m_process_input_reader.reset(); 3410254721Semaste 3411254721Semaste // Find the process and its architecture. Make sure it matches the architecture 3412254721Semaste // of the current Target, and if not adjust it. 3413254721Semaste 3414254721Semaste Error error (DoConnectRemote (strm, remote_url)); 3415254721Semaste if (error.Success()) 3416254721Semaste { 3417254721Semaste if (GetID() != LLDB_INVALID_PROCESS_ID) 3418254721Semaste { 3419254721Semaste EventSP event_sp; 3420254721Semaste StateType state = WaitForProcessStopPrivate(NULL, event_sp); 3421254721Semaste 3422254721Semaste if (state == eStateStopped || state == eStateCrashed) 3423254721Semaste { 3424254721Semaste // If we attached and actually have a process on the other end, then 3425254721Semaste // this ended up being the equivalent of an attach. 3426254721Semaste CompleteAttach (); 3427254721Semaste 3428254721Semaste // This delays passing the stopped event to listeners till 3429254721Semaste // CompleteAttach gets a chance to complete... 3430254721Semaste HandlePrivateEvent (event_sp); 3431254721Semaste 3432254721Semaste } 3433254721Semaste } 3434254721Semaste 3435254721Semaste if (PrivateStateThreadIsValid ()) 3436254721Semaste ResumePrivateStateThread (); 3437254721Semaste else 3438254721Semaste StartPrivateStateThread (); 3439254721Semaste } 3440254721Semaste return error; 3441254721Semaste} 3442254721Semaste 3443254721Semaste 3444254721SemasteError 3445254721SemasteProcess::PrivateResume () 3446254721Semaste{ 3447254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP)); 3448254721Semaste if (log) 3449254721Semaste log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s", 3450254721Semaste m_mod_id.GetStopID(), 3451254721Semaste StateAsCString(m_public_state.GetValue()), 3452254721Semaste StateAsCString(m_private_state.GetValue())); 3453254721Semaste 3454254721Semaste Error error (WillResume()); 3455254721Semaste // Tell the process it is about to resume before the thread list 3456254721Semaste if (error.Success()) 3457254721Semaste { 3458254721Semaste // Now let the thread list know we are about to resume so it 3459254721Semaste // can let all of our threads know that they are about to be 3460254721Semaste // resumed. Threads will each be called with 3461254721Semaste // Thread::WillResume(StateType) where StateType contains the state 3462254721Semaste // that they are supposed to have when the process is resumed 3463254721Semaste // (suspended/running/stepping). Threads should also check 3464254721Semaste // their resume signal in lldb::Thread::GetResumeSignal() 3465254721Semaste // to see if they are supposed to start back up with a signal. 3466254721Semaste if (m_thread_list.WillResume()) 3467254721Semaste { 3468254721Semaste // Last thing, do the PreResumeActions. 3469254721Semaste if (!RunPreResumeActions()) 3470254721Semaste { 3471254721Semaste error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming."); 3472254721Semaste } 3473254721Semaste else 3474254721Semaste { 3475254721Semaste m_mod_id.BumpResumeID(); 3476254721Semaste error = DoResume(); 3477254721Semaste if (error.Success()) 3478254721Semaste { 3479254721Semaste DidResume(); 3480254721Semaste m_thread_list.DidResume(); 3481254721Semaste if (log) 3482254721Semaste log->Printf ("Process thinks the process has resumed."); 3483254721Semaste } 3484254721Semaste } 3485254721Semaste } 3486254721Semaste else 3487254721Semaste { 3488254721Semaste // Somebody wanted to run without running. So generate a continue & a stopped event, 3489254721Semaste // and let the world handle them. 3490254721Semaste if (log) 3491254721Semaste log->Printf ("Process::PrivateResume() asked to simulate a start & stop."); 3492254721Semaste 3493254721Semaste SetPrivateState(eStateRunning); 3494254721Semaste SetPrivateState(eStateStopped); 3495254721Semaste } 3496254721Semaste } 3497254721Semaste else if (log) 3498254721Semaste log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>")); 3499254721Semaste return error; 3500254721Semaste} 3501254721Semaste 3502254721SemasteError 3503254721SemasteProcess::Halt (bool clear_thread_plans) 3504254721Semaste{ 3505254721Semaste // Don't clear the m_clear_thread_plans_on_stop, only set it to true if 3506254721Semaste // in case it was already set and some thread plan logic calls halt on its 3507254721Semaste // own. 3508254721Semaste m_clear_thread_plans_on_stop |= clear_thread_plans; 3509254721Semaste 3510254721Semaste // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since 3511254721Semaste // we could just straightaway get another event. It just narrows the window... 3512254721Semaste m_currently_handling_event.WaitForValueEqualTo(false); 3513254721Semaste 3514254721Semaste 3515254721Semaste // Pause our private state thread so we can ensure no one else eats 3516254721Semaste // the stop event out from under us. 3517254721Semaste Listener halt_listener ("lldb.process.halt_listener"); 3518254721Semaste HijackPrivateProcessEvents(&halt_listener); 3519254721Semaste 3520254721Semaste EventSP event_sp; 3521254721Semaste Error error (WillHalt()); 3522254721Semaste 3523254721Semaste if (error.Success()) 3524254721Semaste { 3525254721Semaste 3526254721Semaste bool caused_stop = false; 3527254721Semaste 3528254721Semaste // Ask the process subclass to actually halt our process 3529254721Semaste error = DoHalt(caused_stop); 3530254721Semaste if (error.Success()) 3531254721Semaste { 3532254721Semaste if (m_public_state.GetValue() == eStateAttaching) 3533254721Semaste { 3534254721Semaste SetExitStatus(SIGKILL, "Cancelled async attach."); 3535254721Semaste Destroy (); 3536254721Semaste } 3537254721Semaste else 3538254721Semaste { 3539254721Semaste // If "caused_stop" is true, then DoHalt stopped the process. If 3540254721Semaste // "caused_stop" is false, the process was already stopped. 3541254721Semaste // If the DoHalt caused the process to stop, then we want to catch 3542254721Semaste // this event and set the interrupted bool to true before we pass 3543254721Semaste // this along so clients know that the process was interrupted by 3544254721Semaste // a halt command. 3545254721Semaste if (caused_stop) 3546254721Semaste { 3547254721Semaste // Wait for 1 second for the process to stop. 3548254721Semaste TimeValue timeout_time; 3549254721Semaste timeout_time = TimeValue::Now(); 3550254721Semaste timeout_time.OffsetWithSeconds(1); 3551254721Semaste bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp); 3552254721Semaste StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 3553254721Semaste 3554254721Semaste if (!got_event || state == eStateInvalid) 3555254721Semaste { 3556254721Semaste // We timeout out and didn't get a stop event... 3557254721Semaste error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState())); 3558254721Semaste } 3559254721Semaste else 3560254721Semaste { 3561254721Semaste if (StateIsStoppedState (state, false)) 3562254721Semaste { 3563254721Semaste // We caused the process to interrupt itself, so mark this 3564254721Semaste // as such in the stop event so clients can tell an interrupted 3565254721Semaste // process from a natural stop 3566254721Semaste ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); 3567254721Semaste } 3568254721Semaste else 3569254721Semaste { 3570254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3571254721Semaste if (log) 3572254721Semaste log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); 3573254721Semaste error.SetErrorString ("Did not get stopped event after halt."); 3574254721Semaste } 3575254721Semaste } 3576254721Semaste } 3577254721Semaste DidHalt(); 3578254721Semaste } 3579254721Semaste } 3580254721Semaste } 3581254721Semaste // Resume our private state thread before we post the event (if any) 3582254721Semaste RestorePrivateProcessEvents(); 3583254721Semaste 3584254721Semaste // Post any event we might have consumed. If all goes well, we will have 3585254721Semaste // stopped the process, intercepted the event and set the interrupted 3586254721Semaste // bool in the event. Post it to the private event queue and that will end up 3587254721Semaste // correctly setting the state. 3588254721Semaste if (event_sp) 3589254721Semaste m_private_state_broadcaster.BroadcastEvent(event_sp); 3590254721Semaste 3591254721Semaste return error; 3592254721Semaste} 3593254721Semaste 3594254721SemasteError 3595254721SemasteProcess::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp) 3596254721Semaste{ 3597254721Semaste Error error; 3598254721Semaste if (m_public_state.GetValue() == eStateRunning) 3599254721Semaste { 3600254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3601254721Semaste if (log) 3602254721Semaste log->Printf("Process::Destroy() About to halt."); 3603254721Semaste error = Halt(); 3604254721Semaste if (error.Success()) 3605254721Semaste { 3606254721Semaste // Consume the halt event. 3607254721Semaste TimeValue timeout (TimeValue::Now()); 3608254721Semaste timeout.OffsetWithSeconds(1); 3609254721Semaste StateType state = WaitForProcessToStop (&timeout, &exit_event_sp); 3610254721Semaste 3611254721Semaste // If the process exited while we were waiting for it to stop, put the exited event into 3612254721Semaste // the shared pointer passed in and return. Our caller doesn't need to do anything else, since 3613254721Semaste // they don't have a process anymore... 3614254721Semaste 3615254721Semaste if (state == eStateExited || m_private_state.GetValue() == eStateExited) 3616254721Semaste { 3617254721Semaste if (log) 3618254721Semaste log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt."); 3619254721Semaste return error; 3620254721Semaste } 3621254721Semaste else 3622254721Semaste exit_event_sp.reset(); // It is ok to consume any non-exit stop events 3623254721Semaste 3624254721Semaste if (state != eStateStopped) 3625254721Semaste { 3626254721Semaste if (log) 3627254721Semaste log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state)); 3628254721Semaste // If we really couldn't stop the process then we should just error out here, but if the 3629254721Semaste // lower levels just bobbled sending the event and we really are stopped, then continue on. 3630254721Semaste StateType private_state = m_private_state.GetValue(); 3631254721Semaste if (private_state != eStateStopped) 3632254721Semaste { 3633254721Semaste return error; 3634254721Semaste } 3635254721Semaste } 3636254721Semaste } 3637254721Semaste else 3638254721Semaste { 3639254721Semaste if (log) 3640254721Semaste log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString()); 3641254721Semaste } 3642254721Semaste } 3643254721Semaste return error; 3644254721Semaste} 3645254721Semaste 3646254721SemasteError 3647254721SemasteProcess::Detach (bool keep_stopped) 3648254721Semaste{ 3649254721Semaste EventSP exit_event_sp; 3650254721Semaste Error error; 3651254721Semaste m_destroy_in_process = true; 3652254721Semaste 3653254721Semaste error = WillDetach(); 3654254721Semaste 3655254721Semaste if (error.Success()) 3656254721Semaste { 3657254721Semaste if (DetachRequiresHalt()) 3658254721Semaste { 3659254721Semaste error = HaltForDestroyOrDetach (exit_event_sp); 3660254721Semaste if (!error.Success()) 3661254721Semaste { 3662254721Semaste m_destroy_in_process = false; 3663254721Semaste return error; 3664254721Semaste } 3665254721Semaste else if (exit_event_sp) 3666254721Semaste { 3667254721Semaste // We shouldn't need to do anything else here. There's no process left to detach from... 3668254721Semaste StopPrivateStateThread(); 3669254721Semaste m_destroy_in_process = false; 3670254721Semaste return error; 3671254721Semaste } 3672254721Semaste } 3673254721Semaste 3674254721Semaste error = DoDetach(keep_stopped); 3675254721Semaste if (error.Success()) 3676254721Semaste { 3677254721Semaste DidDetach(); 3678254721Semaste StopPrivateStateThread(); 3679254721Semaste } 3680254721Semaste else 3681254721Semaste { 3682254721Semaste return error; 3683254721Semaste } 3684254721Semaste } 3685254721Semaste m_destroy_in_process = false; 3686254721Semaste 3687254721Semaste // If we exited when we were waiting for a process to stop, then 3688254721Semaste // forward the event here so we don't lose the event 3689254721Semaste if (exit_event_sp) 3690254721Semaste { 3691254721Semaste // Directly broadcast our exited event because we shut down our 3692254721Semaste // private state thread above 3693254721Semaste BroadcastEvent(exit_event_sp); 3694254721Semaste } 3695254721Semaste 3696254721Semaste // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating 3697254721Semaste // the last events through the event system, in which case we might strand the write lock. Unlock 3698254721Semaste // it here so when we do to tear down the process we don't get an error destroying the lock. 3699254721Semaste 3700254721Semaste m_public_run_lock.SetStopped(); 3701254721Semaste return error; 3702254721Semaste} 3703254721Semaste 3704254721SemasteError 3705254721SemasteProcess::Destroy () 3706254721Semaste{ 3707254721Semaste 3708254721Semaste // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work 3709254721Semaste // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt 3710254721Semaste // failed and the process stays around for some reason it won't be in a confused state. 3711254721Semaste 3712254721Semaste m_destroy_in_process = true; 3713254721Semaste 3714254721Semaste Error error (WillDestroy()); 3715254721Semaste if (error.Success()) 3716254721Semaste { 3717254721Semaste EventSP exit_event_sp; 3718254721Semaste if (DestroyRequiresHalt()) 3719254721Semaste { 3720254721Semaste error = HaltForDestroyOrDetach(exit_event_sp); 3721254721Semaste } 3722254721Semaste 3723254721Semaste if (m_public_state.GetValue() != eStateRunning) 3724254721Semaste { 3725254721Semaste // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to 3726254721Semaste // kill it, we don't want it hitting a breakpoint... 3727254721Semaste // Only do this if we've stopped, however, since if we didn't manage to halt it above, then 3728254721Semaste // we're not going to have much luck doing this now. 3729254721Semaste m_thread_list.DiscardThreadPlans(); 3730254721Semaste DisableAllBreakpointSites(); 3731254721Semaste } 3732254721Semaste 3733254721Semaste error = DoDestroy(); 3734254721Semaste if (error.Success()) 3735254721Semaste { 3736254721Semaste DidDestroy(); 3737254721Semaste StopPrivateStateThread(); 3738254721Semaste } 3739254721Semaste m_stdio_communication.StopReadThread(); 3740254721Semaste m_stdio_communication.Disconnect(); 3741254721Semaste if (m_process_input_reader) 3742254721Semaste m_process_input_reader.reset(); 3743254721Semaste 3744254721Semaste // If we exited when we were waiting for a process to stop, then 3745254721Semaste // forward the event here so we don't lose the event 3746254721Semaste if (exit_event_sp) 3747254721Semaste { 3748254721Semaste // Directly broadcast our exited event because we shut down our 3749254721Semaste // private state thread above 3750254721Semaste BroadcastEvent(exit_event_sp); 3751254721Semaste } 3752254721Semaste 3753254721Semaste // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating 3754254721Semaste // the last events through the event system, in which case we might strand the write lock. Unlock 3755254721Semaste // it here so when we do to tear down the process we don't get an error destroying the lock. 3756254721Semaste m_public_run_lock.SetStopped(); 3757254721Semaste } 3758254721Semaste 3759254721Semaste m_destroy_in_process = false; 3760254721Semaste 3761254721Semaste return error; 3762254721Semaste} 3763254721Semaste 3764254721SemasteError 3765254721SemasteProcess::Signal (int signal) 3766254721Semaste{ 3767254721Semaste Error error (WillSignal()); 3768254721Semaste if (error.Success()) 3769254721Semaste { 3770254721Semaste error = DoSignal(signal); 3771254721Semaste if (error.Success()) 3772254721Semaste DidSignal(); 3773254721Semaste } 3774254721Semaste return error; 3775254721Semaste} 3776254721Semaste 3777254721Semastelldb::ByteOrder 3778254721SemasteProcess::GetByteOrder () const 3779254721Semaste{ 3780254721Semaste return m_target.GetArchitecture().GetByteOrder(); 3781254721Semaste} 3782254721Semaste 3783254721Semasteuint32_t 3784254721SemasteProcess::GetAddressByteSize () const 3785254721Semaste{ 3786254721Semaste return m_target.GetArchitecture().GetAddressByteSize(); 3787254721Semaste} 3788254721Semaste 3789254721Semaste 3790254721Semastebool 3791254721SemasteProcess::ShouldBroadcastEvent (Event *event_ptr) 3792254721Semaste{ 3793254721Semaste const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr); 3794254721Semaste bool return_value = true; 3795254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS)); 3796254721Semaste 3797254721Semaste switch (state) 3798254721Semaste { 3799254721Semaste case eStateConnected: 3800254721Semaste case eStateAttaching: 3801254721Semaste case eStateLaunching: 3802254721Semaste case eStateDetached: 3803254721Semaste case eStateExited: 3804254721Semaste case eStateUnloaded: 3805254721Semaste // These events indicate changes in the state of the debugging session, always report them. 3806254721Semaste return_value = true; 3807254721Semaste break; 3808254721Semaste case eStateInvalid: 3809254721Semaste // We stopped for no apparent reason, don't report it. 3810254721Semaste return_value = false; 3811254721Semaste break; 3812254721Semaste case eStateRunning: 3813254721Semaste case eStateStepping: 3814254721Semaste // If we've started the target running, we handle the cases where we 3815254721Semaste // are already running and where there is a transition from stopped to 3816254721Semaste // running differently. 3817254721Semaste // running -> running: Automatically suppress extra running events 3818254721Semaste // stopped -> running: Report except when there is one or more no votes 3819254721Semaste // and no yes votes. 3820254721Semaste SynchronouslyNotifyStateChanged (state); 3821269024Semaste if (m_force_next_event_delivery) 3822269024Semaste return_value = true; 3823269024Semaste else 3824254721Semaste { 3825269024Semaste switch (m_last_broadcast_state) 3826269024Semaste { 3827269024Semaste case eStateRunning: 3828269024Semaste case eStateStepping: 3829269024Semaste // We always suppress multiple runnings with no PUBLIC stop in between. 3830269024Semaste return_value = false; 3831269024Semaste break; 3832269024Semaste default: 3833269024Semaste // TODO: make this work correctly. For now always report 3834269024Semaste // run if we aren't running so we don't miss any runnning 3835269024Semaste // events. If I run the lldb/test/thread/a.out file and 3836269024Semaste // break at main.cpp:58, run and hit the breakpoints on 3837269024Semaste // multiple threads, then somehow during the stepping over 3838269024Semaste // of all breakpoints no run gets reported. 3839254721Semaste 3840269024Semaste // This is a transition from stop to run. 3841269024Semaste switch (m_thread_list.ShouldReportRun (event_ptr)) 3842269024Semaste { 3843269024Semaste case eVoteYes: 3844269024Semaste case eVoteNoOpinion: 3845269024Semaste return_value = true; 3846269024Semaste break; 3847269024Semaste case eVoteNo: 3848269024Semaste return_value = false; 3849269024Semaste break; 3850269024Semaste } 3851269024Semaste break; 3852269024Semaste } 3853254721Semaste } 3854254721Semaste break; 3855254721Semaste case eStateStopped: 3856254721Semaste case eStateCrashed: 3857254721Semaste case eStateSuspended: 3858254721Semaste { 3859254721Semaste // We've stopped. First see if we're going to restart the target. 3860254721Semaste // If we are going to stop, then we always broadcast the event. 3861254721Semaste // If we aren't going to stop, let the thread plans decide if we're going to report this event. 3862254721Semaste // If no thread has an opinion, we don't report it. 3863254721Semaste 3864254721Semaste RefreshStateAfterStop (); 3865254721Semaste if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) 3866254721Semaste { 3867254721Semaste if (log) 3868254721Semaste log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", 3869254721Semaste event_ptr, 3870254721Semaste StateAsCString(state)); 3871254721Semaste return_value = true; 3872254721Semaste } 3873254721Semaste else 3874254721Semaste { 3875254721Semaste bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr); 3876254721Semaste bool should_resume = false; 3877254721Semaste 3878254721Semaste // It makes no sense to ask "ShouldStop" if we've already been restarted... 3879254721Semaste // Asking the thread list is also not likely to go well, since we are running again. 3880254721Semaste // So in that case just report the event. 3881254721Semaste 3882254721Semaste if (!was_restarted) 3883254721Semaste should_resume = m_thread_list.ShouldStop (event_ptr) == false; 3884254721Semaste 3885254721Semaste if (was_restarted || should_resume || m_resume_requested) 3886254721Semaste { 3887254721Semaste Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr); 3888254721Semaste if (log) 3889254721Semaste log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.", 3890254721Semaste should_resume, 3891254721Semaste StateAsCString(state), 3892254721Semaste was_restarted, 3893254721Semaste stop_vote); 3894254721Semaste 3895254721Semaste switch (stop_vote) 3896254721Semaste { 3897254721Semaste case eVoteYes: 3898254721Semaste return_value = true; 3899254721Semaste break; 3900254721Semaste case eVoteNoOpinion: 3901254721Semaste case eVoteNo: 3902254721Semaste return_value = false; 3903254721Semaste break; 3904254721Semaste } 3905254721Semaste 3906254721Semaste if (!was_restarted) 3907254721Semaste { 3908254721Semaste if (log) 3909254721Semaste log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state)); 3910254721Semaste ProcessEventData::SetRestartedInEvent(event_ptr, true); 3911254721Semaste PrivateResume (); 3912254721Semaste } 3913254721Semaste 3914254721Semaste } 3915254721Semaste else 3916254721Semaste { 3917254721Semaste return_value = true; 3918254721Semaste SynchronouslyNotifyStateChanged (state); 3919254721Semaste } 3920254721Semaste } 3921254721Semaste } 3922254721Semaste break; 3923254721Semaste } 3924254721Semaste 3925269024Semaste // Forcing the next event delivery is a one shot deal. So reset it here. 3926269024Semaste m_force_next_event_delivery = false; 3927269024Semaste 3928254721Semaste // We do some coalescing of events (for instance two consecutive running events get coalesced.) 3929254721Semaste // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state 3930254721Semaste // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done, 3931254721Semaste // because the PublicState reflects the last event pulled off the queue, and there may be several 3932254721Semaste // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event 3933254721Semaste // yet. m_last_broadcast_state gets updated here. 3934254721Semaste 3935254721Semaste if (return_value) 3936254721Semaste m_last_broadcast_state = state; 3937254721Semaste 3938254721Semaste if (log) 3939254721Semaste log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s", 3940254721Semaste event_ptr, 3941254721Semaste StateAsCString(state), 3942254721Semaste StateAsCString(m_last_broadcast_state), 3943254721Semaste return_value ? "YES" : "NO"); 3944254721Semaste return return_value; 3945254721Semaste} 3946254721Semaste 3947254721Semaste 3948254721Semastebool 3949254721SemasteProcess::StartPrivateStateThread (bool force) 3950254721Semaste{ 3951254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3952254721Semaste 3953254721Semaste bool already_running = PrivateStateThreadIsValid (); 3954254721Semaste if (log) 3955254721Semaste log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread"); 3956254721Semaste 3957254721Semaste if (!force && already_running) 3958254721Semaste return true; 3959254721Semaste 3960254721Semaste // Create a thread that watches our internal state and controls which 3961254721Semaste // events make it to clients (into the DCProcess event queue). 3962254721Semaste char thread_name[1024]; 3963254721Semaste if (already_running) 3964254721Semaste snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID()); 3965254721Semaste else 3966254721Semaste snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID()); 3967254721Semaste 3968254721Semaste // Create the private state thread, and start it running. 3969254721Semaste m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL); 3970254721Semaste bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread); 3971254721Semaste if (success) 3972254721Semaste { 3973254721Semaste ResumePrivateStateThread(); 3974254721Semaste return true; 3975254721Semaste } 3976254721Semaste else 3977254721Semaste return false; 3978254721Semaste} 3979254721Semaste 3980254721Semastevoid 3981254721SemasteProcess::PausePrivateStateThread () 3982254721Semaste{ 3983254721Semaste ControlPrivateStateThread (eBroadcastInternalStateControlPause); 3984254721Semaste} 3985254721Semaste 3986254721Semastevoid 3987254721SemasteProcess::ResumePrivateStateThread () 3988254721Semaste{ 3989254721Semaste ControlPrivateStateThread (eBroadcastInternalStateControlResume); 3990254721Semaste} 3991254721Semaste 3992254721Semastevoid 3993254721SemasteProcess::StopPrivateStateThread () 3994254721Semaste{ 3995254721Semaste if (PrivateStateThreadIsValid ()) 3996254721Semaste ControlPrivateStateThread (eBroadcastInternalStateControlStop); 3997254721Semaste else 3998254721Semaste { 3999254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4000254721Semaste if (log) 4001254721Semaste log->Printf ("Went to stop the private state thread, but it was already invalid."); 4002254721Semaste } 4003254721Semaste} 4004254721Semaste 4005254721Semastevoid 4006254721SemasteProcess::ControlPrivateStateThread (uint32_t signal) 4007254721Semaste{ 4008254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4009254721Semaste 4010254721Semaste assert (signal == eBroadcastInternalStateControlStop || 4011254721Semaste signal == eBroadcastInternalStateControlPause || 4012254721Semaste signal == eBroadcastInternalStateControlResume); 4013254721Semaste 4014254721Semaste if (log) 4015254721Semaste log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal); 4016254721Semaste 4017254721Semaste // Signal the private state thread. First we should copy this is case the 4018254721Semaste // thread starts exiting since the private state thread will NULL this out 4019254721Semaste // when it exits 4020254721Semaste const lldb::thread_t private_state_thread = m_private_state_thread; 4021254721Semaste if (IS_VALID_LLDB_HOST_THREAD(private_state_thread)) 4022254721Semaste { 4023254721Semaste TimeValue timeout_time; 4024254721Semaste bool timed_out; 4025254721Semaste 4026254721Semaste m_private_state_control_broadcaster.BroadcastEvent (signal, NULL); 4027254721Semaste 4028254721Semaste timeout_time = TimeValue::Now(); 4029254721Semaste timeout_time.OffsetWithSeconds(2); 4030254721Semaste if (log) 4031254721Semaste log->Printf ("Sending control event of type: %d.", signal); 4032254721Semaste m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out); 4033254721Semaste m_private_state_control_wait.SetValue (false, eBroadcastNever); 4034254721Semaste 4035254721Semaste if (signal == eBroadcastInternalStateControlStop) 4036254721Semaste { 4037254721Semaste if (timed_out) 4038254721Semaste { 4039254721Semaste Error error; 4040254721Semaste Host::ThreadCancel (private_state_thread, &error); 4041254721Semaste if (log) 4042254721Semaste log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString()); 4043254721Semaste } 4044254721Semaste else 4045254721Semaste { 4046254721Semaste if (log) 4047254721Semaste log->Printf ("The control event killed the private state thread without having to cancel."); 4048254721Semaste } 4049254721Semaste 4050254721Semaste thread_result_t result = NULL; 4051254721Semaste Host::ThreadJoin (private_state_thread, &result, NULL); 4052254721Semaste m_private_state_thread = LLDB_INVALID_HOST_THREAD; 4053254721Semaste } 4054254721Semaste } 4055254721Semaste else 4056254721Semaste { 4057254721Semaste if (log) 4058254721Semaste log->Printf ("Private state thread already dead, no need to signal it to stop."); 4059254721Semaste } 4060254721Semaste} 4061254721Semaste 4062254721Semastevoid 4063254721SemasteProcess::SendAsyncInterrupt () 4064254721Semaste{ 4065254721Semaste if (PrivateStateThreadIsValid()) 4066254721Semaste m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL); 4067254721Semaste else 4068254721Semaste BroadcastEvent (Process::eBroadcastBitInterrupt, NULL); 4069254721Semaste} 4070254721Semaste 4071254721Semastevoid 4072254721SemasteProcess::HandlePrivateEvent (EventSP &event_sp) 4073254721Semaste{ 4074254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4075254721Semaste m_resume_requested = false; 4076254721Semaste 4077254721Semaste m_currently_handling_event.SetValue(true, eBroadcastNever); 4078254721Semaste 4079254721Semaste const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4080254721Semaste 4081254721Semaste // First check to see if anybody wants a shot at this event: 4082254721Semaste if (m_next_event_action_ap.get() != NULL) 4083254721Semaste { 4084254721Semaste NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp); 4085254721Semaste if (log) 4086254721Semaste log->Printf ("Ran next event action, result was %d.", action_result); 4087254721Semaste 4088254721Semaste switch (action_result) 4089254721Semaste { 4090254721Semaste case NextEventAction::eEventActionSuccess: 4091254721Semaste SetNextEventAction(NULL); 4092254721Semaste break; 4093254721Semaste 4094254721Semaste case NextEventAction::eEventActionRetry: 4095254721Semaste break; 4096254721Semaste 4097254721Semaste case NextEventAction::eEventActionExit: 4098254721Semaste // Handle Exiting Here. If we already got an exited event, 4099254721Semaste // we should just propagate it. Otherwise, swallow this event, 4100254721Semaste // and set our state to exit so the next event will kill us. 4101254721Semaste if (new_state != eStateExited) 4102254721Semaste { 4103254721Semaste // FIXME: should cons up an exited event, and discard this one. 4104254721Semaste SetExitStatus(0, m_next_event_action_ap->GetExitString()); 4105254721Semaste m_currently_handling_event.SetValue(false, eBroadcastAlways); 4106254721Semaste SetNextEventAction(NULL); 4107254721Semaste return; 4108254721Semaste } 4109254721Semaste SetNextEventAction(NULL); 4110254721Semaste break; 4111254721Semaste } 4112254721Semaste } 4113254721Semaste 4114254721Semaste // See if we should broadcast this state to external clients? 4115254721Semaste const bool should_broadcast = ShouldBroadcastEvent (event_sp.get()); 4116254721Semaste 4117254721Semaste if (should_broadcast) 4118254721Semaste { 4119254721Semaste if (log) 4120254721Semaste { 4121254721Semaste log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s", 4122254721Semaste __FUNCTION__, 4123254721Semaste GetID(), 4124254721Semaste StateAsCString(new_state), 4125254721Semaste StateAsCString (GetState ()), 4126254721Semaste IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public"); 4127254721Semaste } 4128254721Semaste Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 4129254721Semaste if (StateIsRunningState (new_state)) 4130269024Semaste { 4131269024Semaste // Only push the input handler if we aren't fowarding events, 4132269024Semaste // as this means the curses GUI is in use... 4133269024Semaste if (!GetTarget().GetDebugger().IsForwardingEvents()) 4134269024Semaste PushProcessIOHandler (); 4135269024Semaste } 4136254721Semaste else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 4137269024Semaste PopProcessIOHandler (); 4138254721Semaste 4139254721Semaste BroadcastEvent (event_sp); 4140254721Semaste } 4141254721Semaste else 4142254721Semaste { 4143254721Semaste if (log) 4144254721Semaste { 4145254721Semaste log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false", 4146254721Semaste __FUNCTION__, 4147254721Semaste GetID(), 4148254721Semaste StateAsCString(new_state), 4149254721Semaste StateAsCString (GetState ())); 4150254721Semaste } 4151254721Semaste } 4152254721Semaste m_currently_handling_event.SetValue(false, eBroadcastAlways); 4153254721Semaste} 4154254721Semaste 4155263363Semastethread_result_t 4156254721SemasteProcess::PrivateStateThread (void *arg) 4157254721Semaste{ 4158254721Semaste Process *proc = static_cast<Process*> (arg); 4159263363Semaste thread_result_t result = proc->RunPrivateStateThread(); 4160254721Semaste return result; 4161254721Semaste} 4162254721Semaste 4163263363Semastethread_result_t 4164254721SemasteProcess::RunPrivateStateThread () 4165254721Semaste{ 4166254721Semaste bool control_only = true; 4167254721Semaste m_private_state_control_wait.SetValue (false, eBroadcastNever); 4168254721Semaste 4169254721Semaste Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4170254721Semaste if (log) 4171254721Semaste log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID()); 4172254721Semaste 4173254721Semaste bool exit_now = false; 4174254721Semaste while (!exit_now) 4175254721Semaste { 4176254721Semaste EventSP event_sp; 4177254721Semaste WaitForEventsPrivate (NULL, event_sp, control_only); 4178254721Semaste if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) 4179254721Semaste { 4180254721Semaste if (log) 4181254721Semaste log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType()); 4182254721Semaste 4183254721Semaste switch (event_sp->GetType()) 4184254721Semaste { 4185254721Semaste case eBroadcastInternalStateControlStop: 4186254721Semaste exit_now = true; 4187254721Semaste break; // doing any internal state managment below 4188254721Semaste 4189254721Semaste case eBroadcastInternalStateControlPause: 4190254721Semaste control_only = true; 4191254721Semaste break; 4192254721Semaste 4193254721Semaste case eBroadcastInternalStateControlResume: 4194254721Semaste control_only = false; 4195254721Semaste break; 4196254721Semaste } 4197254721Semaste 4198254721Semaste m_private_state_control_wait.SetValue (true, eBroadcastAlways); 4199254721Semaste continue; 4200254721Semaste } 4201254721Semaste else if (event_sp->GetType() == eBroadcastBitInterrupt) 4202254721Semaste { 4203254721Semaste if (m_public_state.GetValue() == eStateAttaching) 4204254721Semaste { 4205254721Semaste if (log) 4206254721Semaste log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID()); 4207254721Semaste BroadcastEvent (eBroadcastBitInterrupt, NULL); 4208254721Semaste } 4209254721Semaste else 4210254721Semaste { 4211254721Semaste if (log) 4212254721Semaste log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID()); 4213254721Semaste Halt(); 4214254721Semaste } 4215254721Semaste continue; 4216254721Semaste } 4217254721Semaste 4218254721Semaste const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4219254721Semaste 4220254721Semaste if (internal_state != eStateInvalid) 4221254721Semaste { 4222254721Semaste if (m_clear_thread_plans_on_stop && 4223254721Semaste StateIsStoppedState(internal_state, true)) 4224254721Semaste { 4225254721Semaste m_clear_thread_plans_on_stop = false; 4226254721Semaste m_thread_list.DiscardThreadPlans(); 4227254721Semaste } 4228254721Semaste HandlePrivateEvent (event_sp); 4229254721Semaste } 4230254721Semaste 4231254721Semaste if (internal_state == eStateInvalid || 4232254721Semaste internal_state == eStateExited || 4233254721Semaste internal_state == eStateDetached ) 4234254721Semaste { 4235254721Semaste if (log) 4236254721Semaste log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state)); 4237254721Semaste 4238254721Semaste break; 4239254721Semaste } 4240254721Semaste } 4241254721Semaste 4242254721Semaste // Verify log is still enabled before attempting to write to it... 4243254721Semaste if (log) 4244254721Semaste log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID()); 4245254721Semaste 4246254721Semaste m_public_run_lock.SetStopped(); 4247254721Semaste m_private_state_control_wait.SetValue (true, eBroadcastAlways); 4248254721Semaste m_private_state_thread = LLDB_INVALID_HOST_THREAD; 4249254721Semaste return NULL; 4250254721Semaste} 4251254721Semaste 4252254721Semaste//------------------------------------------------------------------ 4253254721Semaste// Process Event Data 4254254721Semaste//------------------------------------------------------------------ 4255254721Semaste 4256254721SemasteProcess::ProcessEventData::ProcessEventData () : 4257254721Semaste EventData (), 4258254721Semaste m_process_sp (), 4259254721Semaste m_state (eStateInvalid), 4260254721Semaste m_restarted (false), 4261254721Semaste m_update_state (0), 4262254721Semaste m_interrupted (false) 4263254721Semaste{ 4264254721Semaste} 4265254721Semaste 4266254721SemasteProcess::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) : 4267254721Semaste EventData (), 4268254721Semaste m_process_sp (process_sp), 4269254721Semaste m_state (state), 4270254721Semaste m_restarted (false), 4271254721Semaste m_update_state (0), 4272254721Semaste m_interrupted (false) 4273254721Semaste{ 4274254721Semaste} 4275254721Semaste 4276254721SemasteProcess::ProcessEventData::~ProcessEventData() 4277254721Semaste{ 4278254721Semaste} 4279254721Semaste 4280254721Semasteconst ConstString & 4281254721SemasteProcess::ProcessEventData::GetFlavorString () 4282254721Semaste{ 4283254721Semaste static ConstString g_flavor ("Process::ProcessEventData"); 4284254721Semaste return g_flavor; 4285254721Semaste} 4286254721Semaste 4287254721Semasteconst ConstString & 4288254721SemasteProcess::ProcessEventData::GetFlavor () const 4289254721Semaste{ 4290254721Semaste return ProcessEventData::GetFlavorString (); 4291254721Semaste} 4292254721Semaste 4293254721Semastevoid 4294254721SemasteProcess::ProcessEventData::DoOnRemoval (Event *event_ptr) 4295254721Semaste{ 4296254721Semaste // This function gets called twice for each event, once when the event gets pulled 4297254721Semaste // off of the private process event queue, and then any number of times, first when it gets pulled off of 4298254721Semaste // the public event queue, then other times when we're pretending that this is where we stopped at the 4299254721Semaste // end of expression evaluation. m_update_state is used to distinguish these 4300254721Semaste // three cases; it is 0 when we're just pulling it off for private handling, 4301254721Semaste // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then. 4302254721Semaste if (m_update_state != 1) 4303254721Semaste return; 4304254721Semaste 4305254721Semaste m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr)); 4306254721Semaste 4307254721Semaste // If we're stopped and haven't restarted, then do the breakpoint commands here: 4308254721Semaste if (m_state == eStateStopped && ! m_restarted) 4309254721Semaste { 4310254721Semaste ThreadList &curr_thread_list = m_process_sp->GetThreadList(); 4311254721Semaste uint32_t num_threads = curr_thread_list.GetSize(); 4312254721Semaste uint32_t idx; 4313254721Semaste 4314254721Semaste // The actions might change one of the thread's stop_info's opinions about whether we should 4315254721Semaste // stop the process, so we need to query that as we go. 4316254721Semaste 4317254721Semaste // One other complication here, is that we try to catch any case where the target has run (except for expressions) 4318254721Semaste // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and 4319254721Semaste // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like 4320254721Semaste // 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 4321254721Semaste // against this list & bag out if anything differs. 4322254721Semaste std::vector<uint32_t> thread_index_array(num_threads); 4323254721Semaste for (idx = 0; idx < num_threads; ++idx) 4324254721Semaste thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 4325254721Semaste 4326254721Semaste // Use this to track whether we should continue from here. We will only continue the target running if 4327254721Semaste // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running, 4328254721Semaste // then it doesn't matter what the other threads say... 4329254721Semaste 4330254721Semaste bool still_should_stop = false; 4331254721Semaste 4332254721Semaste // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a 4333254721Semaste // valid stop reason. In that case we should just stop, because we have no way of telling what the right 4334254721Semaste // thing to do is, and it's better to let the user decide than continue behind their backs. 4335254721Semaste 4336254721Semaste bool does_anybody_have_an_opinion = false; 4337254721Semaste 4338254721Semaste for (idx = 0; idx < num_threads; ++idx) 4339254721Semaste { 4340254721Semaste curr_thread_list = m_process_sp->GetThreadList(); 4341254721Semaste if (curr_thread_list.GetSize() != num_threads) 4342254721Semaste { 4343254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 4344254721Semaste if (log) 4345254721Semaste log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize()); 4346254721Semaste break; 4347254721Semaste } 4348254721Semaste 4349254721Semaste lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 4350254721Semaste 4351254721Semaste if (thread_sp->GetIndexID() != thread_index_array[idx]) 4352254721Semaste { 4353254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 4354254721Semaste if (log) 4355254721Semaste log->Printf("The thread at position %u changed from %u to %u while processing event.", 4356254721Semaste idx, 4357254721Semaste thread_index_array[idx], 4358254721Semaste thread_sp->GetIndexID()); 4359254721Semaste break; 4360254721Semaste } 4361254721Semaste 4362254721Semaste StopInfoSP stop_info_sp = thread_sp->GetStopInfo (); 4363254721Semaste if (stop_info_sp && stop_info_sp->IsValid()) 4364254721Semaste { 4365254721Semaste does_anybody_have_an_opinion = true; 4366254721Semaste bool this_thread_wants_to_stop; 4367254721Semaste if (stop_info_sp->GetOverrideShouldStop()) 4368254721Semaste { 4369254721Semaste this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue(); 4370254721Semaste } 4371254721Semaste else 4372254721Semaste { 4373254721Semaste stop_info_sp->PerformAction(event_ptr); 4374254721Semaste // The stop action might restart the target. If it does, then we want to mark that in the 4375254721Semaste // event so that whoever is receiving it will know to wait for the running event and reflect 4376254721Semaste // that state appropriately. 4377254721Semaste // We also need to stop processing actions, since they aren't expecting the target to be running. 4378254721Semaste 4379254721Semaste // FIXME: we might have run. 4380254721Semaste if (stop_info_sp->HasTargetRunSinceMe()) 4381254721Semaste { 4382254721Semaste SetRestarted (true); 4383254721Semaste break; 4384254721Semaste } 4385254721Semaste 4386254721Semaste this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr); 4387254721Semaste } 4388254721Semaste 4389254721Semaste if (still_should_stop == false) 4390254721Semaste still_should_stop = this_thread_wants_to_stop; 4391254721Semaste } 4392254721Semaste } 4393254721Semaste 4394254721Semaste 4395254721Semaste if (!GetRestarted()) 4396254721Semaste { 4397254721Semaste if (!still_should_stop && does_anybody_have_an_opinion) 4398254721Semaste { 4399254721Semaste // We've been asked to continue, so do that here. 4400254721Semaste SetRestarted(true); 4401254721Semaste // Use the public resume method here, since this is just 4402254721Semaste // extending a public resume. 4403254721Semaste m_process_sp->PrivateResume(); 4404254721Semaste } 4405254721Semaste else 4406254721Semaste { 4407254721Semaste // If we didn't restart, run the Stop Hooks here: 4408254721Semaste // They might also restart the target, so watch for that. 4409254721Semaste m_process_sp->GetTarget().RunStopHooks(); 4410254721Semaste if (m_process_sp->GetPrivateState() == eStateRunning) 4411254721Semaste SetRestarted(true); 4412254721Semaste } 4413254721Semaste } 4414254721Semaste } 4415254721Semaste} 4416254721Semaste 4417254721Semastevoid 4418254721SemasteProcess::ProcessEventData::Dump (Stream *s) const 4419254721Semaste{ 4420254721Semaste if (m_process_sp) 4421254721Semaste s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID()); 4422254721Semaste 4423254721Semaste s->Printf("state = %s", StateAsCString(GetState())); 4424254721Semaste} 4425254721Semaste 4426254721Semasteconst Process::ProcessEventData * 4427254721SemasteProcess::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr) 4428254721Semaste{ 4429254721Semaste if (event_ptr) 4430254721Semaste { 4431254721Semaste const EventData *event_data = event_ptr->GetData(); 4432254721Semaste if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 4433254721Semaste return static_cast <const ProcessEventData *> (event_ptr->GetData()); 4434254721Semaste } 4435254721Semaste return NULL; 4436254721Semaste} 4437254721Semaste 4438254721SemasteProcessSP 4439254721SemasteProcess::ProcessEventData::GetProcessFromEvent (const Event *event_ptr) 4440254721Semaste{ 4441254721Semaste ProcessSP process_sp; 4442254721Semaste const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4443254721Semaste if (data) 4444254721Semaste process_sp = data->GetProcessSP(); 4445254721Semaste return process_sp; 4446254721Semaste} 4447254721Semaste 4448254721SemasteStateType 4449254721SemasteProcess::ProcessEventData::GetStateFromEvent (const Event *event_ptr) 4450254721Semaste{ 4451254721Semaste const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4452254721Semaste if (data == NULL) 4453254721Semaste return eStateInvalid; 4454254721Semaste else 4455254721Semaste return data->GetState(); 4456254721Semaste} 4457254721Semaste 4458254721Semastebool 4459254721SemasteProcess::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr) 4460254721Semaste{ 4461254721Semaste const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4462254721Semaste if (data == NULL) 4463254721Semaste return false; 4464254721Semaste else 4465254721Semaste return data->GetRestarted(); 4466254721Semaste} 4467254721Semaste 4468254721Semastevoid 4469254721SemasteProcess::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value) 4470254721Semaste{ 4471254721Semaste ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4472254721Semaste if (data != NULL) 4473254721Semaste data->SetRestarted(new_value); 4474254721Semaste} 4475254721Semaste 4476254721Semastesize_t 4477254721SemasteProcess::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) 4478254721Semaste{ 4479254721Semaste ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4480254721Semaste if (data != NULL) 4481254721Semaste return data->GetNumRestartedReasons(); 4482254721Semaste else 4483254721Semaste return 0; 4484254721Semaste} 4485254721Semaste 4486254721Semasteconst char * 4487254721SemasteProcess::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx) 4488254721Semaste{ 4489254721Semaste ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4490254721Semaste if (data != NULL) 4491254721Semaste return data->GetRestartedReasonAtIndex(idx); 4492254721Semaste else 4493254721Semaste return NULL; 4494254721Semaste} 4495254721Semaste 4496254721Semastevoid 4497254721SemasteProcess::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason) 4498254721Semaste{ 4499254721Semaste ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4500254721Semaste if (data != NULL) 4501254721Semaste data->AddRestartedReason(reason); 4502254721Semaste} 4503254721Semaste 4504254721Semastebool 4505254721SemasteProcess::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) 4506254721Semaste{ 4507254721Semaste const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4508254721Semaste if (data == NULL) 4509254721Semaste return false; 4510254721Semaste else 4511254721Semaste return data->GetInterrupted (); 4512254721Semaste} 4513254721Semaste 4514254721Semastevoid 4515254721SemasteProcess::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) 4516254721Semaste{ 4517254721Semaste ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4518254721Semaste if (data != NULL) 4519254721Semaste data->SetInterrupted(new_value); 4520254721Semaste} 4521254721Semaste 4522254721Semastebool 4523254721SemasteProcess::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) 4524254721Semaste{ 4525254721Semaste ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4526254721Semaste if (data) 4527254721Semaste { 4528254721Semaste data->SetUpdateStateOnRemoval(); 4529254721Semaste return true; 4530254721Semaste } 4531254721Semaste return false; 4532254721Semaste} 4533254721Semaste 4534254721Semastelldb::TargetSP 4535254721SemasteProcess::CalculateTarget () 4536254721Semaste{ 4537254721Semaste return m_target.shared_from_this(); 4538254721Semaste} 4539254721Semaste 4540254721Semastevoid 4541254721SemasteProcess::CalculateExecutionContext (ExecutionContext &exe_ctx) 4542254721Semaste{ 4543254721Semaste exe_ctx.SetTargetPtr (&m_target); 4544254721Semaste exe_ctx.SetProcessPtr (this); 4545254721Semaste exe_ctx.SetThreadPtr(NULL); 4546254721Semaste exe_ctx.SetFramePtr (NULL); 4547254721Semaste} 4548254721Semaste 4549254721Semaste//uint32_t 4550254721Semaste//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 4551254721Semaste//{ 4552254721Semaste// return 0; 4553254721Semaste//} 4554254721Semaste// 4555254721Semaste//ArchSpec 4556254721Semaste//Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 4557254721Semaste//{ 4558254721Semaste// return Host::GetArchSpecForExistingProcess (pid); 4559254721Semaste//} 4560254721Semaste// 4561254721Semaste//ArchSpec 4562254721Semaste//Process::GetArchSpecForExistingProcess (const char *process_name) 4563254721Semaste//{ 4564254721Semaste// return Host::GetArchSpecForExistingProcess (process_name); 4565254721Semaste//} 4566254721Semaste// 4567254721Semastevoid 4568254721SemasteProcess::AppendSTDOUT (const char * s, size_t len) 4569254721Semaste{ 4570254721Semaste Mutex::Locker locker (m_stdio_communication_mutex); 4571254721Semaste m_stdout_data.append (s, len); 4572254721Semaste BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState())); 4573254721Semaste} 4574254721Semaste 4575254721Semastevoid 4576254721SemasteProcess::AppendSTDERR (const char * s, size_t len) 4577254721Semaste{ 4578254721Semaste Mutex::Locker locker (m_stdio_communication_mutex); 4579254721Semaste m_stderr_data.append (s, len); 4580254721Semaste BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState())); 4581254721Semaste} 4582254721Semaste 4583254721Semastevoid 4584254721SemasteProcess::BroadcastAsyncProfileData(const std::string &one_profile_data) 4585254721Semaste{ 4586254721Semaste Mutex::Locker locker (m_profile_data_comm_mutex); 4587254721Semaste m_profile_data.push_back(one_profile_data); 4588254721Semaste BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState())); 4589254721Semaste} 4590254721Semaste 4591254721Semastesize_t 4592254721SemasteProcess::GetAsyncProfileData (char *buf, size_t buf_size, Error &error) 4593254721Semaste{ 4594254721Semaste Mutex::Locker locker(m_profile_data_comm_mutex); 4595254721Semaste if (m_profile_data.empty()) 4596254721Semaste return 0; 4597254721Semaste 4598254721Semaste std::string &one_profile_data = m_profile_data.front(); 4599254721Semaste size_t bytes_available = one_profile_data.size(); 4600254721Semaste if (bytes_available > 0) 4601254721Semaste { 4602254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4603254721Semaste if (log) 4604254721Semaste log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size); 4605254721Semaste if (bytes_available > buf_size) 4606254721Semaste { 4607254721Semaste memcpy(buf, one_profile_data.c_str(), buf_size); 4608254721Semaste one_profile_data.erase(0, buf_size); 4609254721Semaste bytes_available = buf_size; 4610254721Semaste } 4611254721Semaste else 4612254721Semaste { 4613254721Semaste memcpy(buf, one_profile_data.c_str(), bytes_available); 4614254721Semaste m_profile_data.erase(m_profile_data.begin()); 4615254721Semaste } 4616254721Semaste } 4617254721Semaste return bytes_available; 4618254721Semaste} 4619254721Semaste 4620254721Semaste 4621254721Semaste//------------------------------------------------------------------ 4622254721Semaste// Process STDIO 4623254721Semaste//------------------------------------------------------------------ 4624254721Semaste 4625254721Semastesize_t 4626254721SemasteProcess::GetSTDOUT (char *buf, size_t buf_size, Error &error) 4627254721Semaste{ 4628254721Semaste Mutex::Locker locker(m_stdio_communication_mutex); 4629254721Semaste size_t bytes_available = m_stdout_data.size(); 4630254721Semaste if (bytes_available > 0) 4631254721Semaste { 4632254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4633254721Semaste if (log) 4634254721Semaste log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size); 4635254721Semaste if (bytes_available > buf_size) 4636254721Semaste { 4637254721Semaste memcpy(buf, m_stdout_data.c_str(), buf_size); 4638254721Semaste m_stdout_data.erase(0, buf_size); 4639254721Semaste bytes_available = buf_size; 4640254721Semaste } 4641254721Semaste else 4642254721Semaste { 4643254721Semaste memcpy(buf, m_stdout_data.c_str(), bytes_available); 4644254721Semaste m_stdout_data.clear(); 4645254721Semaste } 4646254721Semaste } 4647254721Semaste return bytes_available; 4648254721Semaste} 4649254721Semaste 4650254721Semaste 4651254721Semastesize_t 4652254721SemasteProcess::GetSTDERR (char *buf, size_t buf_size, Error &error) 4653254721Semaste{ 4654254721Semaste Mutex::Locker locker(m_stdio_communication_mutex); 4655254721Semaste size_t bytes_available = m_stderr_data.size(); 4656254721Semaste if (bytes_available > 0) 4657254721Semaste { 4658254721Semaste Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4659254721Semaste if (log) 4660254721Semaste log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size); 4661254721Semaste if (bytes_available > buf_size) 4662254721Semaste { 4663254721Semaste memcpy(buf, m_stderr_data.c_str(), buf_size); 4664254721Semaste m_stderr_data.erase(0, buf_size); 4665254721Semaste bytes_available = buf_size; 4666254721Semaste } 4667254721Semaste else 4668254721Semaste { 4669254721Semaste memcpy(buf, m_stderr_data.c_str(), bytes_available); 4670254721Semaste m_stderr_data.clear(); 4671254721Semaste } 4672254721Semaste } 4673254721Semaste return bytes_available; 4674254721Semaste} 4675254721Semaste 4676254721Semastevoid 4677254721SemasteProcess::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 4678254721Semaste{ 4679254721Semaste Process *process = (Process *) baton; 4680254721Semaste process->AppendSTDOUT (static_cast<const char *>(src), src_len); 4681254721Semaste} 4682254721Semaste 4683269024Semastevoid 4684269024SemasteProcess::ResetProcessIOHandler () 4685269024Semaste{ 4686269024Semaste m_process_input_reader.reset(); 4687269024Semaste} 4688269024Semaste 4689269024Semaste 4690269024Semasteclass IOHandlerProcessSTDIO : 4691269024Semaste public IOHandler 4692254721Semaste{ 4693269024Semastepublic: 4694269024Semaste IOHandlerProcessSTDIO (Process *process, 4695269024Semaste int write_fd) : 4696269024Semaste IOHandler(process->GetTarget().GetDebugger()), 4697269024Semaste m_process (process), 4698269024Semaste m_read_file (), 4699269024Semaste m_write_file (write_fd, false), 4700269024Semaste m_pipe_read(), 4701269024Semaste m_pipe_write() 4702269024Semaste { 4703269024Semaste m_read_file.SetDescriptor(GetInputFD(), false); 4704269024Semaste } 4705269024Semaste 4706269024Semaste virtual 4707269024Semaste ~IOHandlerProcessSTDIO () 4708269024Semaste { 4709269024Semaste 4710269024Semaste } 4711254721Semaste 4712269024Semaste bool 4713269024Semaste OpenPipes () 4714254721Semaste { 4715269024Semaste if (m_pipe_read.IsValid() && m_pipe_write.IsValid()) 4716269024Semaste return true; 4717269024Semaste 4718269024Semaste int fds[2]; 4719269024Semaste#ifdef _MSC_VER 4720269024Semaste // pipe is not supported on windows so default to a fail condition 4721269024Semaste int err = 1; 4722269024Semaste#else 4723269024Semaste int err = pipe(fds); 4724269024Semaste#endif 4725269024Semaste if (err == 0) 4726254721Semaste { 4727269024Semaste m_pipe_read.SetDescriptor(fds[0], true); 4728269024Semaste m_pipe_write.SetDescriptor(fds[1], true); 4729269024Semaste return true; 4730254721Semaste } 4731269024Semaste return false; 4732269024Semaste } 4733269024Semaste 4734269024Semaste void 4735269024Semaste ClosePipes() 4736269024Semaste { 4737269024Semaste m_pipe_read.Close(); 4738269024Semaste m_pipe_write.Close(); 4739269024Semaste } 4740269024Semaste 4741269024Semaste // Each IOHandler gets to run until it is done. It should read data 4742269024Semaste // from the "in" and place output into "out" and "err and return 4743269024Semaste // when done. 4744269024Semaste virtual void 4745269024Semaste Run () 4746269024Semaste { 4747269024Semaste if (m_read_file.IsValid() && m_write_file.IsValid()) 4748269024Semaste { 4749269024Semaste SetIsDone(false); 4750269024Semaste if (OpenPipes()) 4751269024Semaste { 4752269024Semaste const int read_fd = m_read_file.GetDescriptor(); 4753269024Semaste const int pipe_read_fd = m_pipe_read.GetDescriptor(); 4754269024Semaste TerminalState terminal_state; 4755269024Semaste terminal_state.Save (read_fd, false); 4756269024Semaste Terminal terminal(read_fd); 4757269024Semaste terminal.SetCanonical(false); 4758269024Semaste terminal.SetEcho(false); 4759269024Semaste// FD_ZERO, FD_SET are not supported on windows 4760269024Semaste#ifndef _MSC_VER 4761269024Semaste while (!GetIsDone()) 4762269024Semaste { 4763269024Semaste fd_set read_fdset; 4764269024Semaste FD_ZERO (&read_fdset); 4765269024Semaste FD_SET (read_fd, &read_fdset); 4766269024Semaste FD_SET (pipe_read_fd, &read_fdset); 4767269024Semaste const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1; 4768269024Semaste int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL); 4769269024Semaste if (num_set_fds < 0) 4770269024Semaste { 4771269024Semaste const int select_errno = errno; 4772269024Semaste 4773269024Semaste if (select_errno != EINTR) 4774269024Semaste SetIsDone(true); 4775269024Semaste } 4776269024Semaste else if (num_set_fds > 0) 4777269024Semaste { 4778269024Semaste char ch = 0; 4779269024Semaste size_t n; 4780269024Semaste if (FD_ISSET (read_fd, &read_fdset)) 4781269024Semaste { 4782269024Semaste n = 1; 4783269024Semaste if (m_read_file.Read(&ch, n).Success() && n == 1) 4784269024Semaste { 4785269024Semaste if (m_write_file.Write(&ch, n).Fail() || n != 1) 4786269024Semaste SetIsDone(true); 4787269024Semaste } 4788269024Semaste else 4789269024Semaste SetIsDone(true); 4790269024Semaste } 4791269024Semaste if (FD_ISSET (pipe_read_fd, &read_fdset)) 4792269024Semaste { 4793269024Semaste // Consume the interrupt byte 4794269024Semaste n = 1; 4795269024Semaste m_pipe_read.Read (&ch, n); 4796269024Semaste SetIsDone(true); 4797269024Semaste } 4798269024Semaste } 4799269024Semaste } 4800269024Semaste#endif 4801269024Semaste terminal_state.Restore(); 4802269024Semaste 4803269024Semaste } 4804269024Semaste else 4805269024Semaste SetIsDone(true); 4806269024Semaste } 4807269024Semaste else 4808269024Semaste SetIsDone(true); 4809269024Semaste } 4810269024Semaste 4811269024Semaste // Hide any characters that have been displayed so far so async 4812269024Semaste // output can be displayed. Refresh() will be called after the 4813269024Semaste // output has been displayed. 4814269024Semaste virtual void 4815269024Semaste Hide () 4816269024Semaste { 4817254721Semaste 4818269024Semaste } 4819269024Semaste // Called when the async output has been received in order to update 4820269024Semaste // the input reader (refresh the prompt and redisplay any current 4821269024Semaste // line(s) that are being edited 4822269024Semaste virtual void 4823269024Semaste Refresh () 4824269024Semaste { 4825254721Semaste 4826269024Semaste } 4827269024Semaste 4828269024Semaste virtual void 4829269024Semaste Cancel () 4830269024Semaste { 4831269024Semaste size_t n = 1; 4832269024Semaste char ch = 'q'; 4833269024Semaste m_pipe_write.Write (&ch, n); 4834269024Semaste } 4835269024Semaste 4836269024Semaste virtual void 4837269024Semaste Interrupt () 4838269024Semaste { 4839269024Semaste if (StateIsRunningState(m_process->GetState())) 4840269024Semaste m_process->SendAsyncInterrupt(); 4841269024Semaste } 4842269024Semaste 4843269024Semaste virtual void 4844269024Semaste GotEOF() 4845269024Semaste { 4846254721Semaste 4847254721Semaste } 4848254721Semaste 4849269024Semasteprotected: 4850269024Semaste Process *m_process; 4851269024Semaste File m_read_file; // Read from this file (usually actual STDIN for LLDB 4852269024Semaste File m_write_file; // Write to this file (usually the master pty for getting io to debuggee) 4853269024Semaste File m_pipe_read; 4854269024Semaste File m_pipe_write; 4855269024Semaste 4856269024Semaste}; 4857269024Semaste 4858269024Semastevoid 4859269024SemasteProcess::WatchForSTDIN (IOHandler &io_handler) 4860269024Semaste{ 4861254721Semaste} 4862254721Semaste 4863254721Semastevoid 4864269024SemasteProcess::CancelWatchForSTDIN (bool exited) 4865269024Semaste{ 4866269024Semaste if (m_process_input_reader) 4867269024Semaste { 4868269024Semaste if (exited) 4869269024Semaste m_process_input_reader->SetIsDone(true); 4870269024Semaste m_process_input_reader->Cancel(); 4871269024Semaste } 4872254721Semaste} 4873254721Semaste 4874254721Semastevoid 4875269024SemasteProcess::SetSTDIOFileDescriptor (int fd) 4876254721Semaste{ 4877254721Semaste // First set up the Read Thread for reading/handling process I/O 4878254721Semaste 4879269024Semaste std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true)); 4880254721Semaste 4881254721Semaste if (conn_ap.get()) 4882254721Semaste { 4883254721Semaste m_stdio_communication.SetConnection (conn_ap.release()); 4884254721Semaste if (m_stdio_communication.IsConnected()) 4885254721Semaste { 4886254721Semaste m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 4887254721Semaste m_stdio_communication.StartReadThread(); 4888254721Semaste 4889254721Semaste // Now read thread is set up, set up input reader. 4890254721Semaste 4891254721Semaste if (!m_process_input_reader.get()) 4892269024Semaste m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd)); 4893254721Semaste } 4894254721Semaste } 4895254721Semaste} 4896254721Semaste 4897254721Semastevoid 4898269024SemasteProcess::PushProcessIOHandler () 4899254721Semaste{ 4900269024Semaste IOHandlerSP io_handler_sp (m_process_input_reader); 4901269024Semaste if (io_handler_sp) 4902269024Semaste { 4903269024Semaste io_handler_sp->SetIsDone(false); 4904269024Semaste m_target.GetDebugger().PushIOHandler (io_handler_sp); 4905269024Semaste } 4906254721Semaste} 4907254721Semaste 4908254721Semastevoid 4909269024SemasteProcess::PopProcessIOHandler () 4910254721Semaste{ 4911269024Semaste IOHandlerSP io_handler_sp (m_process_input_reader); 4912269024Semaste if (io_handler_sp) 4913269024Semaste { 4914269024Semaste io_handler_sp->Cancel(); 4915269024Semaste m_target.GetDebugger().PopIOHandler (io_handler_sp); 4916269024Semaste } 4917254721Semaste} 4918254721Semaste 4919254721Semaste// The process needs to know about installed plug-ins 4920254721Semastevoid 4921254721SemasteProcess::SettingsInitialize () 4922254721Semaste{ 4923254721Semaste Thread::SettingsInitialize (); 4924254721Semaste} 4925254721Semaste 4926254721Semastevoid 4927254721SemasteProcess::SettingsTerminate () 4928254721Semaste{ 4929254721Semaste Thread::SettingsTerminate (); 4930254721Semaste} 4931254721Semaste 4932254721SemasteExecutionResults 4933254721SemasteProcess::RunThreadPlan (ExecutionContext &exe_ctx, 4934254721Semaste lldb::ThreadPlanSP &thread_plan_sp, 4935263367Semaste const EvaluateExpressionOptions &options, 4936254721Semaste Stream &errors) 4937254721Semaste{ 4938254721Semaste ExecutionResults return_value = eExecutionSetupError; 4939254721Semaste 4940254721Semaste if (thread_plan_sp.get() == NULL) 4941254721Semaste { 4942254721Semaste errors.Printf("RunThreadPlan called with empty thread plan."); 4943254721Semaste return eExecutionSetupError; 4944254721Semaste } 4945254721Semaste 4946254721Semaste if (!thread_plan_sp->ValidatePlan(NULL)) 4947254721Semaste { 4948254721Semaste errors.Printf ("RunThreadPlan called with an invalid thread plan."); 4949254721Semaste return eExecutionSetupError; 4950254721Semaste } 4951254721Semaste 4952254721Semaste if (exe_ctx.GetProcessPtr() != this) 4953254721Semaste { 4954254721Semaste errors.Printf("RunThreadPlan called on wrong process."); 4955254721Semaste return eExecutionSetupError; 4956254721Semaste } 4957254721Semaste 4958254721Semaste Thread *thread = exe_ctx.GetThreadPtr(); 4959254721Semaste if (thread == NULL) 4960254721Semaste { 4961254721Semaste errors.Printf("RunThreadPlan called with invalid thread."); 4962254721Semaste return eExecutionSetupError; 4963254721Semaste } 4964254721Semaste 4965254721Semaste // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes. 4966254721Semaste // For that to be true the plan can't be private - since private plans suppress themselves in the 4967254721Semaste // GetCompletedPlan call. 4968254721Semaste 4969254721Semaste bool orig_plan_private = thread_plan_sp->GetPrivate(); 4970254721Semaste thread_plan_sp->SetPrivate(false); 4971254721Semaste 4972254721Semaste if (m_private_state.GetValue() != eStateStopped) 4973254721Semaste { 4974254721Semaste errors.Printf ("RunThreadPlan called while the private state was not stopped."); 4975254721Semaste return eExecutionSetupError; 4976254721Semaste } 4977254721Semaste 4978254721Semaste // Save the thread & frame from the exe_ctx for restoration after we run 4979254721Semaste const uint32_t thread_idx_id = thread->GetIndexID(); 4980254721Semaste StackFrameSP selected_frame_sp = thread->GetSelectedFrame(); 4981254721Semaste if (!selected_frame_sp) 4982254721Semaste { 4983254721Semaste thread->SetSelectedFrame(0); 4984254721Semaste selected_frame_sp = thread->GetSelectedFrame(); 4985254721Semaste if (!selected_frame_sp) 4986254721Semaste { 4987254721Semaste errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id); 4988254721Semaste return eExecutionSetupError; 4989254721Semaste } 4990254721Semaste } 4991254721Semaste 4992254721Semaste StackID ctx_frame_id = selected_frame_sp->GetStackID(); 4993254721Semaste 4994254721Semaste // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either, 4995254721Semaste // so we should arrange to reset them as well. 4996254721Semaste 4997254721Semaste lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4998254721Semaste 4999254721Semaste uint32_t selected_tid; 5000254721Semaste StackID selected_stack_id; 5001254721Semaste if (selected_thread_sp) 5002254721Semaste { 5003254721Semaste selected_tid = selected_thread_sp->GetIndexID(); 5004254721Semaste selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 5005254721Semaste } 5006254721Semaste else 5007254721Semaste { 5008254721Semaste selected_tid = LLDB_INVALID_THREAD_ID; 5009254721Semaste } 5010254721Semaste 5011254721Semaste lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD; 5012254721Semaste lldb::StateType old_state; 5013254721Semaste lldb::ThreadPlanSP stopper_base_plan_sp; 5014254721Semaste 5015254721Semaste Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 5016254721Semaste if (Host::GetCurrentThread() == m_private_state_thread) 5017254721Semaste { 5018254721Semaste // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since 5019254721Semaste // we are the thread that is generating public events. 5020254721Semaste // The simplest thing to do is to spin up a temporary thread to handle private state thread events while 5021254721Semaste // we are fielding public events here. 5022254721Semaste if (log) 5023254721Semaste log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events."); 5024254721Semaste 5025254721Semaste 5026254721Semaste backup_private_state_thread = m_private_state_thread; 5027254721Semaste 5028254721Semaste // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop, 5029254721Semaste // returning control here. 5030254721Semaste // But in the normal course of things, the plan above us on the stack would be given a shot at the stop 5031254721Semaste // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack 5032254721Semaste // before the plan we want to run. Since base plans always stop and return control to the user, that will 5033254721Semaste // do just what we want. 5034254721Semaste stopper_base_plan_sp.reset(new ThreadPlanBase (*thread)); 5035254721Semaste thread->QueueThreadPlan (stopper_base_plan_sp, false); 5036254721Semaste // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly. 5037254721Semaste old_state = m_public_state.GetValue(); 5038254721Semaste m_public_state.SetValueNoLock(eStateStopped); 5039254721Semaste 5040254721Semaste // Now spin up the private state thread: 5041254721Semaste StartPrivateStateThread(true); 5042254721Semaste } 5043254721Semaste 5044254721Semaste thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense? 5045254721Semaste 5046263367Semaste if (options.GetDebug()) 5047263367Semaste { 5048263367Semaste // In this case, we aren't actually going to run, we just want to stop right away. 5049263367Semaste // Flush this thread so we will refetch the stacks and show the correct backtrace. 5050263367Semaste // FIXME: To make this prettier we should invent some stop reason for this, but that 5051263367Semaste // is only cosmetic, and this functionality is only of use to lldb developers who can 5052263367Semaste // live with not pretty... 5053263367Semaste thread->Flush(); 5054263367Semaste return eExecutionStoppedForDebug; 5055263367Semaste } 5056263367Semaste 5057254721Semaste Listener listener("lldb.process.listener.run-thread-plan"); 5058254721Semaste 5059254721Semaste lldb::EventSP event_to_broadcast_sp; 5060254721Semaste 5061254721Semaste { 5062254721Semaste // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get 5063254721Semaste // restored on exit to the function. 5064254721Semaste // 5065254721Semaste // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event 5066254721Semaste // is put into event_to_broadcast_sp for rebroadcasting. 5067254721Semaste 5068254721Semaste ProcessEventHijacker run_thread_plan_hijacker (*this, &listener); 5069254721Semaste 5070254721Semaste if (log) 5071254721Semaste { 5072254721Semaste StreamString s; 5073254721Semaste thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 5074254721Semaste log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".", 5075254721Semaste thread->GetIndexID(), 5076254721Semaste thread->GetID(), 5077254721Semaste s.GetData()); 5078254721Semaste } 5079254721Semaste 5080254721Semaste bool got_event; 5081254721Semaste lldb::EventSP event_sp; 5082254721Semaste lldb::StateType stop_state = lldb::eStateInvalid; 5083254721Semaste 5084254721Semaste TimeValue* timeout_ptr = NULL; 5085254721Semaste TimeValue real_timeout; 5086254721Semaste 5087254721Semaste bool before_first_timeout = true; // This is set to false the first time that we have to halt the target. 5088254721Semaste bool do_resume = true; 5089254721Semaste bool handle_running_event = true; 5090254721Semaste const uint64_t default_one_thread_timeout_usec = 250000; 5091254721Semaste 5092254721Semaste // This is just for accounting: 5093254721Semaste uint32_t num_resumes = 0; 5094254721Semaste 5095254721Semaste TimeValue one_thread_timeout = TimeValue::Now(); 5096254721Semaste TimeValue final_timeout = one_thread_timeout; 5097254721Semaste 5098263367Semaste uint32_t timeout_usec = options.GetTimeoutUsec(); 5099263367Semaste if (options.GetTryAllThreads()) 5100254721Semaste { 5101254721Semaste // If we are running all threads then we take half the time to run all threads, bounded by 5102254721Semaste // .25 sec. 5103263367Semaste if (options.GetTimeoutUsec() == 0) 5104254721Semaste one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec); 5105254721Semaste else 5106254721Semaste { 5107254721Semaste uint64_t computed_timeout = timeout_usec / 2; 5108254721Semaste if (computed_timeout > default_one_thread_timeout_usec) 5109254721Semaste computed_timeout = default_one_thread_timeout_usec; 5110254721Semaste one_thread_timeout.OffsetWithMicroSeconds(computed_timeout); 5111254721Semaste } 5112254721Semaste final_timeout.OffsetWithMicroSeconds (timeout_usec); 5113254721Semaste } 5114254721Semaste else 5115254721Semaste { 5116254721Semaste if (timeout_usec != 0) 5117254721Semaste final_timeout.OffsetWithMicroSeconds(timeout_usec); 5118254721Semaste } 5119254721Semaste 5120269024Semaste // This isn't going to work if there are unfetched events on the queue. 5121269024Semaste // Are there cases where we might want to run the remaining events here, and then try to 5122269024Semaste // call the function? That's probably being too tricky for our own good. 5123269024Semaste 5124269024Semaste Event *other_events = listener.PeekAtNextEvent(); 5125269024Semaste if (other_events != NULL) 5126269024Semaste { 5127269024Semaste errors.Printf("Calling RunThreadPlan with pending events on the queue."); 5128269024Semaste return eExecutionSetupError; 5129269024Semaste } 5130269024Semaste 5131269024Semaste // We also need to make sure that the next event is delivered. We might be calling a function as part of 5132269024Semaste // a thread plan, in which case the last delivered event could be the running event, and we don't want 5133269024Semaste // event coalescing to cause us to lose OUR running event... 5134269024Semaste ForceNextEventDelivery(); 5135269024Semaste 5136254721Semaste // This while loop must exit out the bottom, there's cleanup that we need to do when we are done. 5137254721Semaste // So don't call return anywhere within it. 5138254721Semaste 5139254721Semaste while (1) 5140254721Semaste { 5141254721Semaste // We usually want to resume the process if we get to the top of the loop. 5142254721Semaste // The only exception is if we get two running events with no intervening 5143254721Semaste // stop, which can happen, we will just wait for then next stop event. 5144254721Semaste if (log) 5145254721Semaste log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.", 5146254721Semaste do_resume, 5147254721Semaste handle_running_event, 5148254721Semaste before_first_timeout); 5149254721Semaste 5150254721Semaste if (do_resume || handle_running_event) 5151254721Semaste { 5152254721Semaste // Do the initial resume and wait for the running event before going further. 5153254721Semaste 5154254721Semaste if (do_resume) 5155254721Semaste { 5156254721Semaste num_resumes++; 5157254721Semaste Error resume_error = PrivateResume (); 5158254721Semaste if (!resume_error.Success()) 5159254721Semaste { 5160254721Semaste errors.Printf("Error resuming inferior the %d time: \"%s\".\n", 5161254721Semaste num_resumes, 5162254721Semaste resume_error.AsCString()); 5163254721Semaste return_value = eExecutionSetupError; 5164254721Semaste break; 5165254721Semaste } 5166254721Semaste } 5167254721Semaste 5168254721Semaste TimeValue resume_timeout = TimeValue::Now(); 5169254721Semaste resume_timeout.OffsetWithMicroSeconds(500000); 5170254721Semaste 5171254721Semaste got_event = listener.WaitForEvent(&resume_timeout, event_sp); 5172254721Semaste if (!got_event) 5173254721Semaste { 5174254721Semaste if (log) 5175254721Semaste log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.", 5176254721Semaste num_resumes); 5177254721Semaste 5178254721Semaste errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes); 5179254721Semaste return_value = eExecutionSetupError; 5180254721Semaste break; 5181254721Semaste } 5182254721Semaste 5183254721Semaste stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5184254721Semaste 5185254721Semaste if (stop_state != eStateRunning) 5186254721Semaste { 5187254721Semaste bool restarted = false; 5188254721Semaste 5189254721Semaste if (stop_state == eStateStopped) 5190254721Semaste { 5191254721Semaste restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()); 5192254721Semaste if (log) 5193254721Semaste log->Printf("Process::RunThreadPlan(): didn't get running event after " 5194254721Semaste "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).", 5195254721Semaste num_resumes, 5196254721Semaste StateAsCString(stop_state), 5197254721Semaste restarted, 5198254721Semaste do_resume, 5199254721Semaste handle_running_event); 5200254721Semaste } 5201254721Semaste 5202254721Semaste if (restarted) 5203254721Semaste { 5204254721Semaste // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted 5205254721Semaste // event here. But if I do, the best thing is to Halt and then get out of here. 5206254721Semaste Halt(); 5207254721Semaste } 5208254721Semaste 5209254721Semaste errors.Printf("Didn't get running event after initial resume, got %s instead.", 5210254721Semaste StateAsCString(stop_state)); 5211254721Semaste return_value = eExecutionSetupError; 5212254721Semaste break; 5213254721Semaste } 5214254721Semaste 5215254721Semaste if (log) 5216254721Semaste log->PutCString ("Process::RunThreadPlan(): resuming succeeded."); 5217254721Semaste // We need to call the function synchronously, so spin waiting for it to return. 5218254721Semaste // If we get interrupted while executing, we're going to lose our context, and 5219254721Semaste // won't be able to gather the result at this point. 5220254721Semaste // We set the timeout AFTER the resume, since the resume takes some time and we 5221254721Semaste // don't want to charge that to the timeout. 5222254721Semaste } 5223254721Semaste else 5224254721Semaste { 5225254721Semaste if (log) 5226254721Semaste log->PutCString ("Process::RunThreadPlan(): waiting for next event."); 5227254721Semaste } 5228254721Semaste 5229254721Semaste if (before_first_timeout) 5230254721Semaste { 5231263367Semaste if (options.GetTryAllThreads()) 5232254721Semaste timeout_ptr = &one_thread_timeout; 5233254721Semaste else 5234254721Semaste { 5235254721Semaste if (timeout_usec == 0) 5236254721Semaste timeout_ptr = NULL; 5237254721Semaste else 5238254721Semaste timeout_ptr = &final_timeout; 5239254721Semaste } 5240254721Semaste } 5241254721Semaste else 5242254721Semaste { 5243254721Semaste if (timeout_usec == 0) 5244254721Semaste timeout_ptr = NULL; 5245254721Semaste else 5246254721Semaste timeout_ptr = &final_timeout; 5247254721Semaste } 5248254721Semaste 5249254721Semaste do_resume = true; 5250254721Semaste handle_running_event = true; 5251254721Semaste 5252254721Semaste // Now wait for the process to stop again: 5253254721Semaste event_sp.reset(); 5254254721Semaste 5255254721Semaste if (log) 5256254721Semaste { 5257254721Semaste if (timeout_ptr) 5258254721Semaste { 5259254721Semaste log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64, 5260254721Semaste TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(), 5261254721Semaste timeout_ptr->GetAsMicroSecondsSinceJan1_1970()); 5262254721Semaste } 5263254721Semaste else 5264254721Semaste { 5265254721Semaste log->Printf ("Process::RunThreadPlan(): about to wait forever."); 5266254721Semaste } 5267254721Semaste } 5268254721Semaste 5269254721Semaste got_event = listener.WaitForEvent (timeout_ptr, event_sp); 5270254721Semaste 5271254721Semaste if (got_event) 5272254721Semaste { 5273254721Semaste if (event_sp.get()) 5274254721Semaste { 5275254721Semaste bool keep_going = false; 5276254721Semaste if (event_sp->GetType() == eBroadcastBitInterrupt) 5277254721Semaste { 5278254721Semaste Halt(); 5279254721Semaste return_value = eExecutionInterrupted; 5280254721Semaste errors.Printf ("Execution halted by user interrupt."); 5281254721Semaste if (log) 5282254721Semaste log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting."); 5283254721Semaste break; 5284254721Semaste } 5285254721Semaste else 5286254721Semaste { 5287254721Semaste stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5288254721Semaste if (log) 5289254721Semaste log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state)); 5290254721Semaste 5291254721Semaste switch (stop_state) 5292254721Semaste { 5293254721Semaste case lldb::eStateStopped: 5294254721Semaste { 5295254721Semaste // We stopped, figure out what we are going to do now. 5296254721Semaste ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id); 5297254721Semaste if (!thread_sp) 5298254721Semaste { 5299254721Semaste // Ooh, our thread has vanished. Unlikely that this was successful execution... 5300254721Semaste if (log) 5301254721Semaste log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id); 5302254721Semaste return_value = eExecutionInterrupted; 5303254721Semaste } 5304254721Semaste else 5305254721Semaste { 5306254721Semaste // If we were restarted, we just need to go back up to fetch another event. 5307254721Semaste if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 5308254721Semaste { 5309254721Semaste if (log) 5310254721Semaste { 5311254721Semaste log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting."); 5312254721Semaste } 5313254721Semaste keep_going = true; 5314254721Semaste do_resume = false; 5315254721Semaste handle_running_event = true; 5316254721Semaste 5317254721Semaste } 5318254721Semaste else 5319254721Semaste { 5320254721Semaste 5321254721Semaste StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 5322254721Semaste StopReason stop_reason = eStopReasonInvalid; 5323254721Semaste if (stop_info_sp) 5324254721Semaste stop_reason = stop_info_sp->GetStopReason(); 5325254721Semaste 5326254721Semaste 5327254721Semaste // FIXME: We only check if the stop reason is plan complete, should we make sure that 5328254721Semaste // it is OUR plan that is complete? 5329254721Semaste if (stop_reason == eStopReasonPlanComplete) 5330254721Semaste { 5331254721Semaste if (log) 5332254721Semaste log->PutCString ("Process::RunThreadPlan(): execution completed successfully."); 5333254721Semaste // Now mark this plan as private so it doesn't get reported as the stop reason 5334254721Semaste // after this point. 5335254721Semaste if (thread_plan_sp) 5336254721Semaste thread_plan_sp->SetPrivate (orig_plan_private); 5337254721Semaste return_value = eExecutionCompleted; 5338254721Semaste } 5339254721Semaste else 5340254721Semaste { 5341254721Semaste // Something restarted the target, so just wait for it to stop for real. 5342254721Semaste if (stop_reason == eStopReasonBreakpoint) 5343254721Semaste { 5344254721Semaste if (log) 5345254721Semaste log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription()); 5346254721Semaste return_value = eExecutionHitBreakpoint; 5347263367Semaste if (!options.DoesIgnoreBreakpoints()) 5348254721Semaste { 5349254721Semaste event_to_broadcast_sp = event_sp; 5350254721Semaste } 5351254721Semaste } 5352254721Semaste else 5353254721Semaste { 5354254721Semaste if (log) 5355254721Semaste log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete."); 5356263367Semaste if (!options.DoesUnwindOnError()) 5357254721Semaste event_to_broadcast_sp = event_sp; 5358254721Semaste return_value = eExecutionInterrupted; 5359254721Semaste } 5360254721Semaste } 5361254721Semaste } 5362254721Semaste } 5363254721Semaste } 5364254721Semaste break; 5365254721Semaste 5366254721Semaste case lldb::eStateRunning: 5367254721Semaste // This shouldn't really happen, but sometimes we do get two running events without an 5368254721Semaste // intervening stop, and in that case we should just go back to waiting for the stop. 5369254721Semaste do_resume = false; 5370254721Semaste keep_going = true; 5371254721Semaste handle_running_event = false; 5372254721Semaste break; 5373254721Semaste 5374254721Semaste default: 5375254721Semaste if (log) 5376254721Semaste log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state)); 5377254721Semaste 5378254721Semaste if (stop_state == eStateExited) 5379254721Semaste event_to_broadcast_sp = event_sp; 5380254721Semaste 5381254721Semaste errors.Printf ("Execution stopped with unexpected state.\n"); 5382254721Semaste return_value = eExecutionInterrupted; 5383254721Semaste break; 5384254721Semaste } 5385254721Semaste } 5386254721Semaste 5387254721Semaste if (keep_going) 5388254721Semaste continue; 5389254721Semaste else 5390254721Semaste break; 5391254721Semaste } 5392254721Semaste else 5393254721Semaste { 5394254721Semaste if (log) 5395254721Semaste log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd..."); 5396254721Semaste return_value = eExecutionInterrupted; 5397254721Semaste break; 5398254721Semaste } 5399254721Semaste } 5400254721Semaste else 5401254721Semaste { 5402254721Semaste // If we didn't get an event that means we've timed out... 5403254721Semaste // We will interrupt the process here. Depending on what we were asked to do we will 5404254721Semaste // either exit, or try with all threads running for the same timeout. 5405254721Semaste 5406254721Semaste if (log) { 5407263367Semaste if (options.GetTryAllThreads()) 5408254721Semaste { 5409254721Semaste uint64_t remaining_time = final_timeout - TimeValue::Now(); 5410254721Semaste if (before_first_timeout) 5411254721Semaste log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, " 5412263363Semaste "running till for %" PRIu64 " usec with all threads enabled.", 5413254721Semaste remaining_time); 5414254721Semaste else 5415254721Semaste log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled " 5416263363Semaste "and timeout: %u timed out, abandoning execution.", 5417254721Semaste timeout_usec); 5418254721Semaste } 5419254721Semaste else 5420263363Semaste log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, " 5421254721Semaste "abandoning execution.", 5422254721Semaste timeout_usec); 5423254721Semaste } 5424254721Semaste 5425254721Semaste // It is possible that between the time we issued the Halt, and we get around to calling Halt the target 5426254721Semaste // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event. 5427254721Semaste // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In 5428254721Semaste // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's 5429254721Semaste // stopped event. That's what this while loop does. 5430254721Semaste 5431254721Semaste bool back_to_top = true; 5432254721Semaste uint32_t try_halt_again = 0; 5433254721Semaste bool do_halt = true; 5434254721Semaste const uint32_t num_retries = 5; 5435254721Semaste while (try_halt_again < num_retries) 5436254721Semaste { 5437254721Semaste Error halt_error; 5438254721Semaste if (do_halt) 5439254721Semaste { 5440254721Semaste if (log) 5441254721Semaste log->Printf ("Process::RunThreadPlan(): Running Halt."); 5442254721Semaste halt_error = Halt(); 5443254721Semaste } 5444254721Semaste if (halt_error.Success()) 5445254721Semaste { 5446254721Semaste if (log) 5447254721Semaste log->PutCString ("Process::RunThreadPlan(): Halt succeeded."); 5448254721Semaste 5449254721Semaste real_timeout = TimeValue::Now(); 5450254721Semaste real_timeout.OffsetWithMicroSeconds(500000); 5451254721Semaste 5452254721Semaste got_event = listener.WaitForEvent(&real_timeout, event_sp); 5453254721Semaste 5454254721Semaste if (got_event) 5455254721Semaste { 5456254721Semaste stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5457254721Semaste if (log) 5458254721Semaste { 5459254721Semaste log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state)); 5460254721Semaste if (stop_state == lldb::eStateStopped 5461254721Semaste && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 5462254721Semaste log->PutCString (" Event was the Halt interruption event."); 5463254721Semaste } 5464254721Semaste 5465254721Semaste if (stop_state == lldb::eStateStopped) 5466254721Semaste { 5467254721Semaste // Between the time we initiated the Halt and the time we delivered it, the process could have 5468254721Semaste // already finished its job. Check that here: 5469254721Semaste 5470254721Semaste if (thread->IsThreadPlanDone (thread_plan_sp.get())) 5471254721Semaste { 5472254721Semaste if (log) 5473254721Semaste log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. " 5474254721Semaste "Exiting wait loop."); 5475254721Semaste return_value = eExecutionCompleted; 5476254721Semaste back_to_top = false; 5477254721Semaste break; 5478254721Semaste } 5479254721Semaste 5480254721Semaste if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 5481254721Semaste { 5482254721Semaste if (log) 5483254721Semaste log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... " 5484254721Semaste "Exiting wait loop."); 5485254721Semaste try_halt_again++; 5486254721Semaste do_halt = false; 5487254721Semaste continue; 5488254721Semaste } 5489254721Semaste 5490263367Semaste if (!options.GetTryAllThreads()) 5491254721Semaste { 5492254721Semaste if (log) 5493254721Semaste log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting."); 5494254721Semaste return_value = eExecutionInterrupted; 5495254721Semaste back_to_top = false; 5496254721Semaste break; 5497254721Semaste } 5498254721Semaste 5499254721Semaste if (before_first_timeout) 5500254721Semaste { 5501254721Semaste // Set all the other threads to run, and return to the top of the loop, which will continue; 5502254721Semaste before_first_timeout = false; 5503254721Semaste thread_plan_sp->SetStopOthers (false); 5504254721Semaste if (log) 5505254721Semaste log->PutCString ("Process::RunThreadPlan(): about to resume."); 5506254721Semaste 5507254721Semaste back_to_top = true; 5508254721Semaste break; 5509254721Semaste } 5510254721Semaste else 5511254721Semaste { 5512254721Semaste // Running all threads failed, so return Interrupted. 5513254721Semaste if (log) 5514254721Semaste log->PutCString("Process::RunThreadPlan(): running all threads timed out."); 5515254721Semaste return_value = eExecutionInterrupted; 5516254721Semaste back_to_top = false; 5517254721Semaste break; 5518254721Semaste } 5519254721Semaste } 5520254721Semaste } 5521254721Semaste else 5522254721Semaste { if (log) 5523254721Semaste log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. " 5524254721Semaste "I'm getting out of here passing Interrupted."); 5525254721Semaste return_value = eExecutionInterrupted; 5526254721Semaste back_to_top = false; 5527254721Semaste break; 5528254721Semaste } 5529254721Semaste } 5530254721Semaste else 5531254721Semaste { 5532254721Semaste try_halt_again++; 5533254721Semaste continue; 5534254721Semaste } 5535254721Semaste } 5536254721Semaste 5537254721Semaste if (!back_to_top || try_halt_again > num_retries) 5538254721Semaste break; 5539254721Semaste else 5540254721Semaste continue; 5541254721Semaste } 5542254721Semaste } // END WAIT LOOP 5543254721Semaste 5544254721Semaste // If we had to start up a temporary private state thread to run this thread plan, shut it down now. 5545254721Semaste if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread)) 5546254721Semaste { 5547254721Semaste StopPrivateStateThread(); 5548254721Semaste Error error; 5549254721Semaste m_private_state_thread = backup_private_state_thread; 5550254721Semaste if (stopper_base_plan_sp) 5551254721Semaste { 5552254721Semaste thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 5553254721Semaste } 5554254721Semaste m_public_state.SetValueNoLock(old_state); 5555254721Semaste 5556254721Semaste } 5557254721Semaste 5558254721Semaste // Restore the thread state if we are going to discard the plan execution. There are three cases where this 5559254721Semaste // could happen: 5560254721Semaste // 1) The execution successfully completed 5561254721Semaste // 2) We hit a breakpoint, and ignore_breakpoints was true 5562254721Semaste // 3) We got some other error, and discard_on_error was true 5563263367Semaste bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError()) 5564263367Semaste || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints()); 5565254721Semaste 5566254721Semaste if (return_value == eExecutionCompleted 5567254721Semaste || should_unwind) 5568254721Semaste { 5569254721Semaste thread_plan_sp->RestoreThreadState(); 5570254721Semaste } 5571254721Semaste 5572254721Semaste // Now do some processing on the results of the run: 5573254721Semaste if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint) 5574254721Semaste { 5575254721Semaste if (log) 5576254721Semaste { 5577254721Semaste StreamString s; 5578254721Semaste if (event_sp) 5579254721Semaste event_sp->Dump (&s); 5580254721Semaste else 5581254721Semaste { 5582254721Semaste log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL."); 5583254721Semaste } 5584254721Semaste 5585254721Semaste StreamString ts; 5586254721Semaste 5587254721Semaste const char *event_explanation = NULL; 5588254721Semaste 5589254721Semaste do 5590254721Semaste { 5591254721Semaste if (!event_sp) 5592254721Semaste { 5593254721Semaste event_explanation = "<no event>"; 5594254721Semaste break; 5595254721Semaste } 5596254721Semaste else if (event_sp->GetType() == eBroadcastBitInterrupt) 5597254721Semaste { 5598254721Semaste event_explanation = "<user interrupt>"; 5599254721Semaste break; 5600254721Semaste } 5601254721Semaste else 5602254721Semaste { 5603254721Semaste const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get()); 5604254721Semaste 5605254721Semaste if (!event_data) 5606254721Semaste { 5607254721Semaste event_explanation = "<no event data>"; 5608254721Semaste break; 5609254721Semaste } 5610254721Semaste 5611254721Semaste Process *process = event_data->GetProcessSP().get(); 5612254721Semaste 5613254721Semaste if (!process) 5614254721Semaste { 5615254721Semaste event_explanation = "<no process>"; 5616254721Semaste break; 5617254721Semaste } 5618254721Semaste 5619254721Semaste ThreadList &thread_list = process->GetThreadList(); 5620254721Semaste 5621254721Semaste uint32_t num_threads = thread_list.GetSize(); 5622254721Semaste uint32_t thread_index; 5623254721Semaste 5624254721Semaste ts.Printf("<%u threads> ", num_threads); 5625254721Semaste 5626254721Semaste for (thread_index = 0; 5627254721Semaste thread_index < num_threads; 5628254721Semaste ++thread_index) 5629254721Semaste { 5630254721Semaste Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 5631254721Semaste 5632254721Semaste if (!thread) 5633254721Semaste { 5634254721Semaste ts.Printf("<?> "); 5635254721Semaste continue; 5636254721Semaste } 5637254721Semaste 5638254721Semaste ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID()); 5639254721Semaste RegisterContext *register_context = thread->GetRegisterContext().get(); 5640254721Semaste 5641254721Semaste if (register_context) 5642254721Semaste ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC()); 5643254721Semaste else 5644254721Semaste ts.Printf("[ip unknown] "); 5645254721Semaste 5646254721Semaste lldb::StopInfoSP stop_info_sp = thread->GetStopInfo(); 5647254721Semaste if (stop_info_sp) 5648254721Semaste { 5649254721Semaste const char *stop_desc = stop_info_sp->GetDescription(); 5650254721Semaste if (stop_desc) 5651254721Semaste ts.PutCString (stop_desc); 5652254721Semaste } 5653254721Semaste ts.Printf(">"); 5654254721Semaste } 5655254721Semaste 5656254721Semaste event_explanation = ts.GetData(); 5657254721Semaste } 5658254721Semaste } while (0); 5659254721Semaste 5660254721Semaste if (event_explanation) 5661254721Semaste log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation); 5662254721Semaste else 5663254721Semaste log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData()); 5664254721Semaste } 5665254721Semaste 5666263363Semaste if (should_unwind) 5667254721Semaste { 5668254721Semaste if (log) 5669254721Semaste log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get()); 5670254721Semaste thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 5671254721Semaste thread_plan_sp->SetPrivate (orig_plan_private); 5672254721Semaste } 5673254721Semaste else 5674254721Semaste { 5675254721Semaste if (log) 5676254721Semaste log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get()); 5677254721Semaste } 5678254721Semaste } 5679254721Semaste else if (return_value == eExecutionSetupError) 5680254721Semaste { 5681254721Semaste if (log) 5682254721Semaste log->PutCString("Process::RunThreadPlan(): execution set up error."); 5683254721Semaste 5684263367Semaste if (options.DoesUnwindOnError()) 5685254721Semaste { 5686254721Semaste thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 5687254721Semaste thread_plan_sp->SetPrivate (orig_plan_private); 5688254721Semaste } 5689254721Semaste } 5690254721Semaste else 5691254721Semaste { 5692254721Semaste if (thread->IsThreadPlanDone (thread_plan_sp.get())) 5693254721Semaste { 5694254721Semaste if (log) 5695254721Semaste log->PutCString("Process::RunThreadPlan(): thread plan is done"); 5696254721Semaste return_value = eExecutionCompleted; 5697254721Semaste } 5698254721Semaste else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get())) 5699254721Semaste { 5700254721Semaste if (log) 5701254721Semaste log->PutCString("Process::RunThreadPlan(): thread plan was discarded"); 5702254721Semaste return_value = eExecutionDiscarded; 5703254721Semaste } 5704254721Semaste else 5705254721Semaste { 5706254721Semaste if (log) 5707254721Semaste log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course"); 5708263367Semaste if (options.DoesUnwindOnError() && thread_plan_sp) 5709254721Semaste { 5710254721Semaste if (log) 5711254721Semaste log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set."); 5712254721Semaste thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 5713254721Semaste thread_plan_sp->SetPrivate (orig_plan_private); 5714254721Semaste } 5715254721Semaste } 5716254721Semaste } 5717254721Semaste 5718254721Semaste // Thread we ran the function in may have gone away because we ran the target 5719254721Semaste // Check that it's still there, and if it is put it back in the context. Also restore the 5720254721Semaste // frame in the context if it is still present. 5721254721Semaste thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 5722254721Semaste if (thread) 5723254721Semaste { 5724254721Semaste exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id)); 5725254721Semaste } 5726254721Semaste 5727254721Semaste // Also restore the current process'es selected frame & thread, since this function calling may 5728254721Semaste // be done behind the user's back. 5729254721Semaste 5730254721Semaste if (selected_tid != LLDB_INVALID_THREAD_ID) 5731254721Semaste { 5732254721Semaste if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid()) 5733254721Semaste { 5734254721Semaste // We were able to restore the selected thread, now restore the frame: 5735254721Semaste Mutex::Locker lock(GetThreadList().GetMutex()); 5736254721Semaste StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id); 5737254721Semaste if (old_frame_sp) 5738254721Semaste GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get()); 5739254721Semaste } 5740254721Semaste } 5741254721Semaste } 5742254721Semaste 5743254721Semaste // If the process exited during the run of the thread plan, notify everyone. 5744254721Semaste 5745254721Semaste if (event_to_broadcast_sp) 5746254721Semaste { 5747254721Semaste if (log) 5748254721Semaste log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 5749254721Semaste BroadcastEvent(event_to_broadcast_sp); 5750254721Semaste } 5751254721Semaste 5752254721Semaste return return_value; 5753254721Semaste} 5754254721Semaste 5755254721Semasteconst char * 5756254721SemasteProcess::ExecutionResultAsCString (ExecutionResults result) 5757254721Semaste{ 5758254721Semaste const char *result_name; 5759254721Semaste 5760254721Semaste switch (result) 5761254721Semaste { 5762254721Semaste case eExecutionCompleted: 5763254721Semaste result_name = "eExecutionCompleted"; 5764254721Semaste break; 5765254721Semaste case eExecutionDiscarded: 5766254721Semaste result_name = "eExecutionDiscarded"; 5767254721Semaste break; 5768254721Semaste case eExecutionInterrupted: 5769254721Semaste result_name = "eExecutionInterrupted"; 5770254721Semaste break; 5771254721Semaste case eExecutionHitBreakpoint: 5772254721Semaste result_name = "eExecutionHitBreakpoint"; 5773254721Semaste break; 5774254721Semaste case eExecutionSetupError: 5775254721Semaste result_name = "eExecutionSetupError"; 5776254721Semaste break; 5777254721Semaste case eExecutionTimedOut: 5778254721Semaste result_name = "eExecutionTimedOut"; 5779254721Semaste break; 5780263367Semaste case eExecutionStoppedForDebug: 5781263367Semaste result_name = "eExecutionStoppedForDebug"; 5782263367Semaste break; 5783254721Semaste } 5784254721Semaste return result_name; 5785254721Semaste} 5786254721Semaste 5787254721Semastevoid 5788254721SemasteProcess::GetStatus (Stream &strm) 5789254721Semaste{ 5790254721Semaste const StateType state = GetState(); 5791254721Semaste if (StateIsStoppedState(state, false)) 5792254721Semaste { 5793254721Semaste if (state == eStateExited) 5794254721Semaste { 5795254721Semaste int exit_status = GetExitStatus(); 5796254721Semaste const char *exit_description = GetExitDescription(); 5797254721Semaste strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n", 5798254721Semaste GetID(), 5799254721Semaste exit_status, 5800254721Semaste exit_status, 5801254721Semaste exit_description ? exit_description : ""); 5802254721Semaste } 5803254721Semaste else 5804254721Semaste { 5805254721Semaste if (state == eStateConnected) 5806254721Semaste strm.Printf ("Connected to remote target.\n"); 5807254721Semaste else 5808254721Semaste strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state)); 5809254721Semaste } 5810254721Semaste } 5811254721Semaste else 5812254721Semaste { 5813254721Semaste strm.Printf ("Process %" PRIu64 " is running.\n", GetID()); 5814254721Semaste } 5815254721Semaste} 5816254721Semaste 5817254721Semastesize_t 5818254721SemasteProcess::GetThreadStatus (Stream &strm, 5819254721Semaste bool only_threads_with_stop_reason, 5820254721Semaste uint32_t start_frame, 5821254721Semaste uint32_t num_frames, 5822254721Semaste uint32_t num_frames_with_source) 5823254721Semaste{ 5824254721Semaste size_t num_thread_infos_dumped = 0; 5825254721Semaste 5826254721Semaste Mutex::Locker locker (GetThreadList().GetMutex()); 5827254721Semaste const size_t num_threads = GetThreadList().GetSize(); 5828254721Semaste for (uint32_t i = 0; i < num_threads; i++) 5829254721Semaste { 5830254721Semaste Thread *thread = GetThreadList().GetThreadAtIndex(i).get(); 5831254721Semaste if (thread) 5832254721Semaste { 5833254721Semaste if (only_threads_with_stop_reason) 5834254721Semaste { 5835254721Semaste StopInfoSP stop_info_sp = thread->GetStopInfo(); 5836254721Semaste if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid()) 5837254721Semaste continue; 5838254721Semaste } 5839254721Semaste thread->GetStatus (strm, 5840254721Semaste start_frame, 5841254721Semaste num_frames, 5842254721Semaste num_frames_with_source); 5843254721Semaste ++num_thread_infos_dumped; 5844254721Semaste } 5845254721Semaste } 5846254721Semaste return num_thread_infos_dumped; 5847254721Semaste} 5848254721Semaste 5849254721Semastevoid 5850254721SemasteProcess::AddInvalidMemoryRegion (const LoadRange ®ion) 5851254721Semaste{ 5852254721Semaste m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5853254721Semaste} 5854254721Semaste 5855254721Semastebool 5856254721SemasteProcess::RemoveInvalidMemoryRange (const LoadRange ®ion) 5857254721Semaste{ 5858254721Semaste return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5859254721Semaste} 5860254721Semaste 5861254721Semastevoid 5862254721SemasteProcess::AddPreResumeAction (PreResumeActionCallback callback, void *baton) 5863254721Semaste{ 5864254721Semaste m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton)); 5865254721Semaste} 5866254721Semaste 5867254721Semastebool 5868254721SemasteProcess::RunPreResumeActions () 5869254721Semaste{ 5870254721Semaste bool result = true; 5871254721Semaste while (!m_pre_resume_actions.empty()) 5872254721Semaste { 5873254721Semaste struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5874254721Semaste m_pre_resume_actions.pop_back(); 5875254721Semaste bool this_result = action.callback (action.baton); 5876254721Semaste if (result == true) result = this_result; 5877254721Semaste } 5878254721Semaste return result; 5879254721Semaste} 5880254721Semaste 5881254721Semastevoid 5882254721SemasteProcess::ClearPreResumeActions () 5883254721Semaste{ 5884254721Semaste m_pre_resume_actions.clear(); 5885254721Semaste} 5886254721Semaste 5887254721Semastevoid 5888254721SemasteProcess::Flush () 5889254721Semaste{ 5890254721Semaste m_thread_list.Flush(); 5891269024Semaste m_extended_thread_list.Flush(); 5892269024Semaste m_extended_thread_stop_id = 0; 5893269024Semaste m_queue_list.Clear(); 5894269024Semaste m_queue_list_stop_id = 0; 5895254721Semaste} 5896254721Semaste 5897254721Semastevoid 5898254721SemasteProcess::DidExec () 5899254721Semaste{ 5900254721Semaste Target &target = GetTarget(); 5901254721Semaste target.CleanupProcess (); 5902263367Semaste target.ClearModules(false); 5903254721Semaste m_dynamic_checkers_ap.reset(); 5904254721Semaste m_abi_sp.reset(); 5905263363Semaste m_system_runtime_ap.reset(); 5906254721Semaste m_os_ap.reset(); 5907254721Semaste m_dyld_ap.reset(); 5908254721Semaste m_image_tokens.clear(); 5909254721Semaste m_allocated_memory_cache.Clear(); 5910254721Semaste m_language_runtimes.clear(); 5911254721Semaste m_thread_list.DiscardThreadPlans(); 5912254721Semaste m_memory_cache.Clear(true); 5913254721Semaste DoDidExec(); 5914254721Semaste CompleteAttach (); 5915263363Semaste // Flush the process (threads and all stack frames) after running CompleteAttach() 5916263363Semaste // in case the dynamic loader loaded things in new locations. 5917263363Semaste Flush(); 5918263367Semaste 5919263367Semaste // After we figure out what was loaded/unloaded in CompleteAttach, 5920263367Semaste // we need to let the target know so it can do any cleanup it needs to. 5921263367Semaste target.DidExec(); 5922254721Semaste} 5923263363Semaste 5924269024Semasteaddr_t 5925269024SemasteProcess::ResolveIndirectFunction(const Address *address, Error &error) 5926269024Semaste{ 5927269024Semaste if (address == nullptr) 5928269024Semaste { 5929269024Semaste error.SetErrorString("Invalid address argument"); 5930269024Semaste return LLDB_INVALID_ADDRESS; 5931269024Semaste } 5932269024Semaste 5933269024Semaste addr_t function_addr = LLDB_INVALID_ADDRESS; 5934269024Semaste 5935269024Semaste addr_t addr = address->GetLoadAddress(&GetTarget()); 5936269024Semaste std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr); 5937269024Semaste if (iter != m_resolved_indirect_addresses.end()) 5938269024Semaste { 5939269024Semaste function_addr = (*iter).second; 5940269024Semaste } 5941269024Semaste else 5942269024Semaste { 5943269024Semaste if (!InferiorCall(this, address, function_addr)) 5944269024Semaste { 5945269024Semaste Symbol *symbol = address->CalculateSymbolContextSymbol(); 5946269024Semaste error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s", 5947269024Semaste symbol ? symbol->GetName().AsCString() : "<UNKNOWN>"); 5948269024Semaste function_addr = LLDB_INVALID_ADDRESS; 5949269024Semaste } 5950269024Semaste else 5951269024Semaste { 5952269024Semaste m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr)); 5953269024Semaste } 5954269024Semaste } 5955269024Semaste return function_addr; 5956269024Semaste} 5957269024Semaste 5958