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