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