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