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 12 #include "lldb/lldb-private-log.h" 13 14 #include "lldb/Breakpoint/StoppointCallbackContext.h" 15 #include "lldb/Breakpoint/BreakpointLocation.h" 16 #include "lldb/Core/Event.h" 17 #include "lldb/Core/ConnectionFileDescriptor.h" 18 #include "lldb/Core/Debugger.h" 19 #include "lldb/Core/InputReader.h" 20 #include "lldb/Core/Log.h" 21 #include "lldb/Core/PluginManager.h" 22 #include "lldb/Core/State.h" 23 #include "lldb/Interpreter/CommandInterpreter.h" 24 #include "lldb/Host/Host.h" 25 #include "lldb/Target/ABI.h" 26 #include "lldb/Target/DynamicLoader.h" 27 #include "lldb/Target/LanguageRuntime.h" 28 #include "lldb/Target/CPPLanguageRuntime.h" 29 #include "lldb/Target/ObjCLanguageRuntime.h" 30 #include "lldb/Target/RegisterContext.h" 31 #include "lldb/Target/StopInfo.h" 32 #include "lldb/Target/Target.h" 33 #include "lldb/Target/TargetList.h" 34 #include "lldb/Target/Thread.h" 35 #include "lldb/Target/ThreadPlan.h" 36 37 using namespace lldb; 38 using namespace lldb_private; 39 40 41 //---------------------------------------------------------------------- 42 // MemoryCache constructor 43 //---------------------------------------------------------------------- 44 Process::MemoryCache::MemoryCache() : 45 m_cache_line_byte_size (512), 46 m_cache_mutex (Mutex::eMutexTypeRecursive), 47 m_cache () 48 { 49 } 50 51 //---------------------------------------------------------------------- 52 // Destructor 53 //---------------------------------------------------------------------- 54 Process::MemoryCache::~MemoryCache() 55 { 56 } 57 58 void 59 Process::MemoryCache::Clear() 60 { 61 Mutex::Locker locker (m_cache_mutex); 62 m_cache.clear(); 63 } 64 65 void 66 Process::MemoryCache::Flush (addr_t addr, size_t size) 67 { 68 if (size == 0) 69 return; 70 71 const uint32_t cache_line_byte_size = m_cache_line_byte_size; 72 const addr_t end_addr = (addr + size - 1); 73 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size); 74 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size); 75 76 Mutex::Locker locker (m_cache_mutex); 77 if (m_cache.empty()) 78 return; 79 80 assert ((flush_start_addr % cache_line_byte_size) == 0); 81 82 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size) 83 { 84 collection::iterator pos = m_cache.find (curr_addr); 85 if (pos != m_cache.end()) 86 m_cache.erase(pos); 87 } 88 } 89 90 size_t 91 Process::MemoryCache::Read 92 ( 93 Process *process, 94 addr_t addr, 95 void *dst, 96 size_t dst_len, 97 Error &error 98 ) 99 { 100 size_t bytes_left = dst_len; 101 if (dst && bytes_left > 0) 102 { 103 const uint32_t cache_line_byte_size = m_cache_line_byte_size; 104 uint8_t *dst_buf = (uint8_t *)dst; 105 addr_t curr_addr = addr - (addr % cache_line_byte_size); 106 addr_t cache_offset = addr - curr_addr; 107 Mutex::Locker locker (m_cache_mutex); 108 109 while (bytes_left > 0) 110 { 111 collection::const_iterator pos = m_cache.find (curr_addr); 112 collection::const_iterator end = m_cache.end (); 113 114 if (pos != end) 115 { 116 size_t curr_read_size = cache_line_byte_size - cache_offset; 117 if (curr_read_size > bytes_left) 118 curr_read_size = bytes_left; 119 120 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size); 121 122 bytes_left -= curr_read_size; 123 curr_addr += curr_read_size + cache_offset; 124 cache_offset = 0; 125 126 if (bytes_left > 0) 127 { 128 // Get sequential cache page hits 129 for (++pos; (pos != end) && (bytes_left > 0); ++pos) 130 { 131 assert ((curr_addr % cache_line_byte_size) == 0); 132 133 if (pos->first != curr_addr) 134 break; 135 136 curr_read_size = pos->second->GetByteSize(); 137 if (curr_read_size > bytes_left) 138 curr_read_size = bytes_left; 139 140 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size); 141 142 bytes_left -= curr_read_size; 143 curr_addr += curr_read_size; 144 145 // We have a cache page that succeeded to read some bytes 146 // but not an entire page. If this happens, we must cap 147 // off how much data we are able to read... 148 if (pos->second->GetByteSize() != cache_line_byte_size) 149 return dst_len - bytes_left; 150 } 151 } 152 } 153 154 // We need to read from the process 155 156 if (bytes_left > 0) 157 { 158 assert ((curr_addr % cache_line_byte_size) == 0); 159 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0)); 160 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr, 161 data_buffer_heap_ap->GetBytes(), 162 data_buffer_heap_ap->GetByteSize(), 163 error); 164 if (process_bytes_read == 0) 165 return dst_len - bytes_left; 166 167 if (process_bytes_read != cache_line_byte_size) 168 data_buffer_heap_ap->SetByteSize (process_bytes_read); 169 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release()); 170 // We have read data and put it into the cache, continue through the 171 // loop again to get the data out of the cache... 172 } 173 } 174 } 175 176 return dst_len - bytes_left; 177 } 178 179 Process* 180 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener) 181 { 182 ProcessCreateInstance create_callback = NULL; 183 if (plugin_name) 184 { 185 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name); 186 if (create_callback) 187 { 188 std::auto_ptr<Process> debugger_ap(create_callback(target, listener)); 189 if (debugger_ap->CanDebug(target)) 190 return debugger_ap.release(); 191 } 192 } 193 else 194 { 195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx) 196 { 197 std::auto_ptr<Process> debugger_ap(create_callback(target, listener)); 198 if (debugger_ap->CanDebug(target)) 199 return debugger_ap.release(); 200 } 201 } 202 return NULL; 203 } 204 205 206 //---------------------------------------------------------------------- 207 // Process constructor 208 //---------------------------------------------------------------------- 209 Process::Process(Target &target, Listener &listener) : 210 UserID (LLDB_INVALID_PROCESS_ID), 211 Broadcaster ("lldb.process"), 212 ProcessInstanceSettings (*GetSettingsController()), 213 m_target (target), 214 m_public_state (eStateUnloaded), 215 m_private_state (eStateUnloaded), 216 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"), 217 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"), 218 m_private_state_listener ("lldb.process.internal_state_listener"), 219 m_private_state_control_wait(), 220 m_private_state_thread (LLDB_INVALID_HOST_THREAD), 221 m_stop_id (0), 222 m_thread_index_id (0), 223 m_exit_status (-1), 224 m_exit_string (), 225 m_thread_list (this), 226 m_notifications (), 227 m_image_tokens (), 228 m_listener (listener), 229 m_breakpoint_site_list (), 230 m_dynamic_checkers_ap (), 231 m_unix_signals (), 232 m_target_triple (), 233 m_byte_order (eByteOrderHost), 234 m_addr_byte_size (0), 235 m_abi_sp (), 236 m_process_input_reader (), 237 m_stdio_communication ("process.stdio"), 238 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), 239 m_stdout_data (), 240 m_memory_cache () 241 { 242 UpdateInstanceName(); 243 244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 245 if (log) 246 log->Printf ("%p Process::Process()", this); 247 248 SetEventName (eBroadcastBitStateChanged, "state-changed"); 249 SetEventName (eBroadcastBitInterrupt, "interrupt"); 250 SetEventName (eBroadcastBitSTDOUT, "stdout-available"); 251 SetEventName (eBroadcastBitSTDERR, "stderr-available"); 252 253 listener.StartListeningForEvents (this, 254 eBroadcastBitStateChanged | 255 eBroadcastBitInterrupt | 256 eBroadcastBitSTDOUT | 257 eBroadcastBitSTDERR); 258 259 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster, 260 eBroadcastBitStateChanged); 261 262 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster, 263 eBroadcastInternalStateControlStop | 264 eBroadcastInternalStateControlPause | 265 eBroadcastInternalStateControlResume); 266 } 267 268 //---------------------------------------------------------------------- 269 // Destructor 270 //---------------------------------------------------------------------- 271 Process::~Process() 272 { 273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 274 if (log) 275 log->Printf ("%p Process::~Process()", this); 276 StopPrivateStateThread(); 277 } 278 279 void 280 Process::Finalize() 281 { 282 // Do any cleanup needed prior to being destructed... Subclasses 283 // that override this method should call this superclass method as well. 284 } 285 286 void 287 Process::RegisterNotificationCallbacks (const Notifications& callbacks) 288 { 289 m_notifications.push_back(callbacks); 290 if (callbacks.initialize != NULL) 291 callbacks.initialize (callbacks.baton, this); 292 } 293 294 bool 295 Process::UnregisterNotificationCallbacks(const Notifications& callbacks) 296 { 297 std::vector<Notifications>::iterator pos, end = m_notifications.end(); 298 for (pos = m_notifications.begin(); pos != end; ++pos) 299 { 300 if (pos->baton == callbacks.baton && 301 pos->initialize == callbacks.initialize && 302 pos->process_state_changed == callbacks.process_state_changed) 303 { 304 m_notifications.erase(pos); 305 return true; 306 } 307 } 308 return false; 309 } 310 311 void 312 Process::SynchronouslyNotifyStateChanged (StateType state) 313 { 314 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end(); 315 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos) 316 { 317 if (notification_pos->process_state_changed) 318 notification_pos->process_state_changed (notification_pos->baton, this, state); 319 } 320 } 321 322 // FIXME: We need to do some work on events before the general Listener sees them. 323 // For instance if we are continuing from a breakpoint, we need to ensure that we do 324 // the little "insert real insn, step & stop" trick. But we can't do that when the 325 // event is delivered by the broadcaster - since that is done on the thread that is 326 // waiting for new events, so if we needed more than one event for our handling, we would 327 // stall. So instead we do it when we fetch the event off of the queue. 328 // 329 330 StateType 331 Process::GetNextEvent (EventSP &event_sp) 332 { 333 StateType state = eStateInvalid; 334 335 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp) 336 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 337 338 return state; 339 } 340 341 342 StateType 343 Process::WaitForProcessToStop (const TimeValue *timeout) 344 { 345 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded }; 346 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType)); 347 } 348 349 350 StateType 351 Process::WaitForState 352 ( 353 const TimeValue *timeout, 354 const StateType *match_states, const uint32_t num_match_states 355 ) 356 { 357 EventSP event_sp; 358 uint32_t i; 359 StateType state = GetState(); 360 while (state != eStateInvalid) 361 { 362 // If we are exited or detached, we won't ever get back to any 363 // other valid state... 364 if (state == eStateDetached || state == eStateExited) 365 return state; 366 367 state = WaitForStateChangedEvents (timeout, event_sp); 368 369 for (i=0; i<num_match_states; ++i) 370 { 371 if (match_states[i] == state) 372 return state; 373 } 374 } 375 return state; 376 } 377 378 bool 379 Process::HijackProcessEvents (Listener *listener) 380 { 381 if (listener != NULL) 382 { 383 return HijackBroadcaster(listener, eBroadcastBitStateChanged); 384 } 385 else 386 return false; 387 } 388 389 void 390 Process::RestoreProcessEvents () 391 { 392 RestoreBroadcaster(); 393 } 394 395 StateType 396 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp) 397 { 398 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 399 400 if (log) 401 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 402 403 StateType state = eStateInvalid; 404 if (m_listener.WaitForEventForBroadcasterWithType (timeout, 405 this, 406 eBroadcastBitStateChanged, 407 event_sp)) 408 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 409 410 if (log) 411 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 412 __FUNCTION__, 413 timeout, 414 StateAsCString(state)); 415 return state; 416 } 417 418 Event * 419 Process::PeekAtStateChangedEvents () 420 { 421 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 422 423 if (log) 424 log->Printf ("Process::%s...", __FUNCTION__); 425 426 Event *event_ptr; 427 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this, 428 eBroadcastBitStateChanged); 429 if (log) 430 { 431 if (event_ptr) 432 { 433 log->Printf ("Process::%s (event_ptr) => %s", 434 __FUNCTION__, 435 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr))); 436 } 437 else 438 { 439 log->Printf ("Process::%s no events found", 440 __FUNCTION__); 441 } 442 } 443 return event_ptr; 444 } 445 446 StateType 447 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp) 448 { 449 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 450 451 if (log) 452 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 453 454 StateType state = eStateInvalid; 455 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout, 456 &m_private_state_broadcaster, 457 eBroadcastBitStateChanged, 458 event_sp)) 459 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 460 461 // This is a bit of a hack, but when we wait here we could very well return 462 // to the command-line, and that could disable the log, which would render the 463 // log we got above invalid. 464 if (log) 465 { 466 if (state == eStateInvalid) 467 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout); 468 else 469 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state)); 470 } 471 return state; 472 } 473 474 bool 475 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only) 476 { 477 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 478 479 if (log) 480 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 481 482 if (control_only) 483 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp); 484 else 485 return m_private_state_listener.WaitForEvent(timeout, event_sp); 486 } 487 488 bool 489 Process::IsRunning () const 490 { 491 return StateIsRunningState (m_public_state.GetValue()); 492 } 493 494 int 495 Process::GetExitStatus () 496 { 497 if (m_public_state.GetValue() == eStateExited) 498 return m_exit_status; 499 return -1; 500 } 501 502 503 void 504 Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded () 505 { 506 if (m_inherit_host_env && !m_got_host_env) 507 { 508 m_got_host_env = true; 509 StringList host_env; 510 const size_t host_env_count = Host::GetEnvironment (host_env); 511 for (size_t idx=0; idx<host_env_count; idx++) 512 { 513 const char *env_entry = host_env.GetStringAtIndex (idx); 514 if (env_entry) 515 { 516 const char *equal_pos = ::strchr(env_entry, '='); 517 if (equal_pos) 518 { 519 std::string key (env_entry, equal_pos - env_entry); 520 std::string value (equal_pos + 1); 521 if (m_env_vars.find (key) == m_env_vars.end()) 522 m_env_vars[key] = value; 523 } 524 } 525 } 526 } 527 } 528 529 530 size_t 531 Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env) 532 { 533 GetHostEnvironmentIfNeeded (); 534 535 dictionary::const_iterator pos, end = m_env_vars.end(); 536 for (pos = m_env_vars.begin(); pos != end; ++pos) 537 { 538 std::string env_var_equal_value (pos->first); 539 env_var_equal_value.append(1, '='); 540 env_var_equal_value.append (pos->second); 541 env.AppendArgument (env_var_equal_value.c_str()); 542 } 543 return env.GetArgumentCount(); 544 } 545 546 547 const char * 548 Process::GetExitDescription () 549 { 550 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 551 return m_exit_string.c_str(); 552 return NULL; 553 } 554 555 bool 556 Process::SetExitStatus (int status, const char *cstr) 557 { 558 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 559 if (log) 560 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", 561 status, status, 562 cstr ? "\"" : "", 563 cstr ? cstr : "NULL", 564 cstr ? "\"" : ""); 565 566 // We were already in the exited state 567 if (m_private_state.GetValue() == eStateExited) 568 { 569 if (log) 570 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited"); 571 return false; 572 } 573 574 m_exit_status = status; 575 if (cstr) 576 m_exit_string = cstr; 577 else 578 m_exit_string.clear(); 579 580 DidExit (); 581 582 SetPrivateState (eStateExited); 583 return true; 584 } 585 586 // This static callback can be used to watch for local child processes on 587 // the current host. The the child process exits, the process will be 588 // found in the global target list (we want to be completely sure that the 589 // lldb_private::Process doesn't go away before we can deliver the signal. 590 bool 591 Process::SetProcessExitStatus 592 ( 593 void *callback_baton, 594 lldb::pid_t pid, 595 int signo, // Zero for no signal 596 int exit_status // Exit value of process if signal is zero 597 ) 598 { 599 if (signo == 0 || exit_status) 600 { 601 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid)); 602 if (target_sp) 603 { 604 ProcessSP process_sp (target_sp->GetProcessSP()); 605 if (process_sp) 606 { 607 const char *signal_cstr = NULL; 608 if (signo) 609 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 610 611 process_sp->SetExitStatus (exit_status, signal_cstr); 612 } 613 } 614 return true; 615 } 616 return false; 617 } 618 619 620 uint32_t 621 Process::GetNextThreadIndexID () 622 { 623 return ++m_thread_index_id; 624 } 625 626 StateType 627 Process::GetState() 628 { 629 // If any other threads access this we will need a mutex for it 630 return m_public_state.GetValue (); 631 } 632 633 void 634 Process::SetPublicState (StateType new_state) 635 { 636 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 637 if (log) 638 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state)); 639 m_public_state.SetValue (new_state); 640 } 641 642 StateType 643 Process::GetPrivateState () 644 { 645 return m_private_state.GetValue(); 646 } 647 648 void 649 Process::SetPrivateState (StateType new_state) 650 { 651 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 652 bool state_changed = false; 653 654 if (log) 655 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 656 657 Mutex::Locker locker(m_private_state.GetMutex()); 658 659 const StateType old_state = m_private_state.GetValueNoLock (); 660 state_changed = old_state != new_state; 661 if (state_changed) 662 { 663 m_private_state.SetValueNoLock (new_state); 664 if (StateIsStoppedState(new_state)) 665 { 666 m_stop_id++; 667 m_memory_cache.Clear(); 668 if (log) 669 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id); 670 } 671 // Use our target to get a shared pointer to ourselves... 672 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state)); 673 } 674 else 675 { 676 if (log) 677 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state)); 678 } 679 } 680 681 682 uint32_t 683 Process::GetStopID() const 684 { 685 return m_stop_id; 686 } 687 688 addr_t 689 Process::GetImageInfoAddress() 690 { 691 return LLDB_INVALID_ADDRESS; 692 } 693 694 //---------------------------------------------------------------------- 695 // LoadImage 696 // 697 // This function provides a default implementation that works for most 698 // unix variants. Any Process subclasses that need to do shared library 699 // loading differently should override LoadImage and UnloadImage and 700 // do what is needed. 701 //---------------------------------------------------------------------- 702 uint32_t 703 Process::LoadImage (const FileSpec &image_spec, Error &error) 704 { 705 DynamicLoader *loader = GetDynamicLoader(); 706 if (loader) 707 { 708 error = loader->CanLoadImage(); 709 if (error.Fail()) 710 return LLDB_INVALID_IMAGE_TOKEN; 711 } 712 713 if (error.Success()) 714 { 715 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 716 if (thread_sp == NULL) 717 thread_sp = GetThreadList ().GetThreadAtIndex(0, true); 718 719 if (thread_sp) 720 { 721 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 722 723 if (frame_sp) 724 { 725 ExecutionContext exe_ctx; 726 frame_sp->CalculateExecutionContext (exe_ctx); 727 bool unwind_on_error = true; 728 bool keep_in_memory = false; 729 StreamString expr; 730 char path[PATH_MAX]; 731 image_spec.GetPath(path, sizeof(path)); 732 expr.Printf("dlopen (\"%s\", 2)", path); 733 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n"; 734 lldb::ValueObjectSP result_valobj_sp; 735 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp); 736 if (result_valobj_sp->GetError().Success()) 737 { 738 Scalar scalar; 739 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar)) 740 { 741 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 742 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS) 743 { 744 uint32_t image_token = m_image_tokens.size(); 745 m_image_tokens.push_back (image_ptr); 746 return image_token; 747 } 748 } 749 } 750 } 751 } 752 } 753 return LLDB_INVALID_IMAGE_TOKEN; 754 } 755 756 //---------------------------------------------------------------------- 757 // UnloadImage 758 // 759 // This function provides a default implementation that works for most 760 // unix variants. Any Process subclasses that need to do shared library 761 // loading differently should override LoadImage and UnloadImage and 762 // do what is needed. 763 //---------------------------------------------------------------------- 764 Error 765 Process::UnloadImage (uint32_t image_token) 766 { 767 Error error; 768 if (image_token < m_image_tokens.size()) 769 { 770 const addr_t image_addr = m_image_tokens[image_token]; 771 if (image_addr == LLDB_INVALID_ADDRESS) 772 { 773 error.SetErrorString("image already unloaded"); 774 } 775 else 776 { 777 DynamicLoader *loader = GetDynamicLoader(); 778 if (loader) 779 error = loader->CanLoadImage(); 780 781 if (error.Success()) 782 { 783 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 784 if (thread_sp == NULL) 785 thread_sp = GetThreadList ().GetThreadAtIndex(0, true); 786 787 if (thread_sp) 788 { 789 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 790 791 if (frame_sp) 792 { 793 ExecutionContext exe_ctx; 794 frame_sp->CalculateExecutionContext (exe_ctx); 795 bool unwind_on_error = true; 796 bool keep_in_memory = false; 797 StreamString expr; 798 expr.Printf("dlclose ((void *)0x%llx)", image_addr); 799 const char *prefix = "extern \"C\" int dlclose(void* handle);\n"; 800 lldb::ValueObjectSP result_valobj_sp; 801 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp); 802 if (result_valobj_sp->GetError().Success()) 803 { 804 Scalar scalar; 805 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar)) 806 { 807 if (scalar.UInt(1)) 808 { 809 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData()); 810 } 811 else 812 { 813 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS; 814 } 815 } 816 } 817 else 818 { 819 error = result_valobj_sp->GetError(); 820 } 821 } 822 } 823 } 824 } 825 } 826 else 827 { 828 error.SetErrorString("invalid image token"); 829 } 830 return error; 831 } 832 833 DynamicLoader * 834 Process::GetDynamicLoader() 835 { 836 return NULL; 837 } 838 839 const ABI * 840 Process::GetABI() 841 { 842 ConstString& triple = m_target_triple; 843 844 if (triple.IsEmpty()) 845 return NULL; 846 847 if (m_abi_sp.get() == NULL) 848 { 849 m_abi_sp.reset(ABI::FindPlugin(triple)); 850 } 851 852 return m_abi_sp.get(); 853 } 854 855 LanguageRuntime * 856 Process::GetLanguageRuntime(lldb::LanguageType language) 857 { 858 LanguageRuntimeCollection::iterator pos; 859 pos = m_language_runtimes.find (language); 860 if (pos == m_language_runtimes.end()) 861 { 862 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language)); 863 864 m_language_runtimes[language] 865 = runtime; 866 return runtime.get(); 867 } 868 else 869 return (*pos).second.get(); 870 } 871 872 CPPLanguageRuntime * 873 Process::GetCPPLanguageRuntime () 874 { 875 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus); 876 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus) 877 return static_cast<CPPLanguageRuntime *> (runtime); 878 return NULL; 879 } 880 881 ObjCLanguageRuntime * 882 Process::GetObjCLanguageRuntime () 883 { 884 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC); 885 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC) 886 return static_cast<ObjCLanguageRuntime *> (runtime); 887 return NULL; 888 } 889 890 BreakpointSiteList & 891 Process::GetBreakpointSiteList() 892 { 893 return m_breakpoint_site_list; 894 } 895 896 const BreakpointSiteList & 897 Process::GetBreakpointSiteList() const 898 { 899 return m_breakpoint_site_list; 900 } 901 902 903 void 904 Process::DisableAllBreakpointSites () 905 { 906 m_breakpoint_site_list.SetEnabledForAll (false); 907 } 908 909 Error 910 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id) 911 { 912 Error error (DisableBreakpointSiteByID (break_id)); 913 914 if (error.Success()) 915 m_breakpoint_site_list.Remove(break_id); 916 917 return error; 918 } 919 920 Error 921 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id) 922 { 923 Error error; 924 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 925 if (bp_site_sp) 926 { 927 if (bp_site_sp->IsEnabled()) 928 error = DisableBreakpoint (bp_site_sp.get()); 929 } 930 else 931 { 932 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id); 933 } 934 935 return error; 936 } 937 938 Error 939 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id) 940 { 941 Error error; 942 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 943 if (bp_site_sp) 944 { 945 if (!bp_site_sp->IsEnabled()) 946 error = EnableBreakpoint (bp_site_sp.get()); 947 } 948 else 949 { 950 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id); 951 } 952 return error; 953 } 954 955 lldb::break_id_t 956 Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware) 957 { 958 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target); 959 if (load_addr != LLDB_INVALID_ADDRESS) 960 { 961 BreakpointSiteSP bp_site_sp; 962 963 // Look up this breakpoint site. If it exists, then add this new owner, otherwise 964 // create a new breakpoint site and add it. 965 966 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr); 967 968 if (bp_site_sp) 969 { 970 bp_site_sp->AddOwner (owner); 971 owner->SetBreakpointSite (bp_site_sp); 972 return bp_site_sp->GetID(); 973 } 974 else 975 { 976 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware)); 977 if (bp_site_sp) 978 { 979 if (EnableBreakpoint (bp_site_sp.get()).Success()) 980 { 981 owner->SetBreakpointSite (bp_site_sp); 982 return m_breakpoint_site_list.Add (bp_site_sp); 983 } 984 } 985 } 986 } 987 // We failed to enable the breakpoint 988 return LLDB_INVALID_BREAK_ID; 989 990 } 991 992 void 993 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp) 994 { 995 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id); 996 if (num_owners == 0) 997 { 998 DisableBreakpoint(bp_site_sp.get()); 999 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 1000 } 1001 } 1002 1003 1004 size_t 1005 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const 1006 { 1007 size_t bytes_removed = 0; 1008 addr_t intersect_addr; 1009 size_t intersect_size; 1010 size_t opcode_offset; 1011 size_t idx; 1012 BreakpointSiteSP bp; 1013 1014 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx) 1015 { 1016 if (bp->GetType() == BreakpointSite::eSoftware) 1017 { 1018 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset)) 1019 { 1020 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 1021 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size); 1022 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 1023 size_t buf_offset = intersect_addr - bp_addr; 1024 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size); 1025 } 1026 } 1027 } 1028 return bytes_removed; 1029 } 1030 1031 1032 Error 1033 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site) 1034 { 1035 Error error; 1036 assert (bp_site != NULL); 1037 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1038 const addr_t bp_addr = bp_site->GetLoadAddress(); 1039 if (log) 1040 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr); 1041 if (bp_site->IsEnabled()) 1042 { 1043 if (log) 1044 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr); 1045 return error; 1046 } 1047 1048 if (bp_addr == LLDB_INVALID_ADDRESS) 1049 { 1050 error.SetErrorString("BreakpointSite contains an invalid load address."); 1051 return error; 1052 } 1053 // Ask the lldb::Process subclass to fill in the correct software breakpoint 1054 // trap for the breakpoint site 1055 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 1056 1057 if (bp_opcode_size == 0) 1058 { 1059 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr); 1060 } 1061 else 1062 { 1063 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 1064 1065 if (bp_opcode_bytes == NULL) 1066 { 1067 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode."); 1068 return error; 1069 } 1070 1071 // Save the original opcode by reading it 1072 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size) 1073 { 1074 // Write a software breakpoint in place of the original opcode 1075 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 1076 { 1077 uint8_t verify_bp_opcode_bytes[64]; 1078 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 1079 { 1080 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0) 1081 { 1082 bp_site->SetEnabled(true); 1083 bp_site->SetType (BreakpointSite::eSoftware); 1084 if (log) 1085 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", 1086 bp_site->GetID(), 1087 (uint64_t)bp_addr); 1088 } 1089 else 1090 error.SetErrorString("Failed to verify the breakpoint trap in memory."); 1091 } 1092 else 1093 error.SetErrorString("Unable to read memory to verify breakpoint trap."); 1094 } 1095 else 1096 error.SetErrorString("Unable to write breakpoint trap to memory."); 1097 } 1098 else 1099 error.SetErrorString("Unable to read memory at breakpoint address."); 1100 } 1101 if (log && error.Fail()) 1102 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 1103 bp_site->GetID(), 1104 (uint64_t)bp_addr, 1105 error.AsCString()); 1106 return error; 1107 } 1108 1109 Error 1110 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site) 1111 { 1112 Error error; 1113 assert (bp_site != NULL); 1114 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1115 addr_t bp_addr = bp_site->GetLoadAddress(); 1116 lldb::user_id_t breakID = bp_site->GetID(); 1117 if (log) 1118 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr); 1119 1120 if (bp_site->IsHardware()) 1121 { 1122 error.SetErrorString("Breakpoint site is a hardware breakpoint."); 1123 } 1124 else if (bp_site->IsEnabled()) 1125 { 1126 const size_t break_op_size = bp_site->GetByteSize(); 1127 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes(); 1128 if (break_op_size > 0) 1129 { 1130 // Clear a software breakoint instruction 1131 uint8_t curr_break_op[8]; 1132 assert (break_op_size <= sizeof(curr_break_op)); 1133 bool break_op_found = false; 1134 1135 // Read the breakpoint opcode 1136 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size) 1137 { 1138 bool verify = false; 1139 // Make sure we have the a breakpoint opcode exists at this address 1140 if (::memcmp (curr_break_op, break_op, break_op_size) == 0) 1141 { 1142 break_op_found = true; 1143 // We found a valid breakpoint opcode at this address, now restore 1144 // the saved opcode. 1145 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size) 1146 { 1147 verify = true; 1148 } 1149 else 1150 error.SetErrorString("Memory write failed when restoring original opcode."); 1151 } 1152 else 1153 { 1154 error.SetErrorString("Original breakpoint trap is no longer in memory."); 1155 // Set verify to true and so we can check if the original opcode has already been restored 1156 verify = true; 1157 } 1158 1159 if (verify) 1160 { 1161 uint8_t verify_opcode[8]; 1162 assert (break_op_size < sizeof(verify_opcode)); 1163 // Verify that our original opcode made it back to the inferior 1164 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size) 1165 { 1166 // compare the memory we just read with the original opcode 1167 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0) 1168 { 1169 // SUCCESS 1170 bp_site->SetEnabled(false); 1171 if (log) 1172 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr); 1173 return error; 1174 } 1175 else 1176 { 1177 if (break_op_found) 1178 error.SetErrorString("Failed to restore original opcode."); 1179 } 1180 } 1181 else 1182 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored."); 1183 } 1184 } 1185 else 1186 error.SetErrorString("Unable to read memory that should contain the breakpoint trap."); 1187 } 1188 } 1189 else 1190 { 1191 if (log) 1192 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr); 1193 return error; 1194 } 1195 1196 if (log) 1197 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 1198 bp_site->GetID(), 1199 (uint64_t)bp_addr, 1200 error.AsCString()); 1201 return error; 1202 1203 } 1204 1205 // Comment out line below to disable memory caching 1206 #define ENABLE_MEMORY_CACHING 1207 // Uncomment to verify memory caching works after making changes to caching code 1208 //#define VERIFY_MEMORY_READS 1209 1210 #if defined (ENABLE_MEMORY_CACHING) 1211 1212 #if defined (VERIFY_MEMORY_READS) 1213 1214 size_t 1215 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1216 { 1217 // Memory caching is enabled, with debug verification 1218 if (buf && size) 1219 { 1220 // Uncomment the line below to make sure memory caching is working. 1221 // I ran this through the test suite and got no assertions, so I am 1222 // pretty confident this is working well. If any changes are made to 1223 // memory caching, uncomment the line below and test your changes! 1224 1225 // Verify all memory reads by using the cache first, then redundantly 1226 // reading the same memory from the inferior and comparing to make sure 1227 // everything is exactly the same. 1228 std::string verify_buf (size, '\0'); 1229 assert (verify_buf.size() == size); 1230 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error); 1231 Error verify_error; 1232 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); 1233 assert (cache_bytes_read == verify_bytes_read); 1234 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 1235 assert (verify_error.Success() == error.Success()); 1236 return cache_bytes_read; 1237 } 1238 return 0; 1239 } 1240 1241 #else // #if defined (VERIFY_MEMORY_READS) 1242 1243 size_t 1244 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1245 { 1246 // Memory caching enabled, no verification 1247 return m_memory_cache.Read (this, addr, buf, size, error); 1248 } 1249 1250 #endif // #else for #if defined (VERIFY_MEMORY_READS) 1251 1252 #else // #if defined (ENABLE_MEMORY_CACHING) 1253 1254 size_t 1255 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1256 { 1257 // Memory caching is disabled 1258 return ReadMemoryFromInferior (addr, buf, size, error); 1259 } 1260 1261 #endif // #else for #if defined (ENABLE_MEMORY_CACHING) 1262 1263 1264 size_t 1265 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error) 1266 { 1267 if (buf == NULL || size == 0) 1268 return 0; 1269 1270 size_t bytes_read = 0; 1271 uint8_t *bytes = (uint8_t *)buf; 1272 1273 while (bytes_read < size) 1274 { 1275 const size_t curr_size = size - bytes_read; 1276 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read, 1277 bytes + bytes_read, 1278 curr_size, 1279 error); 1280 bytes_read += curr_bytes_read; 1281 if (curr_bytes_read == curr_size || curr_bytes_read == 0) 1282 break; 1283 } 1284 1285 // Replace any software breakpoint opcodes that fall into this range back 1286 // into "buf" before we return 1287 if (bytes_read > 0) 1288 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf); 1289 return bytes_read; 1290 } 1291 1292 uint64_t 1293 Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error) 1294 { 1295 if (integer_byte_size > sizeof(uint64_t)) 1296 { 1297 error.SetErrorString ("unsupported integer size"); 1298 } 1299 else 1300 { 1301 uint8_t tmp[sizeof(uint64_t)]; 1302 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize()); 1303 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size) 1304 { 1305 uint32_t offset = 0; 1306 return data.GetMaxU64 (&offset, integer_byte_size); 1307 } 1308 } 1309 // Any plug-in that doesn't return success a memory read with the number 1310 // of bytes that were requested should be setting the error 1311 assert (error.Fail()); 1312 return 0; 1313 } 1314 1315 size_t 1316 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error) 1317 { 1318 size_t bytes_written = 0; 1319 const uint8_t *bytes = (const uint8_t *)buf; 1320 1321 while (bytes_written < size) 1322 { 1323 const size_t curr_size = size - bytes_written; 1324 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written, 1325 bytes + bytes_written, 1326 curr_size, 1327 error); 1328 bytes_written += curr_bytes_written; 1329 if (curr_bytes_written == curr_size || curr_bytes_written == 0) 1330 break; 1331 } 1332 return bytes_written; 1333 } 1334 1335 size_t 1336 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1337 { 1338 #if defined (ENABLE_MEMORY_CACHING) 1339 m_memory_cache.Flush (addr, size); 1340 #endif 1341 1342 if (buf == NULL || size == 0) 1343 return 0; 1344 // We need to write any data that would go where any current software traps 1345 // (enabled software breakpoints) any software traps (breakpoints) that we 1346 // may have placed in our tasks memory. 1347 1348 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr); 1349 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end(); 1350 1351 if (iter == end || iter->second->GetLoadAddress() > addr + size) 1352 return DoWriteMemory(addr, buf, size, error); 1353 1354 BreakpointSiteList::collection::const_iterator pos; 1355 size_t bytes_written = 0; 1356 addr_t intersect_addr = 0; 1357 size_t intersect_size = 0; 1358 size_t opcode_offset = 0; 1359 const uint8_t *ubuf = (const uint8_t *)buf; 1360 1361 for (pos = iter; pos != end; ++pos) 1362 { 1363 BreakpointSiteSP bp; 1364 bp = pos->second; 1365 1366 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset)); 1367 assert(addr <= intersect_addr && intersect_addr < addr + size); 1368 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); 1369 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 1370 1371 // Check for bytes before this breakpoint 1372 const addr_t curr_addr = addr + bytes_written; 1373 if (intersect_addr > curr_addr) 1374 { 1375 // There are some bytes before this breakpoint that we need to 1376 // just write to memory 1377 size_t curr_size = intersect_addr - curr_addr; 1378 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr, 1379 ubuf + bytes_written, 1380 curr_size, 1381 error); 1382 bytes_written += curr_bytes_written; 1383 if (curr_bytes_written != curr_size) 1384 { 1385 // We weren't able to write all of the requested bytes, we 1386 // are done looping and will return the number of bytes that 1387 // we have written so far. 1388 break; 1389 } 1390 } 1391 1392 // Now write any bytes that would cover up any software breakpoints 1393 // directly into the breakpoint opcode buffer 1394 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); 1395 bytes_written += intersect_size; 1396 } 1397 1398 // Write any remaining bytes after the last breakpoint if we have any left 1399 if (bytes_written < size) 1400 bytes_written += WriteMemoryPrivate (addr + bytes_written, 1401 ubuf + bytes_written, 1402 size - bytes_written, 1403 error); 1404 1405 return bytes_written; 1406 } 1407 1408 addr_t 1409 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error) 1410 { 1411 // Fixme: we should track the blocks we've allocated, and clean them up... 1412 // We could even do our own allocator here if that ends up being more efficient. 1413 addr_t allocated_addr = DoAllocateMemory (size, permissions, error); 1414 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1415 if (log) 1416 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)", 1417 size, 1418 permissions & ePermissionsReadable ? 'r' : '-', 1419 permissions & ePermissionsWritable ? 'w' : '-', 1420 permissions & ePermissionsExecutable ? 'x' : '-', 1421 (uint64_t)allocated_addr, 1422 m_stop_id); 1423 return allocated_addr; 1424 } 1425 1426 Error 1427 Process::DeallocateMemory (addr_t ptr) 1428 { 1429 Error error(DoDeallocateMemory (ptr)); 1430 1431 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1432 if (log) 1433 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)", 1434 ptr, 1435 error.AsCString("SUCCESS"), 1436 m_stop_id); 1437 return error; 1438 } 1439 1440 1441 Error 1442 Process::EnableWatchpoint (WatchpointLocation *watchpoint) 1443 { 1444 Error error; 1445 error.SetErrorString("watchpoints are not supported"); 1446 return error; 1447 } 1448 1449 Error 1450 Process::DisableWatchpoint (WatchpointLocation *watchpoint) 1451 { 1452 Error error; 1453 error.SetErrorString("watchpoints are not supported"); 1454 return error; 1455 } 1456 1457 StateType 1458 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp) 1459 { 1460 StateType state; 1461 // Now wait for the process to launch and return control to us, and then 1462 // call DidLaunch: 1463 while (1) 1464 { 1465 event_sp.reset(); 1466 state = WaitForStateChangedEventsPrivate (timeout, event_sp); 1467 1468 if (StateIsStoppedState(state)) 1469 break; 1470 1471 // If state is invalid, then we timed out 1472 if (state == eStateInvalid) 1473 break; 1474 1475 if (event_sp) 1476 HandlePrivateEvent (event_sp); 1477 } 1478 return state; 1479 } 1480 1481 Error 1482 Process::Launch 1483 ( 1484 char const *argv[], 1485 char const *envp[], 1486 uint32_t launch_flags, 1487 const char *stdin_path, 1488 const char *stdout_path, 1489 const char *stderr_path, 1490 const char *working_directory 1491 ) 1492 { 1493 Error error; 1494 m_target_triple.Clear(); 1495 m_abi_sp.reset(); 1496 m_process_input_reader.reset(); 1497 1498 Module *exe_module = m_target.GetExecutableModule().get(); 1499 if (exe_module) 1500 { 1501 char exec_file_path[PATH_MAX]; 1502 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path)); 1503 if (exe_module->GetFileSpec().Exists()) 1504 { 1505 error = WillLaunch (exe_module); 1506 if (error.Success()) 1507 { 1508 SetPublicState (eStateLaunching); 1509 // The args coming in should not contain the application name, the 1510 // lldb_private::Process class will add this in case the executable 1511 // gets resolved to a different file than was given on the command 1512 // line (like when an applicaiton bundle is specified and will 1513 // resolve to the contained exectuable file, or the file given was 1514 // a symlink or other file system link that resolves to a different 1515 // file). 1516 1517 // Get the resolved exectuable path 1518 1519 // Make a new argument vector 1520 std::vector<const char *> exec_path_plus_argv; 1521 // Append the resolved executable path 1522 exec_path_plus_argv.push_back (exec_file_path); 1523 1524 // Push all args if there are any 1525 if (argv) 1526 { 1527 for (int i = 0; argv[i]; ++i) 1528 exec_path_plus_argv.push_back(argv[i]); 1529 } 1530 1531 // Push a NULL to terminate the args. 1532 exec_path_plus_argv.push_back(NULL); 1533 1534 // Now launch using these arguments. 1535 error = DoLaunch (exe_module, 1536 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(), 1537 envp, 1538 launch_flags, 1539 stdin_path, 1540 stdout_path, 1541 stderr_path, 1542 working_directory); 1543 1544 if (error.Fail()) 1545 { 1546 if (GetID() != LLDB_INVALID_PROCESS_ID) 1547 { 1548 SetID (LLDB_INVALID_PROCESS_ID); 1549 const char *error_string = error.AsCString(); 1550 if (error_string == NULL) 1551 error_string = "launch failed"; 1552 SetExitStatus (-1, error_string); 1553 } 1554 } 1555 else 1556 { 1557 EventSP event_sp; 1558 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 1559 1560 if (state == eStateStopped || state == eStateCrashed) 1561 { 1562 DidLaunch (); 1563 1564 // This delays passing the stopped event to listeners till DidLaunch gets 1565 // a chance to complete... 1566 HandlePrivateEvent (event_sp); 1567 StartPrivateStateThread (); 1568 } 1569 else if (state == eStateExited) 1570 { 1571 // We exited while trying to launch somehow. Don't call DidLaunch as that's 1572 // not likely to work, and return an invalid pid. 1573 HandlePrivateEvent (event_sp); 1574 } 1575 } 1576 } 1577 } 1578 else 1579 { 1580 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path); 1581 } 1582 } 1583 return error; 1584 } 1585 1586 Error 1587 Process::CompleteAttach () 1588 { 1589 Error error; 1590 1591 if (GetID() == LLDB_INVALID_PROCESS_ID) 1592 { 1593 error.SetErrorString("no process"); 1594 } 1595 1596 EventSP event_sp; 1597 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 1598 if (state == eStateStopped || state == eStateCrashed) 1599 { 1600 DidAttach (); 1601 // Figure out which one is the executable, and set that in our target: 1602 ModuleList &modules = GetTarget().GetImages(); 1603 1604 size_t num_modules = modules.GetSize(); 1605 for (int i = 0; i < num_modules; i++) 1606 { 1607 ModuleSP module_sp = modules.GetModuleAtIndex(i); 1608 if (module_sp->IsExecutable()) 1609 { 1610 ModuleSP exec_module = GetTarget().GetExecutableModule(); 1611 if (!exec_module || exec_module != module_sp) 1612 { 1613 1614 GetTarget().SetExecutableModule (module_sp, false); 1615 } 1616 break; 1617 } 1618 } 1619 1620 // This delays passing the stopped event to listeners till DidLaunch gets 1621 // a chance to complete... 1622 HandlePrivateEvent(event_sp); 1623 StartPrivateStateThread(); 1624 } 1625 else 1626 { 1627 // We exited while trying to launch somehow. Don't call DidLaunch as that's 1628 // not likely to work, and return an invalid pid. 1629 if (state == eStateExited) 1630 HandlePrivateEvent (event_sp); 1631 error.SetErrorStringWithFormat("invalid state after attach: %s", 1632 lldb_private::StateAsCString(state)); 1633 } 1634 return error; 1635 } 1636 1637 Error 1638 Process::Attach (lldb::pid_t attach_pid) 1639 { 1640 1641 m_target_triple.Clear(); 1642 m_abi_sp.reset(); 1643 m_process_input_reader.reset(); 1644 1645 // Find the process and its architecture. Make sure it matches the architecture 1646 // of the current Target, and if not adjust it. 1647 1648 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid); 1649 if (attach_spec != GetTarget().GetArchitecture()) 1650 { 1651 // Set the architecture on the target. 1652 GetTarget().SetArchitecture(attach_spec); 1653 } 1654 1655 Error error (WillAttachToProcessWithID(attach_pid)); 1656 if (error.Success()) 1657 { 1658 SetPublicState (eStateAttaching); 1659 1660 error = DoAttachToProcessWithID (attach_pid); 1661 if (error.Success()) 1662 { 1663 error = CompleteAttach(); 1664 } 1665 else 1666 { 1667 if (GetID() != LLDB_INVALID_PROCESS_ID) 1668 { 1669 SetID (LLDB_INVALID_PROCESS_ID); 1670 const char *error_string = error.AsCString(); 1671 if (error_string == NULL) 1672 error_string = "attach failed"; 1673 1674 SetExitStatus(-1, error_string); 1675 } 1676 } 1677 } 1678 return error; 1679 } 1680 1681 Error 1682 Process::Attach (const char *process_name, bool wait_for_launch) 1683 { 1684 m_target_triple.Clear(); 1685 m_abi_sp.reset(); 1686 m_process_input_reader.reset(); 1687 1688 // Find the process and its architecture. Make sure it matches the architecture 1689 // of the current Target, and if not adjust it. 1690 1691 if (!wait_for_launch) 1692 { 1693 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name); 1694 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture()) 1695 { 1696 // Set the architecture on the target. 1697 GetTarget().SetArchitecture(attach_spec); 1698 } 1699 } 1700 1701 Error error (WillAttachToProcessWithName(process_name, wait_for_launch)); 1702 if (error.Success()) 1703 { 1704 SetPublicState (eStateAttaching); 1705 error = DoAttachToProcessWithName (process_name, wait_for_launch); 1706 if (error.Fail()) 1707 { 1708 if (GetID() != LLDB_INVALID_PROCESS_ID) 1709 { 1710 SetID (LLDB_INVALID_PROCESS_ID); 1711 const char *error_string = error.AsCString(); 1712 if (error_string == NULL) 1713 error_string = "attach failed"; 1714 1715 SetExitStatus(-1, error_string); 1716 } 1717 } 1718 else 1719 { 1720 error = CompleteAttach(); 1721 } 1722 } 1723 return error; 1724 } 1725 1726 Error 1727 Process::Resume () 1728 { 1729 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1730 if (log) 1731 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s", 1732 m_stop_id, 1733 StateAsCString(m_public_state.GetValue()), 1734 StateAsCString(m_private_state.GetValue())); 1735 1736 Error error (WillResume()); 1737 // Tell the process it is about to resume before the thread list 1738 if (error.Success()) 1739 { 1740 // Now let the thread list know we are about to resume so it 1741 // can let all of our threads know that they are about to be 1742 // resumed. Threads will each be called with 1743 // Thread::WillResume(StateType) where StateType contains the state 1744 // that they are supposed to have when the process is resumed 1745 // (suspended/running/stepping). Threads should also check 1746 // their resume signal in lldb::Thread::GetResumeSignal() 1747 // to see if they are suppoed to start back up with a signal. 1748 if (m_thread_list.WillResume()) 1749 { 1750 error = DoResume(); 1751 if (error.Success()) 1752 { 1753 DidResume(); 1754 m_thread_list.DidResume(); 1755 if (log) 1756 log->Printf ("Process thinks the process has resumed."); 1757 } 1758 } 1759 else 1760 { 1761 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume"); 1762 } 1763 } 1764 else if (log) 1765 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>")); 1766 return error; 1767 } 1768 1769 Error 1770 Process::Halt () 1771 { 1772 Error error (WillHalt()); 1773 1774 if (error.Success()) 1775 { 1776 1777 bool caused_stop = false; 1778 EventSP event_sp; 1779 1780 // Pause our private state thread so we can ensure no one else eats 1781 // the stop event out from under us. 1782 PausePrivateStateThread(); 1783 1784 // Ask the process subclass to actually halt our process 1785 error = DoHalt(caused_stop); 1786 if (error.Success()) 1787 { 1788 // If "caused_stop" is true, then DoHalt stopped the process. If 1789 // "caused_stop" is false, the process was already stopped. 1790 // If the DoHalt caused the process to stop, then we want to catch 1791 // this event and set the interrupted bool to true before we pass 1792 // this along so clients know that the process was interrupted by 1793 // a halt command. 1794 if (caused_stop) 1795 { 1796 // Wait for 2 seconds for the process to stop. 1797 TimeValue timeout_time; 1798 timeout_time = TimeValue::Now(); 1799 timeout_time.OffsetWithSeconds(1); 1800 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp); 1801 1802 if (state == eStateInvalid) 1803 { 1804 // We timeout out and didn't get a stop event... 1805 error.SetErrorString ("Halt timed out."); 1806 } 1807 else 1808 { 1809 if (StateIsStoppedState (state)) 1810 { 1811 // We caused the process to interrupt itself, so mark this 1812 // as such in the stop event so clients can tell an interrupted 1813 // process from a natural stop 1814 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); 1815 } 1816 else 1817 { 1818 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1819 if (log) 1820 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); 1821 error.SetErrorString ("Did not get stopped event after halt."); 1822 } 1823 } 1824 } 1825 DidHalt(); 1826 1827 } 1828 // Resume our private state thread before we post the event (if any) 1829 ResumePrivateStateThread(); 1830 1831 // Post any event we might have consumed. If all goes well, we will have 1832 // stopped the process, intercepted the event and set the interrupted 1833 // bool in the event. Post it to the private event queue and that will end up 1834 // correctly setting the state. 1835 if (event_sp) 1836 m_private_state_broadcaster.BroadcastEvent(event_sp); 1837 1838 } 1839 return error; 1840 } 1841 1842 Error 1843 Process::Detach () 1844 { 1845 Error error (WillDetach()); 1846 1847 if (error.Success()) 1848 { 1849 DisableAllBreakpointSites(); 1850 error = DoDetach(); 1851 if (error.Success()) 1852 { 1853 DidDetach(); 1854 StopPrivateStateThread(); 1855 } 1856 } 1857 return error; 1858 } 1859 1860 Error 1861 Process::Destroy () 1862 { 1863 Error error (WillDestroy()); 1864 if (error.Success()) 1865 { 1866 DisableAllBreakpointSites(); 1867 error = DoDestroy(); 1868 if (error.Success()) 1869 { 1870 DidDestroy(); 1871 StopPrivateStateThread(); 1872 } 1873 m_stdio_communication.StopReadThread(); 1874 m_stdio_communication.Disconnect(); 1875 if (m_process_input_reader && m_process_input_reader->IsActive()) 1876 m_target.GetDebugger().PopInputReader (m_process_input_reader); 1877 if (m_process_input_reader) 1878 m_process_input_reader.reset(); 1879 } 1880 return error; 1881 } 1882 1883 Error 1884 Process::Signal (int signal) 1885 { 1886 Error error (WillSignal()); 1887 if (error.Success()) 1888 { 1889 error = DoSignal(signal); 1890 if (error.Success()) 1891 DidSignal(); 1892 } 1893 return error; 1894 } 1895 1896 UnixSignals & 1897 Process::GetUnixSignals () 1898 { 1899 return m_unix_signals; 1900 } 1901 1902 Target & 1903 Process::GetTarget () 1904 { 1905 return m_target; 1906 } 1907 1908 const Target & 1909 Process::GetTarget () const 1910 { 1911 return m_target; 1912 } 1913 1914 uint32_t 1915 Process::GetAddressByteSize() 1916 { 1917 if (m_addr_byte_size == 0) 1918 return m_target.GetArchitecture().GetAddressByteSize(); 1919 return m_addr_byte_size; 1920 } 1921 1922 bool 1923 Process::ShouldBroadcastEvent (Event *event_ptr) 1924 { 1925 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr); 1926 bool return_value = true; 1927 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 1928 1929 switch (state) 1930 { 1931 case eStateAttaching: 1932 case eStateLaunching: 1933 case eStateDetached: 1934 case eStateExited: 1935 case eStateUnloaded: 1936 // These events indicate changes in the state of the debugging session, always report them. 1937 return_value = true; 1938 break; 1939 case eStateInvalid: 1940 // We stopped for no apparent reason, don't report it. 1941 return_value = false; 1942 break; 1943 case eStateRunning: 1944 case eStateStepping: 1945 // If we've started the target running, we handle the cases where we 1946 // are already running and where there is a transition from stopped to 1947 // running differently. 1948 // running -> running: Automatically suppress extra running events 1949 // stopped -> running: Report except when there is one or more no votes 1950 // and no yes votes. 1951 SynchronouslyNotifyStateChanged (state); 1952 switch (m_public_state.GetValue()) 1953 { 1954 case eStateRunning: 1955 case eStateStepping: 1956 // We always suppress multiple runnings with no PUBLIC stop in between. 1957 return_value = false; 1958 break; 1959 default: 1960 // TODO: make this work correctly. For now always report 1961 // run if we aren't running so we don't miss any runnning 1962 // events. If I run the lldb/test/thread/a.out file and 1963 // break at main.cpp:58, run and hit the breakpoints on 1964 // multiple threads, then somehow during the stepping over 1965 // of all breakpoints no run gets reported. 1966 return_value = true; 1967 1968 // This is a transition from stop to run. 1969 switch (m_thread_list.ShouldReportRun (event_ptr)) 1970 { 1971 case eVoteYes: 1972 case eVoteNoOpinion: 1973 return_value = true; 1974 break; 1975 case eVoteNo: 1976 return_value = false; 1977 break; 1978 } 1979 break; 1980 } 1981 break; 1982 case eStateStopped: 1983 case eStateCrashed: 1984 case eStateSuspended: 1985 { 1986 // We've stopped. First see if we're going to restart the target. 1987 // If we are going to stop, then we always broadcast the event. 1988 // If we aren't going to stop, let the thread plans decide if we're going to report this event. 1989 // If no thread has an opinion, we don't report it. 1990 if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) 1991 { 1992 if (log) 1993 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); 1994 return true; 1995 } 1996 else 1997 { 1998 RefreshStateAfterStop (); 1999 2000 if (m_thread_list.ShouldStop (event_ptr) == false) 2001 { 2002 switch (m_thread_list.ShouldReportStop (event_ptr)) 2003 { 2004 case eVoteYes: 2005 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); 2006 // Intentional fall-through here. 2007 case eVoteNoOpinion: 2008 case eVoteNo: 2009 return_value = false; 2010 break; 2011 } 2012 2013 if (log) 2014 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state)); 2015 Resume (); 2016 } 2017 else 2018 { 2019 return_value = true; 2020 SynchronouslyNotifyStateChanged (state); 2021 } 2022 } 2023 } 2024 } 2025 2026 if (log) 2027 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO"); 2028 return return_value; 2029 } 2030 2031 //------------------------------------------------------------------ 2032 // Thread Queries 2033 //------------------------------------------------------------------ 2034 2035 ThreadList & 2036 Process::GetThreadList () 2037 { 2038 return m_thread_list; 2039 } 2040 2041 const ThreadList & 2042 Process::GetThreadList () const 2043 { 2044 return m_thread_list; 2045 } 2046 2047 2048 bool 2049 Process::StartPrivateStateThread () 2050 { 2051 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 2052 2053 if (log) 2054 log->Printf ("Process::%s ( )", __FUNCTION__); 2055 2056 // Create a thread that watches our internal state and controls which 2057 // events make it to clients (into the DCProcess event queue). 2058 char thread_name[1024]; 2059 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID()); 2060 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL); 2061 return m_private_state_thread != LLDB_INVALID_HOST_THREAD; 2062 } 2063 2064 void 2065 Process::PausePrivateStateThread () 2066 { 2067 ControlPrivateStateThread (eBroadcastInternalStateControlPause); 2068 } 2069 2070 void 2071 Process::ResumePrivateStateThread () 2072 { 2073 ControlPrivateStateThread (eBroadcastInternalStateControlResume); 2074 } 2075 2076 void 2077 Process::StopPrivateStateThread () 2078 { 2079 ControlPrivateStateThread (eBroadcastInternalStateControlStop); 2080 } 2081 2082 void 2083 Process::ControlPrivateStateThread (uint32_t signal) 2084 { 2085 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 2086 2087 assert (signal == eBroadcastInternalStateControlStop || 2088 signal == eBroadcastInternalStateControlPause || 2089 signal == eBroadcastInternalStateControlResume); 2090 2091 if (log) 2092 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal); 2093 2094 // Signal the private state thread. First we should copy this is case the 2095 // thread starts exiting since the private state thread will NULL this out 2096 // when it exits 2097 const lldb::thread_t private_state_thread = m_private_state_thread; 2098 if (private_state_thread != LLDB_INVALID_HOST_THREAD) 2099 { 2100 TimeValue timeout_time; 2101 bool timed_out; 2102 2103 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL); 2104 2105 timeout_time = TimeValue::Now(); 2106 timeout_time.OffsetWithSeconds(2); 2107 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out); 2108 m_private_state_control_wait.SetValue (false, eBroadcastNever); 2109 2110 if (signal == eBroadcastInternalStateControlStop) 2111 { 2112 if (timed_out) 2113 Host::ThreadCancel (private_state_thread, NULL); 2114 2115 thread_result_t result = NULL; 2116 Host::ThreadJoin (private_state_thread, &result, NULL); 2117 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 2118 } 2119 } 2120 } 2121 2122 void 2123 Process::HandlePrivateEvent (EventSP &event_sp) 2124 { 2125 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2126 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2127 // See if we should broadcast this state to external clients? 2128 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get()); 2129 2130 if (should_broadcast) 2131 { 2132 if (log) 2133 { 2134 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s", 2135 __FUNCTION__, 2136 GetID(), 2137 StateAsCString(new_state), 2138 StateAsCString (GetState ()), 2139 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public"); 2140 } 2141 if (StateIsRunningState (new_state)) 2142 PushProcessInputReader (); 2143 else 2144 PopProcessInputReader (); 2145 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 2146 BroadcastEvent (event_sp); 2147 } 2148 else 2149 { 2150 if (log) 2151 { 2152 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false", 2153 __FUNCTION__, 2154 GetID(), 2155 StateAsCString(new_state), 2156 StateAsCString (GetState ()), 2157 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public"); 2158 } 2159 } 2160 } 2161 2162 void * 2163 Process::PrivateStateThread (void *arg) 2164 { 2165 Process *proc = static_cast<Process*> (arg); 2166 void *result = proc->RunPrivateStateThread (); 2167 return result; 2168 } 2169 2170 void * 2171 Process::RunPrivateStateThread () 2172 { 2173 bool control_only = false; 2174 m_private_state_control_wait.SetValue (false, eBroadcastNever); 2175 2176 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2177 if (log) 2178 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID()); 2179 2180 bool exit_now = false; 2181 while (!exit_now) 2182 { 2183 EventSP event_sp; 2184 WaitForEventsPrivate (NULL, event_sp, control_only); 2185 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) 2186 { 2187 switch (event_sp->GetType()) 2188 { 2189 case eBroadcastInternalStateControlStop: 2190 exit_now = true; 2191 continue; // Go to next loop iteration so we exit without 2192 break; // doing any internal state managment below 2193 2194 case eBroadcastInternalStateControlPause: 2195 control_only = true; 2196 break; 2197 2198 case eBroadcastInternalStateControlResume: 2199 control_only = false; 2200 break; 2201 } 2202 2203 if (log) 2204 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType()); 2205 2206 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 2207 continue; 2208 } 2209 2210 2211 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2212 2213 if (internal_state != eStateInvalid) 2214 { 2215 HandlePrivateEvent (event_sp); 2216 } 2217 2218 if (internal_state == eStateInvalid || 2219 internal_state == eStateExited || 2220 internal_state == eStateDetached ) 2221 { 2222 if (log) 2223 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state)); 2224 2225 break; 2226 } 2227 } 2228 2229 // Verify log is still enabled before attempting to write to it... 2230 if (log) 2231 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID()); 2232 2233 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 2234 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 2235 return NULL; 2236 } 2237 2238 //------------------------------------------------------------------ 2239 // Process Event Data 2240 //------------------------------------------------------------------ 2241 2242 Process::ProcessEventData::ProcessEventData () : 2243 EventData (), 2244 m_process_sp (), 2245 m_state (eStateInvalid), 2246 m_restarted (false), 2247 m_update_state (false), 2248 m_interrupted (false) 2249 { 2250 } 2251 2252 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) : 2253 EventData (), 2254 m_process_sp (process_sp), 2255 m_state (state), 2256 m_restarted (false), 2257 m_update_state (false), 2258 m_interrupted (false) 2259 { 2260 } 2261 2262 Process::ProcessEventData::~ProcessEventData() 2263 { 2264 } 2265 2266 const ConstString & 2267 Process::ProcessEventData::GetFlavorString () 2268 { 2269 static ConstString g_flavor ("Process::ProcessEventData"); 2270 return g_flavor; 2271 } 2272 2273 const ConstString & 2274 Process::ProcessEventData::GetFlavor () const 2275 { 2276 return ProcessEventData::GetFlavorString (); 2277 } 2278 2279 void 2280 Process::ProcessEventData::DoOnRemoval (Event *event_ptr) 2281 { 2282 // This function gets called twice for each event, once when the event gets pulled 2283 // off of the private process event queue, and once when it gets pulled off of 2284 // the public event queue. m_update_state is used to distinguish these 2285 // two cases; it is false when we're just pulling it off for private handling, 2286 // and we don't want to do the breakpoint command handling then. 2287 2288 if (!m_update_state) 2289 return; 2290 2291 m_process_sp->SetPublicState (m_state); 2292 2293 // If we're stopped and haven't restarted, then do the breakpoint commands here: 2294 if (m_state == eStateStopped && ! m_restarted) 2295 { 2296 int num_threads = m_process_sp->GetThreadList().GetSize(); 2297 int idx; 2298 2299 for (idx = 0; idx < num_threads; ++idx) 2300 { 2301 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx); 2302 2303 StopInfoSP stop_info_sp = thread_sp->GetStopInfo (); 2304 if (stop_info_sp) 2305 { 2306 stop_info_sp->PerformAction(event_ptr); 2307 } 2308 } 2309 2310 // The stop action might restart the target. If it does, then we want to mark that in the 2311 // event so that whoever is receiving it will know to wait for the running event and reflect 2312 // that state appropriately. 2313 2314 if (m_process_sp->GetPrivateState() == eStateRunning) 2315 SetRestarted(true); 2316 } 2317 } 2318 2319 void 2320 Process::ProcessEventData::Dump (Stream *s) const 2321 { 2322 if (m_process_sp) 2323 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID()); 2324 2325 s->Printf("state = %s", StateAsCString(GetState()));; 2326 } 2327 2328 const Process::ProcessEventData * 2329 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr) 2330 { 2331 if (event_ptr) 2332 { 2333 const EventData *event_data = event_ptr->GetData(); 2334 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 2335 return static_cast <const ProcessEventData *> (event_ptr->GetData()); 2336 } 2337 return NULL; 2338 } 2339 2340 ProcessSP 2341 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr) 2342 { 2343 ProcessSP process_sp; 2344 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2345 if (data) 2346 process_sp = data->GetProcessSP(); 2347 return process_sp; 2348 } 2349 2350 StateType 2351 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr) 2352 { 2353 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2354 if (data == NULL) 2355 return eStateInvalid; 2356 else 2357 return data->GetState(); 2358 } 2359 2360 bool 2361 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr) 2362 { 2363 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2364 if (data == NULL) 2365 return false; 2366 else 2367 return data->GetRestarted(); 2368 } 2369 2370 void 2371 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value) 2372 { 2373 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 2374 if (data != NULL) 2375 data->SetRestarted(new_value); 2376 } 2377 2378 bool 2379 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) 2380 { 2381 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2382 if (data == NULL) 2383 return false; 2384 else 2385 return data->GetInterrupted (); 2386 } 2387 2388 void 2389 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) 2390 { 2391 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 2392 if (data != NULL) 2393 data->SetInterrupted(new_value); 2394 } 2395 2396 bool 2397 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) 2398 { 2399 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 2400 if (data) 2401 { 2402 data->SetUpdateStateOnRemoval(); 2403 return true; 2404 } 2405 return false; 2406 } 2407 2408 Target * 2409 Process::CalculateTarget () 2410 { 2411 return &m_target; 2412 } 2413 2414 Process * 2415 Process::CalculateProcess () 2416 { 2417 return this; 2418 } 2419 2420 Thread * 2421 Process::CalculateThread () 2422 { 2423 return NULL; 2424 } 2425 2426 StackFrame * 2427 Process::CalculateStackFrame () 2428 { 2429 return NULL; 2430 } 2431 2432 void 2433 Process::CalculateExecutionContext (ExecutionContext &exe_ctx) 2434 { 2435 exe_ctx.target = &m_target; 2436 exe_ctx.process = this; 2437 exe_ctx.thread = NULL; 2438 exe_ctx.frame = NULL; 2439 } 2440 2441 lldb::ProcessSP 2442 Process::GetSP () 2443 { 2444 return GetTarget().GetProcessSP(); 2445 } 2446 2447 uint32_t 2448 Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2449 { 2450 return 0; 2451 } 2452 2453 ArchSpec 2454 Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 2455 { 2456 return Host::GetArchSpecForExistingProcess (pid); 2457 } 2458 2459 ArchSpec 2460 Process::GetArchSpecForExistingProcess (const char *process_name) 2461 { 2462 return Host::GetArchSpecForExistingProcess (process_name); 2463 } 2464 2465 void 2466 Process::AppendSTDOUT (const char * s, size_t len) 2467 { 2468 Mutex::Locker locker (m_stdio_communication_mutex); 2469 m_stdout_data.append (s, len); 2470 2471 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState())); 2472 } 2473 2474 void 2475 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 2476 { 2477 Process *process = (Process *) baton; 2478 process->AppendSTDOUT (static_cast<const char *>(src), src_len); 2479 } 2480 2481 size_t 2482 Process::ProcessInputReaderCallback (void *baton, 2483 InputReader &reader, 2484 lldb::InputReaderAction notification, 2485 const char *bytes, 2486 size_t bytes_len) 2487 { 2488 Process *process = (Process *) baton; 2489 2490 switch (notification) 2491 { 2492 case eInputReaderActivate: 2493 break; 2494 2495 case eInputReaderDeactivate: 2496 break; 2497 2498 case eInputReaderReactivate: 2499 break; 2500 2501 case eInputReaderGotToken: 2502 { 2503 Error error; 2504 process->PutSTDIN (bytes, bytes_len, error); 2505 } 2506 break; 2507 2508 case eInputReaderInterrupt: 2509 process->Halt (); 2510 break; 2511 2512 case eInputReaderEndOfFile: 2513 process->AppendSTDOUT ("^D", 2); 2514 break; 2515 2516 case eInputReaderDone: 2517 break; 2518 2519 } 2520 2521 return bytes_len; 2522 } 2523 2524 void 2525 Process::ResetProcessInputReader () 2526 { 2527 m_process_input_reader.reset(); 2528 } 2529 2530 void 2531 Process::SetUpProcessInputReader (int file_descriptor) 2532 { 2533 // First set up the Read Thread for reading/handling process I/O 2534 2535 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true)); 2536 2537 if (conn_ap.get()) 2538 { 2539 m_stdio_communication.SetConnection (conn_ap.release()); 2540 if (m_stdio_communication.IsConnected()) 2541 { 2542 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 2543 m_stdio_communication.StartReadThread(); 2544 2545 // Now read thread is set up, set up input reader. 2546 2547 if (!m_process_input_reader.get()) 2548 { 2549 m_process_input_reader.reset (new InputReader(m_target.GetDebugger())); 2550 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback, 2551 this, 2552 eInputReaderGranularityByte, 2553 NULL, 2554 NULL, 2555 false)); 2556 2557 if (err.Fail()) 2558 m_process_input_reader.reset(); 2559 } 2560 } 2561 } 2562 } 2563 2564 void 2565 Process::PushProcessInputReader () 2566 { 2567 if (m_process_input_reader && !m_process_input_reader->IsActive()) 2568 m_target.GetDebugger().PushInputReader (m_process_input_reader); 2569 } 2570 2571 void 2572 Process::PopProcessInputReader () 2573 { 2574 if (m_process_input_reader && m_process_input_reader->IsActive()) 2575 m_target.GetDebugger().PopInputReader (m_process_input_reader); 2576 } 2577 2578 2579 void 2580 Process::Initialize () 2581 { 2582 UserSettingsControllerSP &usc = GetSettingsController(); 2583 usc.reset (new SettingsController); 2584 UserSettingsController::InitializeSettingsController (usc, 2585 SettingsController::global_settings_table, 2586 SettingsController::instance_settings_table); 2587 } 2588 2589 void 2590 Process::Terminate () 2591 { 2592 UserSettingsControllerSP &usc = GetSettingsController(); 2593 UserSettingsController::FinalizeSettingsController (usc); 2594 usc.reset(); 2595 } 2596 2597 UserSettingsControllerSP & 2598 Process::GetSettingsController () 2599 { 2600 static UserSettingsControllerSP g_settings_controller; 2601 return g_settings_controller; 2602 } 2603 2604 void 2605 Process::UpdateInstanceName () 2606 { 2607 ModuleSP module_sp = GetTarget().GetExecutableModule(); 2608 if (module_sp) 2609 { 2610 StreamString sstr; 2611 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString()); 2612 2613 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), 2614 sstr.GetData()); 2615 } 2616 } 2617 2618 ExecutionResults 2619 Process::RunThreadPlan (ExecutionContext &exe_ctx, 2620 lldb::ThreadPlanSP &thread_plan_sp, 2621 bool stop_others, 2622 bool try_all_threads, 2623 bool discard_on_error, 2624 uint32_t single_thread_timeout_usec, 2625 Stream &errors) 2626 { 2627 ExecutionResults return_value = eExecutionSetupError; 2628 2629 if (thread_plan_sp.get() == NULL) 2630 { 2631 errors.Printf("RunThreadPlan called with empty thread plan."); 2632 return lldb::eExecutionSetupError; 2633 } 2634 2635 if (m_private_state.GetValue() != eStateStopped) 2636 { 2637 errors.Printf ("RunThreadPlan called while the private state was not stopped."); 2638 // REMOVE BEAR TRAP... 2639 // abort(); 2640 } 2641 2642 // Save this value for restoration of the execution context after we run 2643 uint32_t tid = exe_ctx.thread->GetIndexID(); 2644 2645 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either, 2646 // so we should arrange to reset them as well. 2647 2648 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread(); 2649 lldb::StackFrameSP selected_frame_sp; 2650 2651 uint32_t selected_tid; 2652 if (selected_thread_sp != NULL) 2653 { 2654 selected_tid = selected_thread_sp->GetIndexID(); 2655 selected_frame_sp = selected_thread_sp->GetSelectedFrame(); 2656 } 2657 else 2658 { 2659 selected_tid = LLDB_INVALID_THREAD_ID; 2660 } 2661 2662 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true); 2663 2664 Listener listener("lldb.process.listener.run-thread-plan"); 2665 exe_ctx.process->HijackProcessEvents(&listener); 2666 2667 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 2668 if (log) 2669 { 2670 StreamString s; 2671 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 2672 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".", exe_ctx.thread->GetIndexID(), exe_ctx.thread->GetID(), s.GetData()); 2673 } 2674 2675 Error resume_error = exe_ctx.process->Resume (); 2676 if (!resume_error.Success()) 2677 { 2678 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString()); 2679 exe_ctx.process->RestoreProcessEvents(); 2680 return lldb::eExecutionSetupError; 2681 } 2682 2683 // We need to call the function synchronously, so spin waiting for it to return. 2684 // If we get interrupted while executing, we're going to lose our context, and 2685 // won't be able to gather the result at this point. 2686 // We set the timeout AFTER the resume, since the resume takes some time and we 2687 // don't want to charge that to the timeout. 2688 2689 TimeValue* timeout_ptr = NULL; 2690 TimeValue real_timeout; 2691 2692 if (single_thread_timeout_usec != 0) 2693 { 2694 real_timeout = TimeValue::Now(); 2695 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec); 2696 timeout_ptr = &real_timeout; 2697 } 2698 2699 while (1) 2700 { 2701 lldb::EventSP event_sp; 2702 lldb::StateType stop_state = lldb::eStateInvalid; 2703 // Now wait for the process to stop again: 2704 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp); 2705 2706 if (!got_event) 2707 { 2708 // Right now this is the only way to tell we've timed out... 2709 // We should interrupt the process here... 2710 // Not really sure what to do if Halt fails here... 2711 if (log) { 2712 if (try_all_threads) 2713 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, trying with all threads enabled.", 2714 single_thread_timeout_usec); 2715 else 2716 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, abandoning execution.", 2717 single_thread_timeout_usec); 2718 } 2719 2720 Error halt_error = exe_ctx.process->Halt(); 2721 2722 if (halt_error.Success()) 2723 { 2724 timeout_ptr = NULL; 2725 if (log) 2726 log->Printf ("Process::RunThreadPlan(): Halt succeeded."); 2727 2728 // Between the time that we got the timeout and the time we halted, but target 2729 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short 2730 // timeout to 2731 got_event = listener.WaitForEvent(NULL, event_sp); 2732 2733 if (got_event) 2734 { 2735 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2736 if (log) 2737 { 2738 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state)); 2739 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 2740 log->Printf (" Event was the Halt interruption event."); 2741 } 2742 2743 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get())) 2744 { 2745 if (log) 2746 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. Exiting wait loop."); 2747 return_value = lldb::eExecutionCompleted; 2748 break; 2749 } 2750 2751 if (try_all_threads 2752 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get()))) 2753 { 2754 2755 thread_plan_sp->SetStopOthers (false); 2756 if (log) 2757 log->Printf ("Process::RunThreadPlan(): About to resume."); 2758 2759 exe_ctx.process->Resume(); 2760 continue; 2761 } 2762 else 2763 { 2764 exe_ctx.process->RestoreProcessEvents (); 2765 return lldb::eExecutionInterrupted; 2766 } 2767 } 2768 } 2769 else 2770 { 2771 2772 if (log) 2773 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.", 2774 halt_error.AsCString()); 2775 // abort(); 2776 2777 if (single_thread_timeout_usec != 0) 2778 { 2779 real_timeout = TimeValue::Now(); 2780 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec); 2781 timeout_ptr = &real_timeout; 2782 } 2783 continue; 2784 } 2785 2786 } 2787 2788 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2789 if (log) 2790 log->Printf("Process::RunThreadPlan(): got event: %s.", StateAsCString(stop_state)); 2791 2792 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping) 2793 continue; 2794 2795 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get())) 2796 { 2797 if (log) 2798 log->Printf("Process::RunThreadPlan(): thread plan is done"); 2799 return_value = lldb::eExecutionCompleted; 2800 break; 2801 } 2802 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get())) 2803 { 2804 if (log) 2805 log->Printf("Process::RunThreadPlan(): thread plan was discarded"); 2806 return_value = lldb::eExecutionDiscarded; 2807 break; 2808 } 2809 else 2810 { 2811 if (log) 2812 { 2813 StreamString s; 2814 if (event_sp) 2815 event_sp->Dump (&s); 2816 else 2817 { 2818 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL."); 2819 } 2820 2821 StreamString ts; 2822 2823 const char *event_explanation; 2824 2825 do 2826 { 2827 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get()); 2828 2829 if (!event_data) 2830 { 2831 event_explanation = "<no event data>"; 2832 break; 2833 } 2834 2835 Process *process = event_data->GetProcessSP().get(); 2836 2837 if (!process) 2838 { 2839 event_explanation = "<no process>"; 2840 break; 2841 } 2842 2843 ThreadList &thread_list = process->GetThreadList(); 2844 2845 uint32_t num_threads = thread_list.GetSize(); 2846 uint32_t thread_index; 2847 2848 ts.Printf("<%u threads> ", num_threads); 2849 2850 for (thread_index = 0; 2851 thread_index < num_threads; 2852 ++thread_index) 2853 { 2854 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 2855 2856 if (!thread) 2857 { 2858 ts.Printf("<?> "); 2859 continue; 2860 } 2861 2862 ts.Printf("<0x%4.4x ", thread->GetID()); 2863 RegisterContext *register_context = thread->GetRegisterContext().get(); 2864 2865 if (register_context) 2866 ts.Printf("[ip 0x%llx] ", register_context->GetPC()); 2867 else 2868 ts.Printf("[ip unknown] "); 2869 2870 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo(); 2871 if (stop_info_sp) 2872 { 2873 const char *stop_desc = stop_info_sp->GetDescription(); 2874 if (stop_desc) 2875 ts.PutCString (stop_desc); 2876 } 2877 ts.Printf(">"); 2878 } 2879 2880 event_explanation = ts.GetData(); 2881 } while (0); 2882 2883 // See if any of the threads that stopped think we ought to stop. Otherwise continue on. 2884 if (!GetThreadList().ShouldStop(event_sp.get())) 2885 { 2886 if (log) 2887 log->Printf("Process::RunThreadPlan(): execution interrupted, but nobody wanted to stop, so we continued: %s %s", 2888 s.GetData(), event_explanation); 2889 if (single_thread_timeout_usec != 0) 2890 { 2891 real_timeout = TimeValue::Now(); 2892 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec); 2893 timeout_ptr = &real_timeout; 2894 } 2895 2896 continue; 2897 } 2898 else 2899 { 2900 if (log) 2901 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation); 2902 } 2903 } 2904 2905 if (discard_on_error && thread_plan_sp) 2906 { 2907 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 2908 } 2909 return_value = lldb::eExecutionInterrupted; 2910 break; 2911 } 2912 } 2913 2914 if (exe_ctx.process) 2915 exe_ctx.process->RestoreProcessEvents (); 2916 2917 // Thread we ran the function in may have gone away because we ran the target 2918 // Check that it's still there. 2919 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get(); 2920 if (exe_ctx.thread) 2921 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get(); 2922 2923 // Also restore the current process'es selected frame & thread, since this function calling may 2924 // be done behind the user's back. 2925 2926 if (selected_tid != LLDB_INVALID_THREAD_ID) 2927 { 2928 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid)) 2929 { 2930 // We were able to restore the selected thread, now restore the frame: 2931 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get()); 2932 } 2933 } 2934 2935 return return_value; 2936 } 2937 2938 const char * 2939 Process::ExecutionResultAsCString (ExecutionResults result) 2940 { 2941 const char *result_name; 2942 2943 switch (result) 2944 { 2945 case lldb::eExecutionCompleted: 2946 result_name = "eExecutionCompleted"; 2947 break; 2948 case lldb::eExecutionDiscarded: 2949 result_name = "eExecutionDiscarded"; 2950 break; 2951 case lldb::eExecutionInterrupted: 2952 result_name = "eExecutionInterrupted"; 2953 break; 2954 case lldb::eExecutionSetupError: 2955 result_name = "eExecutionSetupError"; 2956 break; 2957 case lldb::eExecutionTimedOut: 2958 result_name = "eExecutionTimedOut"; 2959 break; 2960 } 2961 return result_name; 2962 } 2963 2964 //-------------------------------------------------------------- 2965 // class Process::SettingsController 2966 //-------------------------------------------------------------- 2967 2968 Process::SettingsController::SettingsController () : 2969 UserSettingsController ("process", Target::GetSettingsController()) 2970 { 2971 m_default_settings.reset (new ProcessInstanceSettings (*this, 2972 false, 2973 InstanceSettings::GetDefaultName().AsCString())); 2974 } 2975 2976 Process::SettingsController::~SettingsController () 2977 { 2978 } 2979 2980 lldb::InstanceSettingsSP 2981 Process::SettingsController::CreateInstanceSettings (const char *instance_name) 2982 { 2983 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(), 2984 false, 2985 instance_name); 2986 lldb::InstanceSettingsSP new_settings_sp (new_settings); 2987 return new_settings_sp; 2988 } 2989 2990 //-------------------------------------------------------------- 2991 // class ProcessInstanceSettings 2992 //-------------------------------------------------------------- 2993 2994 ProcessInstanceSettings::ProcessInstanceSettings 2995 ( 2996 UserSettingsController &owner, 2997 bool live_instance, 2998 const char *name 2999 ) : 3000 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance), 3001 m_run_args (), 3002 m_env_vars (), 3003 m_input_path (), 3004 m_output_path (), 3005 m_error_path (), 3006 m_plugin (), 3007 m_disable_aslr (true), 3008 m_disable_stdio (false), 3009 m_inherit_host_env (true), 3010 m_got_host_env (false) 3011 { 3012 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called 3013 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers. 3014 // For this reason it has to be called here, rather than in the initializer or in the parent constructor. 3015 // This is true for CreateInstanceName() too. 3016 3017 if (GetInstanceName () == InstanceSettings::InvalidName()) 3018 { 3019 ChangeInstanceName (std::string (CreateInstanceName().AsCString())); 3020 m_owner.RegisterInstanceSettings (this); 3021 } 3022 3023 if (live_instance) 3024 { 3025 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name); 3026 CopyInstanceSettings (pending_settings,false); 3027 //m_owner.RemovePendingSettings (m_instance_name); 3028 } 3029 } 3030 3031 ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) : 3032 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()), 3033 m_run_args (rhs.m_run_args), 3034 m_env_vars (rhs.m_env_vars), 3035 m_input_path (rhs.m_input_path), 3036 m_output_path (rhs.m_output_path), 3037 m_error_path (rhs.m_error_path), 3038 m_plugin (rhs.m_plugin), 3039 m_disable_aslr (rhs.m_disable_aslr), 3040 m_disable_stdio (rhs.m_disable_stdio) 3041 { 3042 if (m_instance_name != InstanceSettings::GetDefaultName()) 3043 { 3044 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name); 3045 CopyInstanceSettings (pending_settings,false); 3046 m_owner.RemovePendingSettings (m_instance_name); 3047 } 3048 } 3049 3050 ProcessInstanceSettings::~ProcessInstanceSettings () 3051 { 3052 } 3053 3054 ProcessInstanceSettings& 3055 ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs) 3056 { 3057 if (this != &rhs) 3058 { 3059 m_run_args = rhs.m_run_args; 3060 m_env_vars = rhs.m_env_vars; 3061 m_input_path = rhs.m_input_path; 3062 m_output_path = rhs.m_output_path; 3063 m_error_path = rhs.m_error_path; 3064 m_plugin = rhs.m_plugin; 3065 m_disable_aslr = rhs.m_disable_aslr; 3066 m_disable_stdio = rhs.m_disable_stdio; 3067 m_inherit_host_env = rhs.m_inherit_host_env; 3068 } 3069 3070 return *this; 3071 } 3072 3073 3074 void 3075 ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name, 3076 const char *index_value, 3077 const char *value, 3078 const ConstString &instance_name, 3079 const SettingEntry &entry, 3080 lldb::VarSetOperationType op, 3081 Error &err, 3082 bool pending) 3083 { 3084 if (var_name == RunArgsVarName()) 3085 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err); 3086 else if (var_name == EnvVarsVarName()) 3087 { 3088 GetHostEnvironmentIfNeeded (); 3089 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err); 3090 } 3091 else if (var_name == InputPathVarName()) 3092 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err); 3093 else if (var_name == OutputPathVarName()) 3094 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err); 3095 else if (var_name == ErrorPathVarName()) 3096 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err); 3097 else if (var_name == PluginVarName()) 3098 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err); 3099 else if (var_name == InheritHostEnvVarName()) 3100 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err); 3101 else if (var_name == DisableASLRVarName()) 3102 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err); 3103 else if (var_name == DisableSTDIOVarName ()) 3104 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err); 3105 } 3106 3107 void 3108 ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, 3109 bool pending) 3110 { 3111 if (new_settings.get() == NULL) 3112 return; 3113 3114 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get(); 3115 3116 m_run_args = new_process_settings->m_run_args; 3117 m_env_vars = new_process_settings->m_env_vars; 3118 m_input_path = new_process_settings->m_input_path; 3119 m_output_path = new_process_settings->m_output_path; 3120 m_error_path = new_process_settings->m_error_path; 3121 m_plugin = new_process_settings->m_plugin; 3122 m_disable_aslr = new_process_settings->m_disable_aslr; 3123 m_disable_stdio = new_process_settings->m_disable_stdio; 3124 } 3125 3126 bool 3127 ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry, 3128 const ConstString &var_name, 3129 StringList &value, 3130 Error *err) 3131 { 3132 if (var_name == RunArgsVarName()) 3133 { 3134 if (m_run_args.GetArgumentCount() > 0) 3135 { 3136 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i) 3137 value.AppendString (m_run_args.GetArgumentAtIndex (i)); 3138 } 3139 } 3140 else if (var_name == EnvVarsVarName()) 3141 { 3142 GetHostEnvironmentIfNeeded (); 3143 3144 if (m_env_vars.size() > 0) 3145 { 3146 std::map<std::string, std::string>::iterator pos; 3147 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos) 3148 { 3149 StreamString value_str; 3150 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str()); 3151 value.AppendString (value_str.GetData()); 3152 } 3153 } 3154 } 3155 else if (var_name == InputPathVarName()) 3156 { 3157 value.AppendString (m_input_path.c_str()); 3158 } 3159 else if (var_name == OutputPathVarName()) 3160 { 3161 value.AppendString (m_output_path.c_str()); 3162 } 3163 else if (var_name == ErrorPathVarName()) 3164 { 3165 value.AppendString (m_error_path.c_str()); 3166 } 3167 else if (var_name == PluginVarName()) 3168 { 3169 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin)); 3170 } 3171 else if (var_name == InheritHostEnvVarName()) 3172 { 3173 if (m_inherit_host_env) 3174 value.AppendString ("true"); 3175 else 3176 value.AppendString ("false"); 3177 } 3178 else if (var_name == DisableASLRVarName()) 3179 { 3180 if (m_disable_aslr) 3181 value.AppendString ("true"); 3182 else 3183 value.AppendString ("false"); 3184 } 3185 else if (var_name == DisableSTDIOVarName()) 3186 { 3187 if (m_disable_stdio) 3188 value.AppendString ("true"); 3189 else 3190 value.AppendString ("false"); 3191 } 3192 else 3193 { 3194 if (err) 3195 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString()); 3196 return false; 3197 } 3198 return true; 3199 } 3200 3201 const ConstString 3202 ProcessInstanceSettings::CreateInstanceName () 3203 { 3204 static int instance_count = 1; 3205 StreamString sstr; 3206 3207 sstr.Printf ("process_%d", instance_count); 3208 ++instance_count; 3209 3210 const ConstString ret_val (sstr.GetData()); 3211 return ret_val; 3212 } 3213 3214 const ConstString & 3215 ProcessInstanceSettings::RunArgsVarName () 3216 { 3217 static ConstString run_args_var_name ("run-args"); 3218 3219 return run_args_var_name; 3220 } 3221 3222 const ConstString & 3223 ProcessInstanceSettings::EnvVarsVarName () 3224 { 3225 static ConstString env_vars_var_name ("env-vars"); 3226 3227 return env_vars_var_name; 3228 } 3229 3230 const ConstString & 3231 ProcessInstanceSettings::InheritHostEnvVarName () 3232 { 3233 static ConstString g_name ("inherit-env"); 3234 3235 return g_name; 3236 } 3237 3238 const ConstString & 3239 ProcessInstanceSettings::InputPathVarName () 3240 { 3241 static ConstString input_path_var_name ("input-path"); 3242 3243 return input_path_var_name; 3244 } 3245 3246 const ConstString & 3247 ProcessInstanceSettings::OutputPathVarName () 3248 { 3249 static ConstString output_path_var_name ("output-path"); 3250 3251 return output_path_var_name; 3252 } 3253 3254 const ConstString & 3255 ProcessInstanceSettings::ErrorPathVarName () 3256 { 3257 static ConstString error_path_var_name ("error-path"); 3258 3259 return error_path_var_name; 3260 } 3261 3262 const ConstString & 3263 ProcessInstanceSettings::PluginVarName () 3264 { 3265 static ConstString plugin_var_name ("plugin"); 3266 3267 return plugin_var_name; 3268 } 3269 3270 3271 const ConstString & 3272 ProcessInstanceSettings::DisableASLRVarName () 3273 { 3274 static ConstString disable_aslr_var_name ("disable-aslr"); 3275 3276 return disable_aslr_var_name; 3277 } 3278 3279 const ConstString & 3280 ProcessInstanceSettings::DisableSTDIOVarName () 3281 { 3282 static ConstString disable_stdio_var_name ("disable-stdio"); 3283 3284 return disable_stdio_var_name; 3285 } 3286 3287 //-------------------------------------------------- 3288 // SettingsController Variable Tables 3289 //-------------------------------------------------- 3290 3291 SettingEntry 3292 Process::SettingsController::global_settings_table[] = 3293 { 3294 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"}, 3295 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL } 3296 }; 3297 3298 3299 lldb::OptionEnumValueElement 3300 Process::SettingsController::g_plugins[] = 3301 { 3302 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" }, 3303 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" }, 3304 { 0, NULL, NULL } 3305 }; 3306 3307 SettingEntry 3308 Process::SettingsController::instance_settings_table[] = 3309 { 3310 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"}, 3311 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." }, 3312 { "env-vars", eSetVarTypeDictionary, NULL, NULL, false, false, "A list of all the environment variables to be passed to the executable's environment, and their values." }, 3313 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." }, 3314 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." }, 3315 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." }, 3316 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." }, 3317 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." }, 3318 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" }, 3319 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" }, 3320 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL } 3321 }; 3322 3323 3324 3325