llvm-project/lldb/source/Target/Thread.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

2015 lines
70 KiB
C++
Raw Normal View History

//===-- Thread.cpp --------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/Thread.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
There are now to new "settings set" variables that live in each debugger instance: settings set frame-format <string> settings set thread-format <string> This allows users to control the information that is seen when dumping threads and frames. The default values are set such that they do what they used to do prior to changing over the the user defined formats. This allows users with terminals that can display color to make different items different colors using the escape control codes. A few alias examples that will colorize your thread and frame prompts are: settings set frame-format 'frame #${frame.index}: \033[0;33m${frame.pc}\033[0m{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{ \033[0;35mat \033[1;35m${line.file.basename}:${line.number}}\033[0m\n' settings set thread-format 'thread #${thread.index}: \033[1;33mtid\033[0;33m = ${thread.id}\033[0m{, \033[0;33m${frame.pc}\033[0m}{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{, \033[1;35mstop reason\033[0;35m = ${thread.stop-reason}\033[0m}{, \033[1;36mname = \033[0;36m${thread.name}\033[0m}{, \033[1;32mqueue = \033[0;32m${thread.queue}}\033[0m\n' A quick web search for "colorize terminal output" should allow you to see what you can do to make your output look like you want it. The "settings set" commands above can of course be added to your ~/.lldbinit file for permanent use. Changed the pure virtual void ExecutionContextScope::Calculate (ExecutionContext&); To: void ExecutionContextScope::CalculateExecutionContext (ExecutionContext&); I did this because this is a class that anything in the execution context heirarchy inherits from and "target->Calculate (exe_ctx)" didn't always tell you what it was really trying to do unless you look at the parameter. llvm-svn: 115485
2010-10-04 09:05:56 +08:00
#include "lldb/Core/Debugger.h"
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
#include "lldb/Core/FormatEntity.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/StructuredDataImpl.h"
#include "lldb/Core/ValueObject.h"
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
#include "lldb/Host/Host.h"
#include "lldb/Interpreter/OptionValueFileSpecList.h"
#include "lldb/Interpreter/OptionValueProperties.h"
#include "lldb/Interpreter/Property.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Target/ABI.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/LanguageRuntime.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrameRecognizer.h"
Abtracted the old "lldb_private::Thread::StopInfo" into an abtract class. This will allow debugger plug-ins to make any instance of "lldb_private::StopInfo" that can completely describe any stop reason. It also provides a framework for doing intelligent things with the stop info at important times in the lifetime of the inferior. Examples include the signal stop info in StopInfoUnixSignal. It will check with the process to see that the current action is for the signal. These actions include wether to stop for the signal, wether the notify that the signal was hit, and wether to pass the signal along to the inferior process. The StopInfoUnixSignal class overrides the "ShouldStop()" method of StopInfo and this allows the stop info to determine if it should stop at the signal or continue the process. StopInfo subclasses must override the following functions: virtual lldb::StopReason GetStopReason () const = 0; virtual const char * GetDescription () = 0; StopInfo subclasses can override the following functions: // If the subclass returns "false", the inferior will resume. The default // version of this function returns "true" which means the default stop // info will stop the process. The breakpoint subclass will check if // the breakpoint wants us to stop by calling any installed callback on // the breakpoint, and also checking if the breakpoint is for the current // thread. Signals will check if they should stop based off of the // UnixSignal settings in the process. virtual bool ShouldStop (Event *event_ptr); // Sublasses can state if they want to notify the debugger when "ShouldStop" // returns false. This would be handy for breakpoints where you want to // log information and continue and is also used by the signal stop info // to notify that a signal was received (after it checks with the process // signal settings). virtual bool ShouldNotify (Event *event_ptr) { return false; } // Allow subclasses to do something intelligent right before we resume. // The signal class will figure out if the signal should be propagated // to the inferior process and pass that along to the debugger plug-ins. virtual void WillResume (lldb::StateType resume_state) { // By default, don't do anything } The support the Mach exceptions was moved into the lldb/source/Plugins/Process/Utility folder and now doesn't polute the lldb_private::Thread class with platform specific code. llvm-svn: 110184
2010-08-04 09:40:35 +08:00
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/SystemRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/ThreadPlan.h"
#include "lldb/Target/ThreadPlanBase.h"
#include "lldb/Target/ThreadPlanCallFunction.h"
#include "lldb/Target/ThreadPlanPython.h"
#include "lldb/Target/ThreadPlanRunToAddress.h"
#include "lldb/Target/ThreadPlanStack.h"
#include "lldb/Target/ThreadPlanStepInRange.h"
#include "lldb/Target/ThreadPlanStepInstruction.h"
#include "lldb/Target/ThreadPlanStepOut.h"
#include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
#include "lldb/Target/ThreadPlanStepOverRange.h"
#include "lldb/Target/ThreadPlanStepThrough.h"
#include "lldb/Target/ThreadPlanStepUntil.h"
#include "lldb/Target/ThreadSpec.h"
#include "lldb/Target/UnwindLLDB.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/RegularExpression.h"
#include "lldb/Utility/State.h"
#include "lldb/Utility/Stream.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/lldb-enumerations.h"
#include <memory>
using namespace lldb;
using namespace lldb_private;
const ThreadPropertiesSP &Thread::GetGlobalProperties() {
// NOTE: intentional leak so we don't crash if global destructor chain gets
// called as other threads still use the result of this function
static ThreadPropertiesSP *g_settings_sp_ptr =
new ThreadPropertiesSP(new ThreadProperties(true));
return *g_settings_sp_ptr;
}
#define LLDB_PROPERTIES_thread
#include "TargetProperties.inc"
enum {
#define LLDB_PROPERTIES_thread
#include "TargetPropertiesEnum.inc"
};
class ThreadOptionValueProperties : public OptionValueProperties {
public:
ThreadOptionValueProperties(ConstString name)
: OptionValueProperties(name) {}
// This constructor is used when creating ThreadOptionValueProperties when it
// is part of a new lldb_private::Thread instance. It will copy all current
// global property values as needed
ThreadOptionValueProperties(ThreadProperties *global_properties)
: OptionValueProperties(*global_properties->GetValueProperties()) {}
const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
bool will_modify,
uint32_t idx) const override {
2014-07-02 05:22:11 +08:00
// When getting the value for a key from the thread options, we will always
// try and grab the setting from the current thread if there is one. Else
// we just use the one from this instance.
if (exe_ctx) {
Thread *thread = exe_ctx->GetThreadPtr();
if (thread) {
ThreadOptionValueProperties *instance_properties =
static_cast<ThreadOptionValueProperties *>(
thread->GetValueProperties().get());
if (this != instance_properties)
return instance_properties->ProtectedGetPropertyAtIndex(idx);
}
}
return ProtectedGetPropertyAtIndex(idx);
}
};
ThreadProperties::ThreadProperties(bool is_global) : Properties() {
if (is_global) {
m_collection_sp =
std::make_shared<ThreadOptionValueProperties>(ConstString("thread"));
m_collection_sp->Initialize(g_thread_properties);
} else
m_collection_sp = std::make_shared<ThreadOptionValueProperties>(
Thread::GetGlobalProperties().get());
}
ThreadProperties::~ThreadProperties() = default;
const RegularExpression *ThreadProperties::GetSymbolsToAvoidRegexp() {
const uint32_t idx = ePropertyStepAvoidRegex;
return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex(nullptr, idx);
}
FileSpecList ThreadProperties::GetLibrariesToAvoid() const {
const uint32_t idx = ePropertyStepAvoidLibraries;
const OptionValueFileSpecList *option_value =
m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
false, idx);
assert(option_value);
return option_value->GetCurrentValue();
}
bool ThreadProperties::GetTraceEnabledState() const {
const uint32_t idx = ePropertyEnableThreadTrace;
return m_collection_sp->GetPropertyAtIndexAsBoolean(
nullptr, idx, g_thread_properties[idx].default_uint_value != 0);
}
bool ThreadProperties::GetStepInAvoidsNoDebug() const {
const uint32_t idx = ePropertyStepInAvoidsNoDebug;
return m_collection_sp->GetPropertyAtIndexAsBoolean(
nullptr, idx, g_thread_properties[idx].default_uint_value != 0);
}
bool ThreadProperties::GetStepOutAvoidsNoDebug() const {
const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
return m_collection_sp->GetPropertyAtIndexAsBoolean(
nullptr, idx, g_thread_properties[idx].default_uint_value != 0);
}
uint64_t ThreadProperties::GetMaxBacktraceDepth() const {
const uint32_t idx = ePropertyMaxBacktraceDepth;
return m_collection_sp->GetPropertyAtIndexAsUInt64(
nullptr, idx, g_thread_properties[idx].default_uint_value != 0);
}
// Thread Event Data
ConstString Thread::ThreadEventData::GetFlavorString() {
static ConstString g_flavor("Thread::ThreadEventData");
return g_flavor;
}
Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp)
: m_thread_sp(thread_sp), m_stack_id() {}
Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp,
const StackID &stack_id)
: m_thread_sp(thread_sp), m_stack_id(stack_id) {}
Thread::ThreadEventData::ThreadEventData() : m_thread_sp(), m_stack_id() {}
Thread::ThreadEventData::~ThreadEventData() = default;
void Thread::ThreadEventData::Dump(Stream *s) const {}
const Thread::ThreadEventData *
Thread::ThreadEventData::GetEventDataFromEvent(const Event *event_ptr) {
if (event_ptr) {
const EventData *event_data = event_ptr->GetData();
if (event_data &&
event_data->GetFlavor() == ThreadEventData::GetFlavorString())
return static_cast<const ThreadEventData *>(event_ptr->GetData());
}
return nullptr;
}
ThreadSP Thread::ThreadEventData::GetThreadFromEvent(const Event *event_ptr) {
ThreadSP thread_sp;
const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
if (event_data)
thread_sp = event_data->GetThread();
return thread_sp;
}
StackID Thread::ThreadEventData::GetStackIDFromEvent(const Event *event_ptr) {
StackID stack_id;
const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
if (event_data)
stack_id = event_data->GetStackID();
return stack_id;
}
StackFrameSP
Thread::ThreadEventData::GetStackFrameFromEvent(const Event *event_ptr) {
const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
StackFrameSP frame_sp;
if (event_data) {
ThreadSP thread_sp = event_data->GetThread();
if (thread_sp) {
frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID(
event_data->GetStackID());
}
}
return frame_sp;
}
// Thread class
ConstString &Thread::GetStaticBroadcasterClass() {
static ConstString class_name("lldb.thread");
return class_name;
}
Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)
: ThreadProperties(false), UserID(tid),
Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(),
Thread::GetStaticBroadcasterClass().AsCString()),
m_process_wp(process.shared_from_this()), m_stop_info_sp(),
m_stop_info_stop_id(0), m_stop_info_override_stop_id(0),
m_index_id(use_invalid_index_id ? LLDB_INVALID_INDEX32
: process.GetNextThreadIndexID(tid)),
m_reg_context_sp(), m_state(eStateUnloaded), m_state_mutex(),
m_frame_mutex(), m_curr_frames_sp(), m_prev_frames_sp(),
m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),
m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning),
m_unwinder_up(), m_destroy_called(false),
m_override_should_notify(eLazyBoolCalculate),
m_extended_info_fetched(false), m_extended_info() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
LLDB_LOGF(log, "%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
static_cast<void *>(this), GetID());
CheckInWithManager();
}
Thread::~Thread() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
LLDB_LOGF(log, "%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
static_cast<void *>(this), GetID());
/// If you hit this assert, it means your derived class forgot to call
/// DoDestroy in its destructor.
assert(m_destroy_called);
}
void Thread::DestroyThread() {
m_destroy_called = true;
m_stop_info_sp.reset();
m_reg_context_sp.reset();
m_unwinder_up.reset();
std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
m_curr_frames_sp.reset();
m_prev_frames_sp.reset();
}
void Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) {
if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
BroadcastEvent(eBroadcastBitSelectedFrameChanged,
new ThreadEventData(this->shared_from_this(), new_frame_id));
}
lldb::StackFrameSP Thread::GetSelectedFrame() {
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
StackFrameListSP stack_frame_list_sp(GetStackFrameList());
StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(
stack_frame_list_sp->GetSelectedFrameIndex());
FrameSelectedCallback(frame_sp.get());
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
return frame_sp;
}
uint32_t Thread::SetSelectedFrame(lldb_private::StackFrame *frame,
bool broadcast) {
uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
if (broadcast)
BroadcastSelectedFrameChange(frame->GetStackID());
FrameSelectedCallback(frame);
return ret_value;
}
bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {
StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));
if (frame_sp) {
GetStackFrameList()->SetSelectedFrame(frame_sp.get());
if (broadcast)
BroadcastSelectedFrameChange(frame_sp->GetStackID());
FrameSelectedCallback(frame_sp.get());
return true;
} else
return false;
}
bool Thread::SetSelectedFrameByIndexNoisily(uint32_t frame_idx,
Stream &output_stream) {
const bool broadcast = true;
bool success = SetSelectedFrameByIndex(frame_idx, broadcast);
if (success) {
StackFrameSP frame_sp = GetSelectedFrame();
if (frame_sp) {
bool already_shown = false;
SymbolContext frame_sc(
frame_sp->GetSymbolContext(eSymbolContextLineEntry));
if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() &&
frame_sc.line_entry.file && frame_sc.line_entry.line != 0) {
already_shown = Host::OpenFileInExternalEditor(
frame_sc.line_entry.file, frame_sc.line_entry.line);
}
bool show_frame_info = true;
bool show_source = !already_shown;
FrameSelectedCallback(frame_sp.get());
return frame_sp->GetStatus(output_stream, show_frame_info, show_source);
}
return false;
} else
return false;
}
void Thread::FrameSelectedCallback(StackFrame *frame) {
if (!frame)
return;
if (frame->HasDebugInformation() &&
(GetProcess()->GetWarningsOptimization() ||
GetProcess()->GetWarningsUnsupportedLanguage())) {
SymbolContext sc =
frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);
GetProcess()->PrintWarningOptimization(sc);
GetProcess()->PrintWarningUnsupportedLanguage(sc);
}
}
lldb::StopInfoSP Thread::GetStopInfo() {
if (m_destroy_called)
return m_stop_info_sp;
ThreadPlanSP completed_plan_sp(GetCompletedPlan());
ProcessSP process_sp(GetProcess());
const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
// Here we select the stop info according to priorirty: - m_stop_info_sp (if
// not trace) - preset value - completed plan stop info - new value with plan
// from completed plan stack - m_stop_info_sp (trace stop reason is OK now) -
// ask GetPrivateStopInfo to set stop info
bool have_valid_stop_info = m_stop_info_sp &&
m_stop_info_sp ->IsValid() &&
m_stop_info_stop_id == stop_id;
bool have_valid_completed_plan = completed_plan_sp && completed_plan_sp->PlanSucceeded();
bool plan_failed = completed_plan_sp && !completed_plan_sp->PlanSucceeded();
bool plan_overrides_trace =
have_valid_stop_info && have_valid_completed_plan
&& (m_stop_info_sp->GetStopReason() == eStopReasonTrace);
if (have_valid_stop_info && !plan_overrides_trace && !plan_failed) {
return m_stop_info_sp;
} else if (completed_plan_sp) {
return StopInfo::CreateStopReasonWithPlan(
completed_plan_sp, GetReturnValueObject(), GetExpressionVariable());
} else {
GetPrivateStopInfo();
return m_stop_info_sp;
}
}
void Thread::CalculatePublicStopInfo() {
ResetStopInfo();
SetStopInfo(GetStopInfo());
}
lldb::StopInfoSP Thread::GetPrivateStopInfo() {
if (m_destroy_called)
return m_stop_info_sp;
ProcessSP process_sp(GetProcess());
if (process_sp) {
const uint32_t process_stop_id = process_sp->GetStopID();
if (m_stop_info_stop_id != process_stop_id) {
if (m_stop_info_sp) {
if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||
GetCurrentPlan()->IsVirtualStep())
SetStopInfo(m_stop_info_sp);
else
m_stop_info_sp.reset();
}
if (!m_stop_info_sp) {
if (!CalculateStopInfo())
SetStopInfo(StopInfoSP());
}
}
// The stop info can be manually set by calling Thread::SetStopInfo() prior
// to this function ever getting called, so we can't rely on
// "m_stop_info_stop_id != process_stop_id" as the condition for the if
// statement below, we must also check the stop info to see if we need to
// override it. See the header documentation in
// Architecture::OverrideStopInfo() for more information on the stop
// info override callback.
if (m_stop_info_override_stop_id != process_stop_id) {
m_stop_info_override_stop_id = process_stop_id;
if (m_stop_info_sp) {
if (const Architecture *arch =
process_sp->GetTarget().GetArchitecturePlugin())
arch->OverrideStopInfo(*this);
}
}
}
return m_stop_info_sp;
}
lldb::StopReason Thread::GetStopReason() {
lldb::StopInfoSP stop_info_sp(GetStopInfo());
if (stop_info_sp)
return stop_info_sp->GetStopReason();
return eStopReasonNone;
}
bool Thread::StopInfoIsUpToDate() const {
ProcessSP process_sp(GetProcess());
if (process_sp)
return m_stop_info_stop_id == process_sp->GetStopID();
else
return true; // Process is no longer around so stop info is always up to
// date...
}
void Thread::ResetStopInfo() {
if (m_stop_info_sp) {
m_stop_info_sp.reset();
}
}
void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {
m_stop_info_sp = stop_info_sp;
if (m_stop_info_sp) {
m_stop_info_sp->MakeStopInfoValid();
// If we are overriding the ShouldReportStop, do that here:
if (m_override_should_notify != eLazyBoolCalculate)
m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
eLazyBoolYes);
}
ProcessSP process_sp(GetProcess());
if (process_sp)
m_stop_info_stop_id = process_sp->GetStopID();
else
m_stop_info_stop_id = UINT32_MAX;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
LLDB_LOGF(log, "%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
static_cast<void *>(this), GetID(),
stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
m_stop_info_stop_id);
}
void Thread::SetShouldReportStop(Vote vote) {
if (vote == eVoteNoOpinion)
return;
else {
m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
if (m_stop_info_sp)
m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
eLazyBoolYes);
}
}
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
void Thread::SetStopInfoToNothing() {
// Note, we can't just NULL out the private reason, or the native thread
// implementation will try to go calculate it again. For now, just set it to
// a Unix Signal with an invalid signal number.
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
SetStopInfo(
StopInfo::CreateStopReasonWithSignal(*this, LLDB_INVALID_SIGNAL_NUMBER));
}
bool Thread::ThreadStoppedForAReason(void) {
return (bool)GetPrivateStopInfo();
}
bool Thread::CheckpointThreadState(ThreadStateCheckpoint &saved_state) {
saved_state.register_backup_sp.reset();
lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
if (frame_sp) {
lldb::RegisterCheckpointSP reg_checkpoint_sp(
new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
if (reg_checkpoint_sp) {
lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))
saved_state.register_backup_sp = reg_checkpoint_sp;
}
}
if (!saved_state.register_backup_sp)
return false;
saved_state.stop_info_sp = GetStopInfo();
ProcessSP process_sp(GetProcess());
if (process_sp)
saved_state.orig_stop_id = process_sp->GetStopID();
saved_state.current_inlined_depth = GetCurrentInlinedDepth();
saved_state.m_completed_plan_checkpoint =
GetPlans().CheckpointCompletedPlans();
return true;
}
bool Thread::RestoreRegisterStateFromCheckpoint(
ThreadStateCheckpoint &saved_state) {
if (saved_state.register_backup_sp) {
lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
if (frame_sp) {
lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
if (reg_ctx_sp) {
bool ret =
reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);
// Clear out all stack frames as our world just changed.
ClearStackFrames();
reg_ctx_sp->InvalidateIfNeeded(true);
if (m_unwinder_up)
m_unwinder_up->Clear();
return ret;
}
}
}
return false;
}
bool Thread::RestoreThreadStateFromCheckpoint(
ThreadStateCheckpoint &saved_state) {
if (saved_state.stop_info_sp)
saved_state.stop_info_sp->MakeStopInfoValid();
SetStopInfo(saved_state.stop_info_sp);
GetStackFrameList()->SetCurrentInlinedDepth(
saved_state.current_inlined_depth);
GetPlans().RestoreCompletedPlanCheckpoint(
saved_state.m_completed_plan_checkpoint);
return true;
}
StateType Thread::GetState() const {
// If any other threads access this we will need a mutex for it
std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
return m_state;
}
void Thread::SetState(StateType state) {
std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
m_state = state;
}
std::string Thread::GetStopDescription() {
StackFrameSP frame_sp = GetStackFrameAtIndex(0);
if (!frame_sp)
return GetStopDescriptionRaw();
auto recognized_frame_sp = frame_sp->GetRecognizedFrame();
if (!recognized_frame_sp)
return GetStopDescriptionRaw();
std::string recognized_stop_description =
recognized_frame_sp->GetStopDescription();
if (!recognized_stop_description.empty())
return recognized_stop_description;
return GetStopDescriptionRaw();
}
std::string Thread::GetStopDescriptionRaw() {
StopInfoSP stop_info_sp = GetStopInfo();
std::string raw_stop_description;
if (stop_info_sp && stop_info_sp->IsValid()) {
raw_stop_description = stop_info_sp->GetDescription();
assert((!raw_stop_description.empty() ||
stop_info_sp->GetStopReason() == eStopReasonNone) &&
"StopInfo returned an empty description.");
}
return raw_stop_description;
}
void Thread::SelectMostRelevantFrame() {
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
auto frames_list_sp = GetStackFrameList();
// Only the top frame should be recognized.
auto frame_sp = frames_list_sp->GetFrameAtIndex(0);
auto recognized_frame_sp = frame_sp->GetRecognizedFrame();
if (!recognized_frame_sp) {
LLDB_LOG(log, "Frame #0 not recognized");
return;
}
if (StackFrameSP most_relevant_frame_sp =
recognized_frame_sp->GetMostRelevantFrame()) {
LLDB_LOG(log, "Found most relevant frame at index {0}",
most_relevant_frame_sp->GetFrameIndex());
SetSelectedFrame(most_relevant_frame_sp.get());
} else {
LLDB_LOG(log, "No relevant frame!");
}
}
void Thread::WillStop() {
ThreadPlan *current_plan = GetCurrentPlan();
SelectMostRelevantFrame();
// FIXME: I may decide to disallow threads with no plans. In which
// case this should go to an assert.
if (!current_plan)
return;
current_plan->WillStop();
}
void Thread::SetupForResume() {
if (GetResumeState() != eStateSuspended) {
// If we're at a breakpoint push the step-over breakpoint plan. Do this
// before telling the current plan it will resume, since we might change
// what the current plan is.
lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
if (reg_ctx_sp) {
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
const addr_t thread_pc = reg_ctx_sp->GetPC();
BreakpointSiteSP bp_site_sp =
GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);
if (bp_site_sp) {
// Note, don't assume there's a ThreadPlanStepOverBreakpoint, the
// target may not require anything special to step over a breakpoint.
ThreadPlan *cur_plan = GetCurrentPlan();
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
bool push_step_over_bp_plan = false;
if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
ThreadPlanStepOverBreakpoint *bp_plan =
(ThreadPlanStepOverBreakpoint *)cur_plan;
if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
push_step_over_bp_plan = true;
} else
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
push_step_over_bp_plan = true;
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
if (push_step_over_bp_plan) {
ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
if (step_bp_plan_sp) {
step_bp_plan_sp->SetPrivate(true);
if (GetCurrentPlan()->RunState() != eStateStepping) {
ThreadPlanStepOverBreakpoint *step_bp_plan =
static_cast<ThreadPlanStepOverBreakpoint *>(
step_bp_plan_sp.get());
step_bp_plan->SetAutoContinue(true);
}
QueueThreadPlan(step_bp_plan_sp, false);
}
}
}
}
}
}
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
bool Thread::ShouldResume(StateType resume_state) {
// At this point clear the completed plan stack.
GetPlans().WillResume();
m_override_should_notify = eLazyBoolCalculate;
Second part of indicating when the user is stopped in optimized code. The first part was in r243508 -- the extent of the UI changes in that patchset was to add "[opt]" to the frame-format when a stack frame was built with optimized code. In this change, when a stack frame built with optimization is selected, a message will be printed to the async output channel -- opt1.c was compiled with optimization - stepping may behave oddly; variables may not be available. The warning will be only be printed once per source file in a debug session. These warnings may be disabled by settings set target.process.optimization-warnings false Internally, a new Process::PrintWarning() method has been added for warnings that we want to print only once to the user. It takes a type of warning (currently only eWarningsOptimization) and an object pointer (CompileUnit*) - the warning will only be printed once for a given object pointer value. This is a bit of a prototype of this change - I think we will be tweaking it more in the future. But I wanted to land this and see how it goes. Advanced users will find these warnings unnecessary noise and will quickly disable them - but anyone who maintains a debugger knows that debugging optimized code, without realizing it, is a constant source of confusion and frustation for more typical debugger users. I imagine there will be more of these "warn once per whatever" style warnings that we will want to add in the future and we'll need to come up with a better way for enabling/disabling them. But I'm not srue what form that warning settings should take and I didn't want to code up something that we regret later, so for now I just added another process setting for this one warning. <rdar://problem/19281172> llvm-svn: 244190
2015-08-06 11:27:10 +08:00
Abtracted the old "lldb_private::Thread::StopInfo" into an abtract class. This will allow debugger plug-ins to make any instance of "lldb_private::StopInfo" that can completely describe any stop reason. It also provides a framework for doing intelligent things with the stop info at important times in the lifetime of the inferior. Examples include the signal stop info in StopInfoUnixSignal. It will check with the process to see that the current action is for the signal. These actions include wether to stop for the signal, wether the notify that the signal was hit, and wether to pass the signal along to the inferior process. The StopInfoUnixSignal class overrides the "ShouldStop()" method of StopInfo and this allows the stop info to determine if it should stop at the signal or continue the process. StopInfo subclasses must override the following functions: virtual lldb::StopReason GetStopReason () const = 0; virtual const char * GetDescription () = 0; StopInfo subclasses can override the following functions: // If the subclass returns "false", the inferior will resume. The default // version of this function returns "true" which means the default stop // info will stop the process. The breakpoint subclass will check if // the breakpoint wants us to stop by calling any installed callback on // the breakpoint, and also checking if the breakpoint is for the current // thread. Signals will check if they should stop based off of the // UnixSignal settings in the process. virtual bool ShouldStop (Event *event_ptr); // Sublasses can state if they want to notify the debugger when "ShouldStop" // returns false. This would be handy for breakpoints where you want to // log information and continue and is also used by the signal stop info // to notify that a signal was received (after it checks with the process // signal settings). virtual bool ShouldNotify (Event *event_ptr) { return false; } // Allow subclasses to do something intelligent right before we resume. // The signal class will figure out if the signal should be propagated // to the inferior process and pass that along to the debugger plug-ins. virtual void WillResume (lldb::StateType resume_state) { // By default, don't do anything } The support the Mach exceptions was moved into the lldb/source/Plugins/Process/Utility folder and now doesn't polute the lldb_private::Thread class with platform specific code. llvm-svn: 110184
2010-08-04 09:40:35 +08:00
StateType prev_resume_state = GetTemporaryResumeState();
SetTemporaryResumeState(resume_state);
lldb::ThreadSP backing_thread_sp(GetBackingThread());
if (backing_thread_sp)
backing_thread_sp->SetTemporaryResumeState(resume_state);
// Make sure m_stop_info_sp is valid. Don't do this for threads we suspended
// in the previous run.
if (prev_resume_state != eStateSuspended)
GetPrivateStopInfo();
// This is a little dubious, but we are trying to limit how often we actually
// fetch stop info from the target, 'cause that slows down single stepping.
// So assume that if we got to the point where we're about to resume, and we
// haven't yet had to fetch the stop reason, then it doesn't need to know
// about the fact that we are resuming...
const uint32_t process_stop_id = GetProcess()->GetStopID();
if (m_stop_info_stop_id == process_stop_id &&
(m_stop_info_sp && m_stop_info_sp->IsValid())) {
StopInfo *stop_info = GetPrivateStopInfo().get();
if (stop_info)
stop_info->WillResume(resume_state);
}
// Tell all the plans that we are about to resume in case they need to clear
// any state. We distinguish between the plan on the top of the stack and the
// lower plans in case a plan needs to do any special business before it
// runs.
bool need_to_resume = false;
ThreadPlan *plan_ptr = GetCurrentPlan();
if (plan_ptr) {
need_to_resume = plan_ptr->WillResume(resume_state, true);
while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
plan_ptr->WillResume(resume_state, false);
}
// If the WillResume for the plan says we are faking a resume, then it will
// have set an appropriate stop info. In that case, don't reset it here.
if (need_to_resume && resume_state != eStateSuspended) {
m_stop_info_sp.reset();
}
}
if (need_to_resume) {
ClearStackFrames();
// Let Thread subclasses do any special work they need to prior to resuming
WillResume(resume_state);
}
return need_to_resume;
}
void Thread::DidResume() { SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER); }
void Thread::DidStop() { SetState(eStateStopped); }
bool Thread::ShouldStop(Event *event_ptr) {
ThreadPlan *current_plan = GetCurrentPlan();
bool should_stop = true;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (GetResumeState() == eStateSuspended) {
LLDB_LOGF(log,
"Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
", should_stop = 0 (ignore since thread was suspended)",
__FUNCTION__, GetID(), GetProtocolID());
return false;
}
if (GetTemporaryResumeState() == eStateSuspended) {
LLDB_LOGF(log,
"Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
", should_stop = 0 (ignore since thread was suspended)",
__FUNCTION__, GetID(), GetProtocolID());
return false;
}
// Based on the current thread plan and process stop info, check if this
// thread caused the process to stop. NOTE: this must take place before the
// plan is moved from the current plan stack to the completed plan stack.
if (!ThreadStoppedForAReason()) {
LLDB_LOGF(log,
"Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
", pc = 0x%16.16" PRIx64
", should_stop = 0 (ignore since no stop reason)",
__FUNCTION__, GetID(), GetProtocolID(),
GetRegisterContext() ? GetRegisterContext()->GetPC()
: LLDB_INVALID_ADDRESS);
return false;
}
if (log) {
LLDB_LOGF(log,
"Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
", pc = 0x%16.16" PRIx64,
__FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(),
GetRegisterContext() ? GetRegisterContext()->GetPC()
: LLDB_INVALID_ADDRESS);
LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
StreamString s;
s.IndentMore();
GetProcess()->DumpThreadPlansForTID(
s, GetID(), eDescriptionLevelVerbose, true /* internal */,
false /* condense_trivial */, true /* skip_unreported */);
LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData());
}
// The top most plan always gets to do the trace log...
current_plan->DoTraceLog();
// First query the stop info's ShouldStopSynchronous. This handles
// "synchronous" stop reasons, for example the breakpoint command on internal
// breakpoints. If a synchronous stop reason says we should not stop, then
// we don't have to do any more work on this stop.
StopInfoSP private_stop_info(GetPrivateStopInfo());
if (private_stop_info &&
!private_stop_info->ShouldStopSynchronous(event_ptr)) {
LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not "
"stop, returning ShouldStop of false.");
return false;
}
// If we've already been restarted, don't query the plans since the state
// they would examine is not current.
if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
return false;
// Before the plans see the state of the world, calculate the current inlined
// depth.
GetStackFrameList()->CalculateCurrentInlinedDepth();
// If the base plan doesn't understand why we stopped, then we have to find a
// plan that does. If that plan is still working, then we don't need to do
// any more work. If the plan that explains the stop is done, then we should
// pop all the plans below it, and pop it, and then let the plans above it
// decide whether they still need to do more work.
bool done_processing_current_plan = false;
if (!current_plan->PlanExplainsStop(event_ptr)) {
if (current_plan->TracerExplainsStop()) {
done_processing_current_plan = true;
should_stop = false;
} else {
// If the current plan doesn't explain the stop, then find one that does
// and let it handle the situation.
ThreadPlan *plan_ptr = current_plan;
while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
if (plan_ptr->PlanExplainsStop(event_ptr)) {
should_stop = plan_ptr->ShouldStop(event_ptr);
// plan_ptr explains the stop, next check whether plan_ptr is done,
// if so, then we should take it and all the plans below it off the
// stack.
if (plan_ptr->MischiefManaged()) {
// We're going to pop the plans up to and including the plan that
// explains the stop.
ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
do {
if (should_stop)
current_plan->WillStop();
PopPlan();
} while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
// Now, if the responsible plan was not "Okay to discard" then
// we're done, otherwise we forward this to the next plan in the
// stack below.
done_processing_current_plan =
(plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard());
} else
done_processing_current_plan = true;
break;
}
}
}
}
if (!done_processing_current_plan) {
bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
LLDB_LOGF(log, "Plan %s explains stop, auto-continue %i.",
current_plan->GetName(), over_ride_stop);
// We're starting from the base plan, so just let it decide;
if (current_plan->IsBasePlan()) {
should_stop = current_plan->ShouldStop(event_ptr);
LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop);
} else {
// Otherwise, don't let the base plan override what the other plans say
// to do, since presumably if there were other plans they would know what
// to do...
while (true) {
if (current_plan->IsBasePlan())
break;
should_stop = current_plan->ShouldStop(event_ptr);
LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(),
should_stop);
if (current_plan->MischiefManaged()) {
if (should_stop)
current_plan->WillStop();
// If a Master Plan wants to stop, and wants to stick on the stack,
// we let it. Otherwise, see if the plan's parent wants to stop.
if (should_stop && current_plan->IsMasterPlan() &&
!current_plan->OkayToDiscard()) {
PopPlan();
break;
} else {
PopPlan();
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
current_plan = GetCurrentPlan();
if (current_plan == nullptr) {
break;
}
}
} else {
break;
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
}
}
}
if (over_ride_stop)
should_stop = false;
}
// One other potential problem is that we set up a master plan, then stop in
// before it is complete - for instance by hitting a breakpoint during a
// step-over - then do some step/finish/etc operations that wind up past the
// end point condition of the initial plan. We don't want to strand the
// original plan on the stack, This code clears stale plans off the stack.
if (should_stop) {
ThreadPlan *plan_ptr = GetCurrentPlan();
// Discard the stale plans and all plans below them in the stack, plus move
// the completed plans to the completed plan stack
while (!plan_ptr->IsBasePlan()) {
bool stale = plan_ptr->IsPlanStale();
ThreadPlan *examined_plan = plan_ptr;
plan_ptr = GetPreviousPlan(examined_plan);
if (stale) {
LLDB_LOGF(
log,
"Plan %s being discarded in cleanup, it says it is already done.",
examined_plan->GetName());
while (GetCurrentPlan() != examined_plan) {
DiscardPlan();
}
if (examined_plan->IsPlanComplete()) {
// plan is complete but does not explain the stop (example: step to a
// line with breakpoint), let us move the plan to
// completed_plan_stack anyway
PopPlan();
} else
DiscardPlan();
}
}
}
if (log) {
StreamString s;
s.IndentMore();
GetProcess()->DumpThreadPlansForTID(
s, GetID(), eDescriptionLevelVerbose, true /* internal */,
false /* condense_trivial */, true /* skip_unreported */);
LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());
LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
should_stop);
}
return should_stop;
}
Vote Thread::ShouldReportStop(Event *event_ptr) {
StateType thread_state = GetResumeState();
StateType temp_thread_state = GetTemporaryResumeState();
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
LLDB_LOGF(log,
"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
": returning vote %i (state was suspended or invalid)",
GetID(), eVoteNoOpinion);
return eVoteNoOpinion;
}
if (temp_thread_state == eStateSuspended ||
temp_thread_state == eStateInvalid) {
LLDB_LOGF(log,
"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
": returning vote %i (temporary state was suspended or invalid)",
GetID(), eVoteNoOpinion);
return eVoteNoOpinion;
}
if (!ThreadStoppedForAReason()) {
LLDB_LOGF(log,
"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
": returning vote %i (thread didn't stop for a reason.)",
GetID(), eVoteNoOpinion);
return eVoteNoOpinion;
}
if (GetPlans().AnyCompletedPlans()) {
// Pass skip_private = false to GetCompletedPlan, since we want to ask
// the last plan, regardless of whether it is private or not.
LLDB_LOGF(log,
"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
": returning vote for complete stack's back plan",
GetID());
return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr);
} else {
Vote thread_vote = eVoteNoOpinion;
ThreadPlan *plan_ptr = GetCurrentPlan();
while (true) {
if (plan_ptr->PlanExplainsStop(event_ptr)) {
thread_vote = plan_ptr->ShouldReportStop(event_ptr);
break;
}
if (plan_ptr->IsBasePlan())
break;
else
plan_ptr = GetPreviousPlan(plan_ptr);
}
LLDB_LOGF(log,
"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
": returning vote %i for current plan",
GetID(), thread_vote);
return thread_vote;
}
}
Vote Thread::ShouldReportRun(Event *event_ptr) {
StateType thread_state = GetResumeState();
if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
return eVoteNoOpinion;
}
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (GetPlans().AnyCompletedPlans()) {
// Pass skip_private = false to GetCompletedPlan, since we want to ask
// the last plan, regardless of whether it is private or not.
LLDB_LOGF(log,
"Current Plan for thread %d(%p) (0x%4.4" PRIx64
", %s): %s being asked whether we should report run.",
GetIndexID(), static_cast<void *>(this), GetID(),
StateAsCString(GetTemporaryResumeState()),
GetCompletedPlan()->GetName());
return GetPlans().GetCompletedPlan(false)->ShouldReportRun(event_ptr);
} else {
LLDB_LOGF(log,
"Current Plan for thread %d(%p) (0x%4.4" PRIx64
", %s): %s being asked whether we should report run.",
GetIndexID(), static_cast<void *>(this), GetID(),
StateAsCString(GetTemporaryResumeState()),
GetCurrentPlan()->GetName());
return GetCurrentPlan()->ShouldReportRun(event_ptr);
}
}
bool Thread::MatchesSpec(const ThreadSpec *spec) {
return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
}
ThreadPlanStack &Thread::GetPlans() const {
ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID());
if (plans)
return *plans;
// History threads don't have a thread plan, but they do ask get asked to
// describe themselves, which usually involves pulling out the stop reason.
// That in turn will check for a completed plan on the ThreadPlanStack.
// Instead of special-casing at that point, we return a Stack with a
// ThreadPlanNull as its base plan. That will give the right answers to the
// queries GetDescription makes, and only assert if you try to run the thread.
if (!m_null_plan_stack_up)
m_null_plan_stack_up.reset(new ThreadPlanStack(*this, true));
return *(m_null_plan_stack_up.get());
}
void Thread::PushPlan(ThreadPlanSP thread_plan_sp) {
assert(thread_plan_sp && "Don't push an empty thread plan.");
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log) {
StreamString s;
thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
static_cast<void *>(this), s.GetData(),
thread_plan_sp->GetThread().GetID());
}
GetPlans().PushPlan(std::move(thread_plan_sp));
}
Figure out the reply to "PlanExplainsStop" once when we stop and then use the cached value. This fixes problems, for instance, with the StepRange plans, where they know that they explained the stop because they were at their "run to here" breakpoint, then deleted that breakpoint, so when they got asked again, doh! I had done this for a couple of plans in an ad hoc fashion, this just formalizes it. Also add a "ResumeRequested" in Process so that the code in the completion handlers can tell the ShouldStop logic they want to resume rather than just directly resuming. That allows us to handle resuming in a more controlled fashion. Also, SetPublicState can take a "restarted" flag, so that it doesn't drop the run lock when the target was immediately restarted. --This line, and those below , will be ignored-- M test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py M include/lldb/Target/ThreadList.h M include/lldb/Target/ThreadPlanStepOut.h M include/lldb/Target/Thread.h M include/lldb/Target/ThreadPlanBase.h M include/lldb/Target/ThreadPlanStepThrough.h M include/lldb/Target/ThreadPlanStepInstruction.h M include/lldb/Target/ThreadPlanStepInRange.h M include/lldb/Target/ThreadPlanStepOverBreakpoint.h M include/lldb/Target/ThreadPlanStepUntil.h M include/lldb/Target/StopInfo.h M include/lldb/Target/Process.h M include/lldb/Target/ThreadPlanRunToAddress.h M include/lldb/Target/ThreadPlan.h M include/lldb/Target/ThreadPlanCallFunction.h M include/lldb/Target/ThreadPlanStepOverRange.h M source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.h M source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp M source/Target/StopInfo.cpp M source/Target/Process.cpp M source/Target/ThreadPlanRunToAddress.cpp M source/Target/ThreadPlan.cpp M source/Target/ThreadPlanCallFunction.cpp M source/Target/ThreadPlanStepOverRange.cpp M source/Target/ThreadList.cpp M source/Target/ThreadPlanStepOut.cpp M source/Target/Thread.cpp M source/Target/ThreadPlanBase.cpp M source/Target/ThreadPlanStepThrough.cpp M source/Target/ThreadPlanStepInstruction.cpp M source/Target/ThreadPlanStepInRange.cpp M source/Target/ThreadPlanStepOverBreakpoint.cpp M source/Target/ThreadPlanStepUntil.cpp M lldb.xcodeproj/xcshareddata/xcschemes/Run Testsuite.xcscheme llvm-svn: 181381
2013-05-08 08:35:16 +08:00
void Thread::PopPlan() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
ThreadPlanSP popped_plan_sp = GetPlans().PopPlan();
if (log) {
LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID());
}
Figure out the reply to "PlanExplainsStop" once when we stop and then use the cached value. This fixes problems, for instance, with the StepRange plans, where they know that they explained the stop because they were at their "run to here" breakpoint, then deleted that breakpoint, so when they got asked again, doh! I had done this for a couple of plans in an ad hoc fashion, this just formalizes it. Also add a "ResumeRequested" in Process so that the code in the completion handlers can tell the ShouldStop logic they want to resume rather than just directly resuming. That allows us to handle resuming in a more controlled fashion. Also, SetPublicState can take a "restarted" flag, so that it doesn't drop the run lock when the target was immediately restarted. --This line, and those below , will be ignored-- M test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py M include/lldb/Target/ThreadList.h M include/lldb/Target/ThreadPlanStepOut.h M include/lldb/Target/Thread.h M include/lldb/Target/ThreadPlanBase.h M include/lldb/Target/ThreadPlanStepThrough.h M include/lldb/Target/ThreadPlanStepInstruction.h M include/lldb/Target/ThreadPlanStepInRange.h M include/lldb/Target/ThreadPlanStepOverBreakpoint.h M include/lldb/Target/ThreadPlanStepUntil.h M include/lldb/Target/StopInfo.h M include/lldb/Target/Process.h M include/lldb/Target/ThreadPlanRunToAddress.h M include/lldb/Target/ThreadPlan.h M include/lldb/Target/ThreadPlanCallFunction.h M include/lldb/Target/ThreadPlanStepOverRange.h M source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.h M source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleThreadPlanStepThroughObjCTrampoline.cpp M source/Target/StopInfo.cpp M source/Target/Process.cpp M source/Target/ThreadPlanRunToAddress.cpp M source/Target/ThreadPlan.cpp M source/Target/ThreadPlanCallFunction.cpp M source/Target/ThreadPlanStepOverRange.cpp M source/Target/ThreadList.cpp M source/Target/ThreadPlanStepOut.cpp M source/Target/Thread.cpp M source/Target/ThreadPlanBase.cpp M source/Target/ThreadPlanStepThrough.cpp M source/Target/ThreadPlanStepInstruction.cpp M source/Target/ThreadPlanStepInRange.cpp M source/Target/ThreadPlanStepOverBreakpoint.cpp M source/Target/ThreadPlanStepUntil.cpp M lldb.xcodeproj/xcshareddata/xcschemes/Run Testsuite.xcscheme llvm-svn: 181381
2013-05-08 08:35:16 +08:00
}
void Thread::DiscardPlan() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
ThreadPlanSP discarded_plan_sp = GetPlans().PopPlan();
LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
discarded_plan_sp->GetName(),
discarded_plan_sp->GetThread().GetID());
}
ThreadPlan *Thread::GetCurrentPlan() const {
return GetPlans().GetCurrentPlan().get();
}
ThreadPlanSP Thread::GetCompletedPlan() const {
return GetPlans().GetCompletedPlan();
}
ValueObjectSP Thread::GetReturnValueObject() const {
return GetPlans().GetReturnValueObject();
}
ExpressionVariableSP Thread::GetExpressionVariable() const {
return GetPlans().GetExpressionVariable();
}
bool Thread::IsThreadPlanDone(ThreadPlan *plan) const {
return GetPlans().IsPlanDone(plan);
}
bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) const {
return GetPlans().WasPlanDiscarded(plan);
}
bool Thread::CompletedPlanOverridesBreakpoint() const {
return GetPlans().AnyCompletedPlans();
}
ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) const{
return GetPlans().GetPreviousPlan(current_plan);
}
Status Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp,
bool abort_other_plans) {
Status status;
StreamString s;
if (!thread_plan_sp->ValidatePlan(&s)) {
DiscardThreadPlansUpToPlan(thread_plan_sp);
thread_plan_sp.reset();
status.SetErrorString(s.GetString());
return status;
}
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
if (abort_other_plans)
DiscardThreadPlans(true);
PushPlan(thread_plan_sp);
// This seems a little funny, but I don't want to have to split up the
// constructor and the DidPush in the scripted plan, that seems annoying.
// That means the constructor has to be in DidPush. So I have to validate the
// plan AFTER pushing it, and then take it off again...
if (!thread_plan_sp->ValidatePlan(&s)) {
DiscardThreadPlansUpToPlan(thread_plan_sp);
thread_plan_sp.reset();
status.SetErrorString(s.GetString());
return status;
}
return status;
}
void Thread::EnableTracer(bool value, bool single_stepping) {
GetPlans().EnableTracer(value, single_stepping);
}
void Thread::SetTracer(lldb::ThreadPlanTracerSP &tracer_sp) {
GetPlans().SetTracer(tracer_sp);
}
bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t plan_index) {
// Count the user thread plans from the back end to get the number of the one
// we want to discard:
ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get();
if (up_to_plan_ptr == nullptr)
return false;
DiscardThreadPlansUpToPlan(up_to_plan_ptr);
return true;
}
void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) {
DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
}
void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
LLDB_LOGF(log,
"Discarding thread plans for thread tid = 0x%4.4" PRIx64
", up to %p",
GetID(), static_cast<void *>(up_to_plan_ptr));
GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr);
}
void Thread::DiscardThreadPlans(bool force) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log) {
LLDB_LOGF(log,
"Discarding thread plans for thread (tid = 0x%4.4" PRIx64
", force %d)",
GetID(), force);
}
if (force) {
GetPlans().DiscardAllPlans();
return;
}
GetPlans().DiscardConsultingMasterPlans();
}
Status Thread::UnwindInnermostExpression() {
Status error;
ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression();
if (!innermost_expr_plan) {
error.SetErrorString("No expressions currently active on this thread");
return error;
}
DiscardThreadPlansUpToPlan(innermost_expr_plan);
return error;
}
ThreadPlanSP Thread::QueueFundamentalPlan(bool abort_other_plans) {
ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction(
bool step_over, bool abort_other_plans, bool stop_other_threads,
Status &status) {
ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
bool abort_other_plans, const AddressRange &range,
const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
ThreadPlanSP thread_plan_sp;
thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(
*this, range, addr_context, stop_other_threads,
step_out_avoids_code_withoug_debug_info);
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
// Call the QueueThreadPlanForStepOverRange method which takes an address
// range.
ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
bool abort_other_plans, const LineEntry &line_entry,
const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
Include inlined functions when figuring out a contiguous address range Checking this in for Antonio Afonso: This diff changes the function LineEntry::GetSameLineContiguousAddressRange so that it also includes function calls that were inlined at the same line of code. My motivation is to decrease the step over time of lines that heavly rely on inlined functions. I have multiple examples in the code base I work that makes a step over stop 20 or mote times internally. This can easly had up to step overs that take >500ms which I was able to lower to 25ms with this new strategy. The reason the current code is not extending the address range beyond an inlined function is because when we resolve the symbol at the next address of the line entry we will get the entry line corresponding to where the original code for the inline function lives, making us barely extend the range. This then will end up on a step over having to stop multiple times everytime there's an inlined function. To check if the range is an inlined function at that line I also get the block associated with the next address and check if there is a parent block with a call site at the line we're trying to extend. To check this I created a new function in Block called GetContainingInlinedBlockWithCallSite that does exactly that. I also added a new function to Declaration for convinence of checking file/line named CompareFileAndLine. To avoid potential issues when extending an address range I added an Extend function that extends the range by the AddressRange given as an argument. This function returns true to indicate sucess when the rage was agumented, false otherwise (e.g.: the ranges are not connected). The reason I do is to make sure that we're not just blindly extending complete_line_range by whatever GetByteSize() we got. If for some reason the ranges are not connected or overlap, or even 0, this could be an issue. I also added a unit tests for this change and include the instructions on the test itself on how to generate the yaml file I use for testing. Differential Revision: https://reviews.llvm.org/D61292 llvm-svn: 360071
2019-05-07 04:01:21 +08:00
const bool include_inlined_functions = true;
auto address_range =
line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);
return QueueThreadPlanForStepOverRange(
Include inlined functions when figuring out a contiguous address range Checking this in for Antonio Afonso: This diff changes the function LineEntry::GetSameLineContiguousAddressRange so that it also includes function calls that were inlined at the same line of code. My motivation is to decrease the step over time of lines that heavly rely on inlined functions. I have multiple examples in the code base I work that makes a step over stop 20 or mote times internally. This can easly had up to step overs that take >500ms which I was able to lower to 25ms with this new strategy. The reason the current code is not extending the address range beyond an inlined function is because when we resolve the symbol at the next address of the line entry we will get the entry line corresponding to where the original code for the inline function lives, making us barely extend the range. This then will end up on a step over having to stop multiple times everytime there's an inlined function. To check if the range is an inlined function at that line I also get the block associated with the next address and check if there is a parent block with a call site at the line we're trying to extend. To check this I created a new function in Block called GetContainingInlinedBlockWithCallSite that does exactly that. I also added a new function to Declaration for convinence of checking file/line named CompareFileAndLine. To avoid potential issues when extending an address range I added an Extend function that extends the range by the AddressRange given as an argument. This function returns true to indicate sucess when the rage was agumented, false otherwise (e.g.: the ranges are not connected). The reason I do is to make sure that we're not just blindly extending complete_line_range by whatever GetByteSize() we got. If for some reason the ranges are not connected or overlap, or even 0, this could be an issue. I also added a unit tests for this change and include the instructions on the test itself on how to generate the yaml file I use for testing. Differential Revision: https://reviews.llvm.org/D61292 llvm-svn: 360071
2019-05-07 04:01:21 +08:00
abort_other_plans, address_range, addr_context, stop_other_threads,
status, step_out_avoids_code_withoug_debug_info);
}
ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
bool abort_other_plans, const AddressRange &range,
const SymbolContext &addr_context, const char *step_in_target,
lldb::RunMode stop_other_threads, Status &status,
LazyBool step_in_avoids_code_without_debug_info,
LazyBool step_out_avoids_code_without_debug_info) {
ThreadPlanSP thread_plan_sp(
new ThreadPlanStepInRange(*this, range, addr_context, stop_other_threads,
step_in_avoids_code_without_debug_info,
step_out_avoids_code_without_debug_info));
ThreadPlanStepInRange *plan =
static_cast<ThreadPlanStepInRange *>(thread_plan_sp.get());
if (step_in_target)
plan->SetStepInTarget(step_in_target);
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
// Call the QueueThreadPlanForStepInRange method which takes an address range.
ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
bool abort_other_plans, const LineEntry &line_entry,
const SymbolContext &addr_context, const char *step_in_target,
lldb::RunMode stop_other_threads, Status &status,
LazyBool step_in_avoids_code_without_debug_info,
LazyBool step_out_avoids_code_without_debug_info) {
Include inlined functions when figuring out a contiguous address range Checking this in for Antonio Afonso: This diff changes the function LineEntry::GetSameLineContiguousAddressRange so that it also includes function calls that were inlined at the same line of code. My motivation is to decrease the step over time of lines that heavly rely on inlined functions. I have multiple examples in the code base I work that makes a step over stop 20 or mote times internally. This can easly had up to step overs that take >500ms which I was able to lower to 25ms with this new strategy. The reason the current code is not extending the address range beyond an inlined function is because when we resolve the symbol at the next address of the line entry we will get the entry line corresponding to where the original code for the inline function lives, making us barely extend the range. This then will end up on a step over having to stop multiple times everytime there's an inlined function. To check if the range is an inlined function at that line I also get the block associated with the next address and check if there is a parent block with a call site at the line we're trying to extend. To check this I created a new function in Block called GetContainingInlinedBlockWithCallSite that does exactly that. I also added a new function to Declaration for convinence of checking file/line named CompareFileAndLine. To avoid potential issues when extending an address range I added an Extend function that extends the range by the AddressRange given as an argument. This function returns true to indicate sucess when the rage was agumented, false otherwise (e.g.: the ranges are not connected). The reason I do is to make sure that we're not just blindly extending complete_line_range by whatever GetByteSize() we got. If for some reason the ranges are not connected or overlap, or even 0, this could be an issue. I also added a unit tests for this change and include the instructions on the test itself on how to generate the yaml file I use for testing. Differential Revision: https://reviews.llvm.org/D61292 llvm-svn: 360071
2019-05-07 04:01:21 +08:00
const bool include_inlined_functions = false;
return QueueThreadPlanForStepInRange(
Include inlined functions when figuring out a contiguous address range Checking this in for Antonio Afonso: This diff changes the function LineEntry::GetSameLineContiguousAddressRange so that it also includes function calls that were inlined at the same line of code. My motivation is to decrease the step over time of lines that heavly rely on inlined functions. I have multiple examples in the code base I work that makes a step over stop 20 or mote times internally. This can easly had up to step overs that take >500ms which I was able to lower to 25ms with this new strategy. The reason the current code is not extending the address range beyond an inlined function is because when we resolve the symbol at the next address of the line entry we will get the entry line corresponding to where the original code for the inline function lives, making us barely extend the range. This then will end up on a step over having to stop multiple times everytime there's an inlined function. To check if the range is an inlined function at that line I also get the block associated with the next address and check if there is a parent block with a call site at the line we're trying to extend. To check this I created a new function in Block called GetContainingInlinedBlockWithCallSite that does exactly that. I also added a new function to Declaration for convinence of checking file/line named CompareFileAndLine. To avoid potential issues when extending an address range I added an Extend function that extends the range by the AddressRange given as an argument. This function returns true to indicate sucess when the rage was agumented, false otherwise (e.g.: the ranges are not connected). The reason I do is to make sure that we're not just blindly extending complete_line_range by whatever GetByteSize() we got. If for some reason the ranges are not connected or overlap, or even 0, this could be an issue. I also added a unit tests for this change and include the instructions on the test itself on how to generate the yaml file I use for testing. Differential Revision: https://reviews.llvm.org/D61292 llvm-svn: 360071
2019-05-07 04:01:21 +08:00
abort_other_plans,
line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),
addr_context, step_in_target, stop_other_threads, status,
step_in_avoids_code_without_debug_info,
step_out_avoids_code_without_debug_info);
}
ThreadPlanSP Thread::QueueThreadPlanForStepOut(
bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
Status &status, LazyBool step_out_avoids_code_without_debug_info) {
ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
*this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
frame_idx, step_out_avoids_code_without_debug_info));
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop(
bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
Status &status, bool continue_to_next_branch) {
const bool calculate_return_value =
false; // No need to calculate the return value here.
ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
*this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
frame_idx, eLazyBoolNo, continue_to_next_branch, calculate_return_value));
ThreadPlanStepOut *new_plan =
static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
new_plan->ClearShouldStopHereCallbacks();
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id,
bool abort_other_plans,
bool stop_other_threads,
Status &status) {
ThreadPlanSP thread_plan_sp(
new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
return ThreadPlanSP();
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans,
Address &target_addr,
bool stop_other_threads,
Status &status) {
ThreadPlanSP thread_plan_sp(
new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
ThreadPlanSP Thread::QueueThreadPlanForStepUntil(
bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses,
bool stop_other_threads, uint32_t frame_idx, Status &status) {
ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil(
*this, address_list, num_addresses, stop_other_threads, frame_idx));
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted(
bool abort_other_plans, const char *class_name,
StructuredData::ObjectSP extra_args_sp, bool stop_other_threads,
Status &status) {
StructuredDataImpl *extra_args_impl = nullptr;
if (extra_args_sp) {
extra_args_impl = new StructuredDataImpl();
extra_args_impl->SetObjectSP(extra_args_sp);
}
ThreadPlanSP thread_plan_sp(new ThreadPlanPython(*this, class_name,
extra_args_impl));
status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
return thread_plan_sp;
}
uint32_t Thread::GetIndexID() const { return m_index_id; }
TargetSP Thread::CalculateTarget() {
TargetSP target_sp;
ProcessSP process_sp(GetProcess());
if (process_sp)
target_sp = process_sp->CalculateTarget();
return target_sp;
}
ProcessSP Thread::CalculateProcess() { return GetProcess(); }
ThreadSP Thread::CalculateThread() { return shared_from_this(); }
StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); }
There are now to new "settings set" variables that live in each debugger instance: settings set frame-format <string> settings set thread-format <string> This allows users to control the information that is seen when dumping threads and frames. The default values are set such that they do what they used to do prior to changing over the the user defined formats. This allows users with terminals that can display color to make different items different colors using the escape control codes. A few alias examples that will colorize your thread and frame prompts are: settings set frame-format 'frame #${frame.index}: \033[0;33m${frame.pc}\033[0m{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{ \033[0;35mat \033[1;35m${line.file.basename}:${line.number}}\033[0m\n' settings set thread-format 'thread #${thread.index}: \033[1;33mtid\033[0;33m = ${thread.id}\033[0m{, \033[0;33m${frame.pc}\033[0m}{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{, \033[1;35mstop reason\033[0;35m = ${thread.stop-reason}\033[0m}{, \033[1;36mname = \033[0;36m${thread.name}\033[0m}{, \033[1;32mqueue = \033[0;32m${thread.queue}}\033[0m\n' A quick web search for "colorize terminal output" should allow you to see what you can do to make your output look like you want it. The "settings set" commands above can of course be added to your ~/.lldbinit file for permanent use. Changed the pure virtual void ExecutionContextScope::Calculate (ExecutionContext&); To: void ExecutionContextScope::CalculateExecutionContext (ExecutionContext&); I did this because this is a class that anything in the execution context heirarchy inherits from and "target->Calculate (exe_ctx)" didn't always tell you what it was really trying to do unless you look at the parameter. llvm-svn: 115485
2010-10-04 09:05:56 +08:00
void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) {
exe_ctx.SetContext(shared_from_this());
}
StackFrameListSP Thread::GetStackFrameList() {
std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
if (!m_curr_frames_sp)
m_curr_frames_sp =
std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true);
return m_curr_frames_sp;
}
void Thread::ClearStackFrames() {
std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
GetUnwinder().Clear();
// Only store away the old "reference" StackFrameList if we got all its
// frames:
// FIXME: At some point we can try to splice in the frames we have fetched
// into
// the new frame as we make it, but let's not try that now.
if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
m_prev_frames_sp.swap(m_curr_frames_sp);
m_curr_frames_sp.reset();
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
m_extended_info.reset();
m_extended_info_fetched = false;
}
Fixed issues with RegisterContext classes and the subclasses. There was an issue with the way the UnwindLLDB was handing out RegisterContexts: it was making shared pointers to register contexts and then handing out just the pointers (which would get put into shared pointers in the thread and stack frame classes) and cause double free issues. MallocScribble helped to find these issues after I did some other cleanup. To help avoid any RegisterContext issue in the future, all code that deals with them now returns shared pointers to the register contexts so we don't end up with multiple deletions. Also now that the RegisterContext class doesn't require a stack frame, we patched a memory leak where a StackFrame object was being created and leaked. Made the RegisterContext class not have a pointer to a StackFrame object as one register context class can be used for N inlined stack frames so there is not a 1 - 1 mapping. Updates the ExecutionContextScope part of the RegisterContext class to never return a stack frame to indicate this when it is asked to recreate the execution context. Now register contexts point to the concrete frame using a concrete frame index. Concrete frames are all of the frames that are actually formed on the stack of a thread. These concrete frames can be turned into one or more user visible frames due to inlining. Each inlined stack frame has the exact same register context (shared via shared pointers) as any parent inlined stack frames all the way up to the concrete frame itself. So now the stack frames and the register contexts should behave much better. llvm-svn: 122976
2011-01-07 06:15:06 +08:00
lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
Fixed issues with RegisterContext classes and the subclasses. There was an issue with the way the UnwindLLDB was handing out RegisterContexts: it was making shared pointers to register contexts and then handing out just the pointers (which would get put into shared pointers in the thread and stack frame classes) and cause double free issues. MallocScribble helped to find these issues after I did some other cleanup. To help avoid any RegisterContext issue in the future, all code that deals with them now returns shared pointers to the register contexts so we don't end up with multiple deletions. Also now that the RegisterContext class doesn't require a stack frame, we patched a memory leak where a StackFrame object was being created and leaked. Made the RegisterContext class not have a pointer to a StackFrame object as one register context class can be used for N inlined stack frames so there is not a 1 - 1 mapping. Updates the ExecutionContextScope part of the RegisterContext class to never return a stack frame to indicate this when it is asked to recreate the execution context. Now register contexts point to the concrete frame using a concrete frame index. Concrete frames are all of the frames that are actually formed on the stack of a thread. These concrete frames can be turned into one or more user visible frames due to inlining. Each inlined stack frame has the exact same register context (shared via shared pointers) as any parent inlined stack frames all the way up to the concrete frame itself. So now the stack frames and the register contexts should behave much better. llvm-svn: 122976
2011-01-07 06:15:06 +08:00
}
Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx,
lldb::ValueObjectSP return_value_sp,
bool broadcast) {
StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
Status return_error;
if (!frame_sp) {
return_error.SetErrorStringWithFormat(
"Could not find frame with index %d in thread 0x%" PRIx64 ".",
frame_idx, GetID());
}
return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
}
Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp,
lldb::ValueObjectSP return_value_sp,
bool broadcast) {
Status return_error;
if (!frame_sp) {
return_error.SetErrorString("Can't return to a null frame.");
return return_error;
}
There are now to new "settings set" variables that live in each debugger instance: settings set frame-format <string> settings set thread-format <string> This allows users to control the information that is seen when dumping threads and frames. The default values are set such that they do what they used to do prior to changing over the the user defined formats. This allows users with terminals that can display color to make different items different colors using the escape control codes. A few alias examples that will colorize your thread and frame prompts are: settings set frame-format 'frame #${frame.index}: \033[0;33m${frame.pc}\033[0m{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{ \033[0;35mat \033[1;35m${line.file.basename}:${line.number}}\033[0m\n' settings set thread-format 'thread #${thread.index}: \033[1;33mtid\033[0;33m = ${thread.id}\033[0m{, \033[0;33m${frame.pc}\033[0m}{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{, \033[1;35mstop reason\033[0;35m = ${thread.stop-reason}\033[0m}{, \033[1;36mname = \033[0;36m${thread.name}\033[0m}{, \033[1;32mqueue = \033[0;32m${thread.queue}}\033[0m\n' A quick web search for "colorize terminal output" should allow you to see what you can do to make your output look like you want it. The "settings set" commands above can of course be added to your ~/.lldbinit file for permanent use. Changed the pure virtual void ExecutionContextScope::Calculate (ExecutionContext&); To: void ExecutionContextScope::CalculateExecutionContext (ExecutionContext&); I did this because this is a class that anything in the execution context heirarchy inherits from and "target->Calculate (exe_ctx)" didn't always tell you what it was really trying to do unless you look at the parameter. llvm-svn: 115485
2010-10-04 09:05:56 +08:00
Thread *thread = frame_sp->GetThread().get();
uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
if (!older_frame_sp) {
return_error.SetErrorString("No older frame to return to.");
return return_error;
}
if (return_value_sp) {
lldb::ABISP abi = thread->GetProcess()->GetABI();
if (!abi) {
return_error.SetErrorString("Could not find ABI to set return value.");
return return_error;
}
SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
// FIXME: ValueObject::Cast doesn't currently work correctly, at least not
// for scalars.
// Turn that back on when that works.
if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
Type *function_type = sc.function->GetType();
if (function_type) {
Final bit of type system cleanup that abstracts declaration contexts into lldb_private::CompilerDeclContext and renames ClangType to CompilerType in many accessors and functions. Create a new "lldb_private::CompilerDeclContext" class that will replace all direct uses of "clang::DeclContext" when used in compiler agnostic code, yet still allow for conversion to clang::DeclContext subclasses by clang specific code. This completes the abstraction of type parsing by removing all "clang::" references from the SymbolFileDWARF. The new "lldb_private::CompilerDeclContext" class abstracts decl contexts found in compiler type systems so they can be used in internal API calls. The TypeSystem is required to support CompilerDeclContexts with new pure virtual functions that start with "DeclContext" in the member function names. Converted all code that used lldb_private::ClangNamespaceDecl over to use the new CompilerDeclContext class and removed the ClangNamespaceDecl.cpp and ClangNamespaceDecl.h files. Removed direct use of clang APIs from SBType and now use the abstract type systems to correctly explore types. Bulk renames for things that used to return a ClangASTType which is now CompilerType: "Type::GetClangFullType()" to "Type::GetFullCompilerType()" "Type::GetClangLayoutType()" to "Type::GetLayoutCompilerType()" "Type::GetClangForwardType()" to "Type::GetForwardCompilerType()" "Value::GetClangType()" to "Value::GetCompilerType()" "Value::SetClangType (const CompilerType &)" to "Value::SetCompilerType (const CompilerType &)" "ValueObject::GetClangType ()" to "ValueObject::GetCompilerType()" many more renames that are similar. llvm-svn: 245905
2015-08-25 07:46:31 +08:00
CompilerType return_type =
sc.function->GetCompilerType().GetFunctionReturnType();
if (return_type) {
StreamString s;
return_type.DumpTypeDescription(&s);
ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
if (cast_value_sp) {
cast_value_sp->SetFormat(eFormatHex);
return_value_sp = cast_value_sp;
}
}
}
}
return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
if (!return_error.Success())
return return_error;
}
// Now write the return registers for the chosen frame: Note, we can't use
// ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
// their data
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
if (youngest_frame_sp) {
lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
if (reg_ctx_sp) {
bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
older_frame_sp->GetRegisterContext());
if (copy_success) {
thread->DiscardThreadPlans(true);
thread->ClearStackFrames();
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
BroadcastEvent(eBroadcastBitStackChanged,
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
new ThreadEventData(this->shared_from_this()));
} else {
return_error.SetErrorString("Could not reset register values.");
}
} else {
return_error.SetErrorString("Frame has no register context.");
}
} else {
return_error.SetErrorString("Returned past top frame.");
}
return return_error;
}
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
static void DumpAddressList(Stream &s, const std::vector<Address> &list,
ExecutionContextScope *exe_scope) {
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
for (size_t n = 0; n < list.size(); n++) {
s << "\t";
list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
Address::DumpStyleSectionNameOffset);
s << "\n";
}
}
Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
bool can_leave_function, std::string *warnings) {
ExecutionContext exe_ctx(GetStackFrameAtIndex(0));
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
Target *target = exe_ctx.GetTargetPtr();
TargetSP target_sp = exe_ctx.GetTargetSP();
RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
StackFrame *frame = exe_ctx.GetFramePtr();
const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
// Find candidate locations.
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
std::vector<Address> candidates, within_function, outside_function;
target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
within_function, outside_function);
// If possible, we try and stay within the current function. Within a
// function, we accept multiple locations (optimized code may do this,
// there's no solution here so we do the best we can). However if we're
// trying to leave the function, we don't know how to pick the right
// location, so if there's more than one then we bail.
if (!within_function.empty())
candidates = within_function;
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
else if (outside_function.size() == 1 && can_leave_function)
candidates = outside_function;
// Check if we got anything.
if (candidates.empty()) {
if (outside_function.empty()) {
return Status("Cannot locate an address for %s:%i.",
file.GetFilename().AsCString(), line);
} else if (outside_function.size() == 1) {
return Status("%s:%i is outside the current function.",
file.GetFilename().AsCString(), line);
} else {
StreamString sstr;
DumpAddressList(sstr, outside_function, target);
return Status("%s:%i has multiple candidate locations:\n%s",
file.GetFilename().AsCString(), line, sstr.GetData());
}
}
// Accept the first location, warn about any others.
Address dest = candidates[0];
if (warnings && candidates.size() > 1) {
StreamString sstr;
sstr.Printf("%s:%i appears multiple times in this function, selecting the "
"first location:\n",
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
file.GetFilename().AsCString(), line);
DumpAddressList(sstr, candidates, target);
*warnings = std::string(sstr.GetString());
}
if (!reg_ctx->SetPC(dest))
return Status("Cannot change PC to target address.");
return Status();
}
void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
bool stop_format) {
ExecutionContext exe_ctx(shared_from_this());
Process *process = exe_ctx.GetProcessPtr();
if (process == nullptr)
return;
StackFrameSP frame_sp;
There are now to new "settings set" variables that live in each debugger instance: settings set frame-format <string> settings set thread-format <string> This allows users to control the information that is seen when dumping threads and frames. The default values are set such that they do what they used to do prior to changing over the the user defined formats. This allows users with terminals that can display color to make different items different colors using the escape control codes. A few alias examples that will colorize your thread and frame prompts are: settings set frame-format 'frame #${frame.index}: \033[0;33m${frame.pc}\033[0m{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{ \033[0;35mat \033[1;35m${line.file.basename}:${line.number}}\033[0m\n' settings set thread-format 'thread #${thread.index}: \033[1;33mtid\033[0;33m = ${thread.id}\033[0m{, \033[0;33m${frame.pc}\033[0m}{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{, \033[1;35mstop reason\033[0;35m = ${thread.stop-reason}\033[0m}{, \033[1;36mname = \033[0;36m${thread.name}\033[0m}{, \033[1;32mqueue = \033[0;32m${thread.queue}}\033[0m\n' A quick web search for "colorize terminal output" should allow you to see what you can do to make your output look like you want it. The "settings set" commands above can of course be added to your ~/.lldbinit file for permanent use. Changed the pure virtual void ExecutionContextScope::Calculate (ExecutionContext&); To: void ExecutionContextScope::CalculateExecutionContext (ExecutionContext&); I did this because this is a class that anything in the execution context heirarchy inherits from and "target->Calculate (exe_ctx)" didn't always tell you what it was really trying to do unless you look at the parameter. llvm-svn: 115485
2010-10-04 09:05:56 +08:00
SymbolContext frame_sc;
if (frame_idx != LLDB_INVALID_FRAME_ID) {
frame_sp = GetStackFrameAtIndex(frame_idx);
if (frame_sp) {
exe_ctx.SetFrameSP(frame_sp);
frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
}
}
const FormatEntity::Entry *thread_format;
if (stop_format)
thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
else
thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
There are now to new "settings set" variables that live in each debugger instance: settings set frame-format <string> settings set thread-format <string> This allows users to control the information that is seen when dumping threads and frames. The default values are set such that they do what they used to do prior to changing over the the user defined formats. This allows users with terminals that can display color to make different items different colors using the escape control codes. A few alias examples that will colorize your thread and frame prompts are: settings set frame-format 'frame #${frame.index}: \033[0;33m${frame.pc}\033[0m{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{ \033[0;35mat \033[1;35m${line.file.basename}:${line.number}}\033[0m\n' settings set thread-format 'thread #${thread.index}: \033[1;33mtid\033[0;33m = ${thread.id}\033[0m{, \033[0;33m${frame.pc}\033[0m}{ \033[1;4;36m${module.file.basename}\033[0;36m ${function.name}{${function.pc-offset}}\033[0m}{, \033[1;35mstop reason\033[0;35m = ${thread.stop-reason}\033[0m}{, \033[1;36mname = \033[0;36m${thread.name}\033[0m}{, \033[1;32mqueue = \033[0;32m${thread.queue}}\033[0m\n' A quick web search for "colorize terminal output" should allow you to see what you can do to make your output look like you want it. The "settings set" commands above can of course be added to your ~/.lldbinit file for permanent use. Changed the pure virtual void ExecutionContextScope::Calculate (ExecutionContext&); To: void ExecutionContextScope::CalculateExecutionContext (ExecutionContext&); I did this because this is a class that anything in the execution context heirarchy inherits from and "target->Calculate (exe_ctx)" didn't always tell you what it was really trying to do unless you look at the parameter. llvm-svn: 115485
2010-10-04 09:05:56 +08:00
assert(thread_format);
Get rid of Debugger::FormatPrompt() and replace it with the new FormatEntity class. Why? Debugger::FormatPrompt() would run through the format prompt every time and parse it and emit it piece by piece. It also did formatting differently depending on which key/value pair it was parsing. The new code improves on this with the following features: 1 - Allow format strings to be parsed into a FormatEntity::Entry which can contain multiple child FormatEntity::Entry objects. This FormatEntity::Entry is a parsed version of what was previously always done in Debugger::FormatPrompt() so it is more efficient to emit formatted strings using the new parsed FormatEntity::Entry. 2 - Allows errors in format strings to be shown immediately when setting the settings (frame-format, thread-format, disassembly-format 3 - Allows auto completion by implementing a new OptionValueFormatEntity and switching frame-format, thread-format, and disassembly-format settings over to using it. 4 - The FormatEntity::Entry for each of the frame-format, thread-format, disassembly-format settings only replaces the old one if the format parses correctly 5 - Combines all consecutive string values together for efficient output. This means all "${ansi.*}" keys and all desensitized characters like "\n" "\t" "\0721" "\x23" will get combined with their previous strings 6 - ${*.script:} (like "${var.script:mymodule.my_var_function}") have all been switched over to use ${script.*:} "${script.var:mymodule.my_var_function}") to make the format easier to parse as I don't believe anyone was using these format string power user features. 7 - All key values pairs are defined in simple C arrays of entries so it is much easier to add new entries. These changes pave the way for subsequent modifications where we can modify formats to do more (like control the width of value strings can do more and add more functionality more easily like string formatting to control the width, printf formats and more). llvm-svn: 228207
2015-02-05 06:00:53 +08:00
FormatEntity::Format(*thread_format, strm, frame_sp ? &frame_sc : nullptr,
&exe_ctx, nullptr, nullptr, false, false);
}
void Thread::SettingsInitialize() {}
void Thread::SettingsTerminate() {}
Added support for reading thread-local storage variables, as defined using the __thread modifier. To make this work this patch extends LLDB to: - Explicitly track the link_map address for each module. This is effectively the module handle, not sure why it wasn't already being stored off anywhere. As an extension later, it would be nice if someone were to add support for printing this as part of the modules list. - Allow reading the per-thread data pointer via ptrace. I have added support for Linux here. I'll be happy to add support for FreeBSD once this is reviewed. OS X does not appear to have __thread variables, so maybe we don't need it there. Windows support should eventually be workable along the same lines. - Make DWARF expressions track which module they originated from. - Add support for the DW_OP_GNU_push_tls_address DWARF opcode, as generated by gcc and recent versions of clang. Earlier versions of clang (such as 3.2, which is default on Ubuntu right now) do not generate TLS debug info correctly so can not be supported here. - Understand the format of the pthread DTV block. This is where it gets tricky. We have three basic options here: 1) Call "dlinfo" or "__tls_get_addr" on the inferior and ask it directly. However this won't work on core dumps, and generally speaking it's not a good idea for the debugger to call functions itself, as it has the potential to not work depending on the state of the target. 2) Use libthread_db. This is what GDB does. However this option requires having a version of libthread_db on the host cross-compiled for each potential target. This places a large burden on the user, and would make it very hard to cross-debug from Windows to Linux, for example. Trying to build a library intended exclusively for one OS on a different one is not pleasant. GDB sidesteps the problem and asks the user to figure it out. 3) Parse the DTV structure ourselves. On initial inspection this seems to be a bad option, as the DTV structure (the format used by the runtime to manage TLS data) is not in fact a kernel data structure, it is implemented entirely in useerland in libc. Therefore the layout of it's fields are version and OS dependent, and are not standardized. However, it turns out not to be such a problem. All OSes use basically the same algorithm (a per-module lookup table) as detailed in Ulrich Drepper's TLS ELF ABI document, so we can easily write code to decode it ourselves. The only question therefore is the exact field layouts required. Happily, the implementors of libpthread expose the structure of the DTV via metadata exported as symbols from the .so itself, designed exactly for this kind of thing. So this patch simply reads that metadata in, and re-implements libthread_db's algorithm itself. We thereby get cross-platform TLS lookup without either requiring third-party libraries, while still being independent of the version of libpthread being used. Test case included. llvm-svn: 192922
2013-10-18 05:14:00 +08:00
lldb::addr_t Thread::GetThreadPointer() { return LLDB_INVALID_ADDRESS; }
Added support for thread local variables on all Apple OS variants. We had support that assumed that thread local data for a variable could be determined solely from the module in which the variable exists. While this work for linux, it doesn't work for Apple OSs. The DWARF for thread local variables consists of location opcodes that do something like: DW_OP_const8u (x) DW_OP_form_tls_address or DW_OP_const8u (x) DW_OP_GNU_push_tls_address The "x" is allowed to be anything that is needed to determine the location of the variable. For Linux "x" is the offset within the TLS data for a given executable (ModuleSP in LLDB). For Apple OS variants, it is the file address of the data structure that contains a pthread key that can be used with pthread_getspecific() and the offset needed. This fix passes the "x" along to the thread: virtual lldb::addr_t lldb_private::Thread::GetThreadLocalData(const lldb::ModuleSP module, lldb::addr_t tls_file_addr); Then this is passed along to the DynamicLoader::GetThreadLocalData(): virtual lldb::addr_t lldb_private::DynamicLoader::GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr); This allows each DynamicLoader plug-in do the right thing for the current OS. The DynamicLoaderMacOSXDYLD was modified to be able to grab the pthread key from the data structure that is in memory and call "void *pthread_getspecific(pthread_key_t key)" to get the value of the thread local storage and it caches it per thread since it never changes. I had to update the test case to access the thread local data before trying to print it as on Apple OS variants, thread locals are not available unless they have been accessed at least one by the current thread. I also added a new lldb::ValueType named "eValueTypeVariableThreadLocal" so that we can ask SBValue objects for their ValueType and be able to tell when we have a thread local variable. <rdar://problem/23308080> llvm-svn: 274366
2016-07-02 01:17:23 +08:00
addr_t Thread::GetThreadLocalData(const ModuleSP module,
Added support for reading thread-local storage variables, as defined using the __thread modifier. To make this work this patch extends LLDB to: - Explicitly track the link_map address for each module. This is effectively the module handle, not sure why it wasn't already being stored off anywhere. As an extension later, it would be nice if someone were to add support for printing this as part of the modules list. - Allow reading the per-thread data pointer via ptrace. I have added support for Linux here. I'll be happy to add support for FreeBSD once this is reviewed. OS X does not appear to have __thread variables, so maybe we don't need it there. Windows support should eventually be workable along the same lines. - Make DWARF expressions track which module they originated from. - Add support for the DW_OP_GNU_push_tls_address DWARF opcode, as generated by gcc and recent versions of clang. Earlier versions of clang (such as 3.2, which is default on Ubuntu right now) do not generate TLS debug info correctly so can not be supported here. - Understand the format of the pthread DTV block. This is where it gets tricky. We have three basic options here: 1) Call "dlinfo" or "__tls_get_addr" on the inferior and ask it directly. However this won't work on core dumps, and generally speaking it's not a good idea for the debugger to call functions itself, as it has the potential to not work depending on the state of the target. 2) Use libthread_db. This is what GDB does. However this option requires having a version of libthread_db on the host cross-compiled for each potential target. This places a large burden on the user, and would make it very hard to cross-debug from Windows to Linux, for example. Trying to build a library intended exclusively for one OS on a different one is not pleasant. GDB sidesteps the problem and asks the user to figure it out. 3) Parse the DTV structure ourselves. On initial inspection this seems to be a bad option, as the DTV structure (the format used by the runtime to manage TLS data) is not in fact a kernel data structure, it is implemented entirely in useerland in libc. Therefore the layout of it's fields are version and OS dependent, and are not standardized. However, it turns out not to be such a problem. All OSes use basically the same algorithm (a per-module lookup table) as detailed in Ulrich Drepper's TLS ELF ABI document, so we can easily write code to decode it ourselves. The only question therefore is the exact field layouts required. Happily, the implementors of libpthread expose the structure of the DTV via metadata exported as symbols from the .so itself, designed exactly for this kind of thing. So this patch simply reads that metadata in, and re-implements libthread_db's algorithm itself. We thereby get cross-platform TLS lookup without either requiring third-party libraries, while still being independent of the version of libpthread being used. Test case included. llvm-svn: 192922
2013-10-18 05:14:00 +08:00
lldb::addr_t tls_file_addr) {
// The default implementation is to ask the dynamic loader for it. This can
// be overridden for specific platforms.
Added support for reading thread-local storage variables, as defined using the __thread modifier. To make this work this patch extends LLDB to: - Explicitly track the link_map address for each module. This is effectively the module handle, not sure why it wasn't already being stored off anywhere. As an extension later, it would be nice if someone were to add support for printing this as part of the modules list. - Allow reading the per-thread data pointer via ptrace. I have added support for Linux here. I'll be happy to add support for FreeBSD once this is reviewed. OS X does not appear to have __thread variables, so maybe we don't need it there. Windows support should eventually be workable along the same lines. - Make DWARF expressions track which module they originated from. - Add support for the DW_OP_GNU_push_tls_address DWARF opcode, as generated by gcc and recent versions of clang. Earlier versions of clang (such as 3.2, which is default on Ubuntu right now) do not generate TLS debug info correctly so can not be supported here. - Understand the format of the pthread DTV block. This is where it gets tricky. We have three basic options here: 1) Call "dlinfo" or "__tls_get_addr" on the inferior and ask it directly. However this won't work on core dumps, and generally speaking it's not a good idea for the debugger to call functions itself, as it has the potential to not work depending on the state of the target. 2) Use libthread_db. This is what GDB does. However this option requires having a version of libthread_db on the host cross-compiled for each potential target. This places a large burden on the user, and would make it very hard to cross-debug from Windows to Linux, for example. Trying to build a library intended exclusively for one OS on a different one is not pleasant. GDB sidesteps the problem and asks the user to figure it out. 3) Parse the DTV structure ourselves. On initial inspection this seems to be a bad option, as the DTV structure (the format used by the runtime to manage TLS data) is not in fact a kernel data structure, it is implemented entirely in useerland in libc. Therefore the layout of it's fields are version and OS dependent, and are not standardized. However, it turns out not to be such a problem. All OSes use basically the same algorithm (a per-module lookup table) as detailed in Ulrich Drepper's TLS ELF ABI document, so we can easily write code to decode it ourselves. The only question therefore is the exact field layouts required. Happily, the implementors of libpthread expose the structure of the DTV via metadata exported as symbols from the .so itself, designed exactly for this kind of thing. So this patch simply reads that metadata in, and re-implements libthread_db's algorithm itself. We thereby get cross-platform TLS lookup without either requiring third-party libraries, while still being independent of the version of libpthread being used. Test case included. llvm-svn: 192922
2013-10-18 05:14:00 +08:00
DynamicLoader *loader = GetProcess()->GetDynamicLoader();
if (loader)
Added support for thread local variables on all Apple OS variants. We had support that assumed that thread local data for a variable could be determined solely from the module in which the variable exists. While this work for linux, it doesn't work for Apple OSs. The DWARF for thread local variables consists of location opcodes that do something like: DW_OP_const8u (x) DW_OP_form_tls_address or DW_OP_const8u (x) DW_OP_GNU_push_tls_address The "x" is allowed to be anything that is needed to determine the location of the variable. For Linux "x" is the offset within the TLS data for a given executable (ModuleSP in LLDB). For Apple OS variants, it is the file address of the data structure that contains a pthread key that can be used with pthread_getspecific() and the offset needed. This fix passes the "x" along to the thread: virtual lldb::addr_t lldb_private::Thread::GetThreadLocalData(const lldb::ModuleSP module, lldb::addr_t tls_file_addr); Then this is passed along to the DynamicLoader::GetThreadLocalData(): virtual lldb::addr_t lldb_private::DynamicLoader::GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr); This allows each DynamicLoader plug-in do the right thing for the current OS. The DynamicLoaderMacOSXDYLD was modified to be able to grab the pthread key from the data structure that is in memory and call "void *pthread_getspecific(pthread_key_t key)" to get the value of the thread local storage and it caches it per thread since it never changes. I had to update the test case to access the thread local data before trying to print it as on Apple OS variants, thread locals are not available unless they have been accessed at least one by the current thread. I also added a new lldb::ValueType named "eValueTypeVariableThreadLocal" so that we can ask SBValue objects for their ValueType and be able to tell when we have a thread local variable. <rdar://problem/23308080> llvm-svn: 274366
2016-07-02 01:17:23 +08:00
return loader->GetThreadLocalData(module, shared_from_this(),
tls_file_addr);
else
Added support for reading thread-local storage variables, as defined using the __thread modifier. To make this work this patch extends LLDB to: - Explicitly track the link_map address for each module. This is effectively the module handle, not sure why it wasn't already being stored off anywhere. As an extension later, it would be nice if someone were to add support for printing this as part of the modules list. - Allow reading the per-thread data pointer via ptrace. I have added support for Linux here. I'll be happy to add support for FreeBSD once this is reviewed. OS X does not appear to have __thread variables, so maybe we don't need it there. Windows support should eventually be workable along the same lines. - Make DWARF expressions track which module they originated from. - Add support for the DW_OP_GNU_push_tls_address DWARF opcode, as generated by gcc and recent versions of clang. Earlier versions of clang (such as 3.2, which is default on Ubuntu right now) do not generate TLS debug info correctly so can not be supported here. - Understand the format of the pthread DTV block. This is where it gets tricky. We have three basic options here: 1) Call "dlinfo" or "__tls_get_addr" on the inferior and ask it directly. However this won't work on core dumps, and generally speaking it's not a good idea for the debugger to call functions itself, as it has the potential to not work depending on the state of the target. 2) Use libthread_db. This is what GDB does. However this option requires having a version of libthread_db on the host cross-compiled for each potential target. This places a large burden on the user, and would make it very hard to cross-debug from Windows to Linux, for example. Trying to build a library intended exclusively for one OS on a different one is not pleasant. GDB sidesteps the problem and asks the user to figure it out. 3) Parse the DTV structure ourselves. On initial inspection this seems to be a bad option, as the DTV structure (the format used by the runtime to manage TLS data) is not in fact a kernel data structure, it is implemented entirely in useerland in libc. Therefore the layout of it's fields are version and OS dependent, and are not standardized. However, it turns out not to be such a problem. All OSes use basically the same algorithm (a per-module lookup table) as detailed in Ulrich Drepper's TLS ELF ABI document, so we can easily write code to decode it ourselves. The only question therefore is the exact field layouts required. Happily, the implementors of libpthread expose the structure of the DTV via metadata exported as symbols from the .so itself, designed exactly for this kind of thing. So this patch simply reads that metadata in, and re-implements libthread_db's algorithm itself. We thereby get cross-platform TLS lookup without either requiring third-party libraries, while still being independent of the version of libpthread being used. Test case included. llvm-svn: 192922
2013-10-18 05:14:00 +08:00
return LLDB_INVALID_ADDRESS;
}
Added support for thread local variables on all Apple OS variants. We had support that assumed that thread local data for a variable could be determined solely from the module in which the variable exists. While this work for linux, it doesn't work for Apple OSs. The DWARF for thread local variables consists of location opcodes that do something like: DW_OP_const8u (x) DW_OP_form_tls_address or DW_OP_const8u (x) DW_OP_GNU_push_tls_address The "x" is allowed to be anything that is needed to determine the location of the variable. For Linux "x" is the offset within the TLS data for a given executable (ModuleSP in LLDB). For Apple OS variants, it is the file address of the data structure that contains a pthread key that can be used with pthread_getspecific() and the offset needed. This fix passes the "x" along to the thread: virtual lldb::addr_t lldb_private::Thread::GetThreadLocalData(const lldb::ModuleSP module, lldb::addr_t tls_file_addr); Then this is passed along to the DynamicLoader::GetThreadLocalData(): virtual lldb::addr_t lldb_private::DynamicLoader::GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr); This allows each DynamicLoader plug-in do the right thing for the current OS. The DynamicLoaderMacOSXDYLD was modified to be able to grab the pthread key from the data structure that is in memory and call "void *pthread_getspecific(pthread_key_t key)" to get the value of the thread local storage and it caches it per thread since it never changes. I had to update the test case to access the thread local data before trying to print it as on Apple OS variants, thread locals are not available unless they have been accessed at least one by the current thread. I also added a new lldb::ValueType named "eValueTypeVariableThreadLocal" so that we can ask SBValue objects for their ValueType and be able to tell when we have a thread local variable. <rdar://problem/23308080> llvm-svn: 274366
2016-07-02 01:17:23 +08:00
bool Thread::SafeToCallFunctions() {
Process *process = GetProcess().get();
if (process) {
SystemRuntime *runtime = process->GetSystemRuntime();
if (runtime) {
return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
}
}
return true;
}
lldb::StackFrameSP
Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
}
const char *Thread::StopReasonAsCString(lldb::StopReason reason) {
switch (reason) {
case eStopReasonInvalid:
return "invalid";
case eStopReasonNone:
return "none";
case eStopReasonTrace:
return "trace";
case eStopReasonBreakpoint:
return "breakpoint";
LLDB AddressSanitizer instrumentation runtime plugin, breakpint on error and report data extraction Reviewed at http://reviews.llvm.org/D5592 This patch gives LLDB some ability to interact with AddressSanitizer runtime library, on top of what we already have (historical memory stack traces provided by ASan). Namely, that's the ability to stop on an error caught by ASan, and access the report information that are associated with it. The report information is also exposed into SB API. More precisely this patch... adds a new plugin type, InstrumentationRuntime, which should serve as a generic superclass for other instrumentation runtime libraries, these plugins get notified when modules are loaded, so they get a chance to "activate" when a specific dynamic library is loaded an instance of this plugin type, AddressSanitizerRuntime, which activates itself when it sees the ASan dynamic library or founds ASan statically linked in the executable adds a collection of these plugins into the Process class AddressSanitizerRuntime sets an internal breakpoint on __asan::AsanDie(), and when this breakpoint gets hit, it retrieves the report information from ASan this breakpoint is then exposed as a new StopReason, eStopReasonInstrumentation, with a new StopInfo subclass, InstrumentationRuntimeStopInfo the StopInfo superclass is extended with a m_extended_info field (it's a StructuredData::ObjectSP), that can hold arbitrary JSON-like data, which is the way the new plugin provides the report data the "thread info" command now accepts a "-s" flag that prints out the JSON data of a stop reason (same way the "-j" flag works now) SBThread has a new API, GetStopReasonExtendedInfoAsJSON, which dumps the JSON string into a SBStream adds a test case for all of this I plan to also get rid of the original ASan plugin (memory history stack traces) and use an instance of AddressSanitizerRuntime for that purpose. Kuba llvm-svn: 219546
2014-10-11 07:43:03 +08:00
case eStopReasonWatchpoint:
return "watchpoint";
case eStopReasonSignal:
return "signal";
LLDB AddressSanitizer instrumentation runtime plugin, breakpint on error and report data extraction Reviewed at http://reviews.llvm.org/D5592 This patch gives LLDB some ability to interact with AddressSanitizer runtime library, on top of what we already have (historical memory stack traces provided by ASan). Namely, that's the ability to stop on an error caught by ASan, and access the report information that are associated with it. The report information is also exposed into SB API. More precisely this patch... adds a new plugin type, InstrumentationRuntime, which should serve as a generic superclass for other instrumentation runtime libraries, these plugins get notified when modules are loaded, so they get a chance to "activate" when a specific dynamic library is loaded an instance of this plugin type, AddressSanitizerRuntime, which activates itself when it sees the ASan dynamic library or founds ASan statically linked in the executable adds a collection of these plugins into the Process class AddressSanitizerRuntime sets an internal breakpoint on __asan::AsanDie(), and when this breakpoint gets hit, it retrieves the report information from ASan this breakpoint is then exposed as a new StopReason, eStopReasonInstrumentation, with a new StopInfo subclass, InstrumentationRuntimeStopInfo the StopInfo superclass is extended with a m_extended_info field (it's a StructuredData::ObjectSP), that can hold arbitrary JSON-like data, which is the way the new plugin provides the report data the "thread info" command now accepts a "-s" flag that prints out the JSON data of a stop reason (same way the "-j" flag works now) SBThread has a new API, GetStopReasonExtendedInfoAsJSON, which dumps the JSON string into a SBStream adds a test case for all of this I plan to also get rid of the original ASan plugin (memory history stack traces) and use an instance of AddressSanitizerRuntime for that purpose. Kuba llvm-svn: 219546
2014-10-11 07:43:03 +08:00
case eStopReasonException:
return "exception";
LLDB AddressSanitizer instrumentation runtime plugin, breakpint on error and report data extraction Reviewed at http://reviews.llvm.org/D5592 This patch gives LLDB some ability to interact with AddressSanitizer runtime library, on top of what we already have (historical memory stack traces provided by ASan). Namely, that's the ability to stop on an error caught by ASan, and access the report information that are associated with it. The report information is also exposed into SB API. More precisely this patch... adds a new plugin type, InstrumentationRuntime, which should serve as a generic superclass for other instrumentation runtime libraries, these plugins get notified when modules are loaded, so they get a chance to "activate" when a specific dynamic library is loaded an instance of this plugin type, AddressSanitizerRuntime, which activates itself when it sees the ASan dynamic library or founds ASan statically linked in the executable adds a collection of these plugins into the Process class AddressSanitizerRuntime sets an internal breakpoint on __asan::AsanDie(), and when this breakpoint gets hit, it retrieves the report information from ASan this breakpoint is then exposed as a new StopReason, eStopReasonInstrumentation, with a new StopInfo subclass, InstrumentationRuntimeStopInfo the StopInfo superclass is extended with a m_extended_info field (it's a StructuredData::ObjectSP), that can hold arbitrary JSON-like data, which is the way the new plugin provides the report data the "thread info" command now accepts a "-s" flag that prints out the JSON data of a stop reason (same way the "-j" flag works now) SBThread has a new API, GetStopReasonExtendedInfoAsJSON, which dumps the JSON string into a SBStream adds a test case for all of this I plan to also get rid of the original ASan plugin (memory history stack traces) and use an instance of AddressSanitizerRuntime for that purpose. Kuba llvm-svn: 219546
2014-10-11 07:43:03 +08:00
case eStopReasonExec:
return "exec";
case eStopReasonPlanComplete:
return "plan complete";
case eStopReasonThreadExiting:
return "thread exiting";
case eStopReasonInstrumentation:
return "instrumentation break";
}
static char unknown_state_string[64];
snprintf(unknown_state_string, sizeof(unknown_state_string),
"StopReason = %i", reason);
return unknown_state_string;
}
const char *Thread::RunModeAsCString(lldb::RunMode mode) {
switch (mode) {
case eOnlyThisThread:
return "only this thread";
case eAllThreads:
return "all threads";
case eOnlyDuringStepping:
return "only during stepping";
}
static char unknown_state_string[64];
snprintf(unknown_state_string, sizeof(unknown_state_string), "RunMode = %i",
mode);
return unknown_state_string;
}
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
uint32_t num_frames, uint32_t num_frames_with_source,
bool stop_format, bool only_stacks) {
if (!only_stacks) {
ExecutionContext exe_ctx(shared_from_this());
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
strm.Indent();
bool is_selected = false;
if (process) {
if (process->GetThreadList().GetSelectedThread().get() == this)
is_selected = true;
}
strm.Printf("%c ", is_selected ? '*' : ' ');
if (target && target->GetDebugger().GetUseExternalEditor()) {
StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
if (frame_sp) {
SymbolContext frame_sc(
frame_sp->GetSymbolContext(eSymbolContextLineEntry));
if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file) {
Host::OpenFileInExternalEditor(frame_sc.line_entry.file,
frame_sc.line_entry.line);
}
}
}
DumpUsingSettingsFormat(strm, start_frame, stop_format);
}
size_t num_frames_shown = 0;
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
if (num_frames > 0) {
strm.IndentMore();
const bool show_frame_info = true;
const bool show_frame_unique = only_stacks;
const char *selected_frame_marker = nullptr;
if (num_frames == 1 || only_stacks ||
(GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
LLDB AddressSanitizer instrumentation runtime plugin, breakpint on error and report data extraction Reviewed at http://reviews.llvm.org/D5592 This patch gives LLDB some ability to interact with AddressSanitizer runtime library, on top of what we already have (historical memory stack traces provided by ASan). Namely, that's the ability to stop on an error caught by ASan, and access the report information that are associated with it. The report information is also exposed into SB API. More precisely this patch... adds a new plugin type, InstrumentationRuntime, which should serve as a generic superclass for other instrumentation runtime libraries, these plugins get notified when modules are loaded, so they get a chance to "activate" when a specific dynamic library is loaded an instance of this plugin type, AddressSanitizerRuntime, which activates itself when it sees the ASan dynamic library or founds ASan statically linked in the executable adds a collection of these plugins into the Process class AddressSanitizerRuntime sets an internal breakpoint on __asan::AsanDie(), and when this breakpoint gets hit, it retrieves the report information from ASan this breakpoint is then exposed as a new StopReason, eStopReasonInstrumentation, with a new StopInfo subclass, InstrumentationRuntimeStopInfo the StopInfo superclass is extended with a m_extended_info field (it's a StructuredData::ObjectSP), that can hold arbitrary JSON-like data, which is the way the new plugin provides the report data the "thread info" command now accepts a "-s" flag that prints out the JSON data of a stop reason (same way the "-j" flag works now) SBThread has a new API, GetStopReasonExtendedInfoAsJSON, which dumps the JSON string into a SBStream adds a test case for all of this I plan to also get rid of the original ASan plugin (memory history stack traces) and use an instance of AddressSanitizerRuntime for that purpose. Kuba llvm-svn: 219546
2014-10-11 07:43:03 +08:00
strm.IndentMore();
else
selected_frame_marker = "* ";
num_frames_shown = GetStackFrameList()->GetStatus(
strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
show_frame_unique, selected_frame_marker);
if (num_frames == 1)
strm.IndentLess();
strm.IndentLess();
}
return num_frames_shown;
}
bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level,
bool print_json_thread, bool print_json_stopinfo) {
const bool stop_format = false;
DumpUsingSettingsFormat(strm, 0, stop_format);
strm.Printf("\n");
StructuredData::ObjectSP thread_info = GetExtendedInfo();
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
if (print_json_thread || print_json_stopinfo) {
if (thread_info && print_json_thread) {
thread_info->Dump(strm);
strm.Printf("\n");
}
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
if (print_json_stopinfo && m_stop_info_sp) {
StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
if (stop_info) {
stop_info->Dump(strm);
strm.Printf("\n");
}
}
return true;
}
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
if (thread_info) {
StructuredData::ObjectSP activity =
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
thread_info->GetObjectForDotSeparatedPath("activity");
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
StructuredData::ObjectSP breadcrumb =
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
thread_info->GetObjectForDotSeparatedPath("breadcrumb");
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
StructuredData::ObjectSP messages =
thread_info->GetObjectForDotSeparatedPath("trace_messages");
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
bool printed_activity = false;
if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
if (name && name->GetType() == eStructuredDataTypeString && id &&
id->GetType() == eStructuredDataTypeInteger) {
strm.Format(" Activity '{0}', {1:x}\n",
name->GetAsString()->GetValue(),
id->GetAsInteger()->GetValue());
}
printed_activity = true;
}
bool printed_breadcrumb = false;
if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
if (printed_activity)
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
strm.Printf("\n");
StructuredData::Dictionary *breadcrumb_dict =
breadcrumb->GetAsDictionary();
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
StructuredData::ObjectSP breadcrumb_text =
breadcrumb_dict->GetValueForKey("name");
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
if (breadcrumb_text &&
breadcrumb_text->GetType() == eStructuredDataTypeString) {
strm.Format(" Current Breadcrumb: {0}\n",
breadcrumb_text->GetAsString()->GetValue());
}
printed_breadcrumb = true;
}
if (messages && messages->GetType() == eStructuredDataTypeArray) {
if (printed_breadcrumb)
strm.Printf("\n");
StructuredData::Array *messages_array = messages->GetAsArray();
const size_t msg_count = messages_array->GetSize();
if (msg_count > 0) {
strm.Printf(" %zu trace messages:\n", msg_count);
for (size_t i = 0; i < msg_count; i++) {
StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
if (message && message->GetType() == eStructuredDataTypeDictionary) {
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
StructuredData::Dictionary *message_dict =
message->GetAsDictionary();
StructuredData::ObjectSP message_text =
Initial merge of some of the iOS 8 / Mac OS X Yosemite specific lldb support. I'll be doing more testing & cleanup but I wanted to get the initial checkin done. This adds a new SBExpressionOptions::SetLanguage API for selecting a language of an expression. I added adds a new SBThread::GetInfoItemByPathString for retriving information about a thread from that thread's StructuredData. I added a new StructuredData class for representing key-value/array/dictionary information (e.g. JSON formatted data). Helper functions to read JSON and create a StructuredData object, and to print a StructuredData object in JSON format are included. A few Cocoa / Cocoa Touch data formatters were updated by Enrico to track changes in iOS 8 / Yosemite. Before we query a thread's extended information, the system runtime may provide hints to the remote debug stub that it will use to retrieve values out of runtime structures. I added a new SystemRuntime method AddThreadExtendedInfoPacketHints which allows the SystemRuntime to add key-value type data to the initial request that we send to the remote stub. The thread-format formatter string can now retrieve values out of a thread's extended info structured data. The default thread-format string picks up two of these - thread.info.activity.name and thread.info.trace_messages. I added a new "jThreadExtendedInfo" packet in debugserver; I will add documentation to the lldb-gdb-remote.txt doc soon. It accepts JSON formatted arguments (most importantly, "thread":threadnum) and it returns a variety of information regarding the thread to lldb in JSON format. This JSON return is scanned into a StructuredData object that is associated with the thread; UI layers can query the thread's StructuredData to see if key-values are present, and if so, show them to the user. These key-values are likely to be specific to different targets with some commonality among many targets. For instance, many targets will be able to advertise the pthread_t value for a thread. I added an initial rough cut of "thread info" command which will print the information about a thread from the jThreadExtendedInfo result. I need to do more work to make this format reasonably. Han Ming added calls into the pmenergy and pmsample libraries if debugserver is run on Mac OS X Yosemite to get information about the inferior's power use. I added support to debugserver for gathering the Genealogy information about threads, if it exists, and returning it in the jThreadExtendedInfo JSON result. llvm-svn: 210874
2014-06-13 10:37:02 +08:00
message_dict->GetValueForKey("message");
if (message_text &&
message_text->GetType() == eStructuredDataTypeString) {
strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
}
}
}
}
}
}
return true;
}
size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
Centralized a lot of the status information for processes, threads, and stack frame down in the lldb_private::Process, lldb_private::Thread, lldb_private::StackFrameList and the lldb_private::StackFrame classes. We had some command line commands that had duplicate versions of the process status output ("thread list" and "process status" for example). Removed the "file" command and placed it where it should have been: "target create". Made an alias for "file" to "target create" so we stay compatible with GDB commands. We can now have multple usable targets in lldb at the same time. This is nice for comparing two runs of a program or debugging more than one binary at the same time. The new command is "target select <target-idx>" and also to see a list of the current targets you can use the new "target list" command. The flow in a debug session can be: (lldb) target create /path/to/exe/a.out (lldb) breakpoint set --name main (lldb) run ... hit breakpoint (lldb) target create /bin/ls (lldb) run /tmp Process 36001 exited with status = 0 (0x00000000) (lldb) target list Current targets: target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) * target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) target select 0 Current targets: * target #0: /tmp/args/a.out ( arch=x86_64-apple-darwin, platform=localhost, pid=35999, state=stopped ) target #1: /bin/ls ( arch=x86_64-apple-darwin, platform=localhost, pid=36001, state=exited ) (lldb) bt * thread #1: tid = 0x2d03, 0x0000000100000b9a a.out`main + 42 at main.c:16, stop reason = breakpoint 1.1 frame #0: 0x0000000100000b9a a.out`main + 42 at main.c:16 frame #1: 0x0000000100000b64 a.out`start + 52 Above we created a target for "a.out" and ran and hit a breakpoint at "main". Then we created a new target for /bin/ls and ran it. Then we listed the targest and selected our original "a.out" program, so we showed two concurent debug sessions going on at the same time. llvm-svn: 129695
2011-04-18 16:33:37 +08:00
uint32_t num_frames, bool show_frame_info,
uint32_t num_frames_with_source) {
return GetStackFrameList()->GetStatus(
strm, first_frame, num_frames, show_frame_info, num_frames_with_source);
}
Unwind &Thread::GetUnwinder() {
if (!m_unwinder_up)
m_unwinder_up.reset(new UnwindLLDB(*this));
return *m_unwinder_up;
}
void Thread::Flush() {
ClearStackFrames();
m_reg_context_sp.reset();
}
bool Thread::IsStillAtLastBreakpointHit() {
// If we are currently stopped at a breakpoint, always return that stopinfo
// and don't reset it. This allows threads to maintain their breakpoint
// stopinfo, such as when thread-stepping in multithreaded programs.
if (m_stop_info_sp) {
StopReason stop_reason = m_stop_info_sp->GetStopReason();
if (stop_reason == lldb::eStopReasonBreakpoint) {
uint64_t value = m_stop_info_sp->GetValue();
lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
if (reg_ctx_sp) {
lldb::addr_t pc = reg_ctx_sp->GetPC();
Handle thumb IT instructions correctly all the time. The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true. When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed. This patch does the following: 1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb 2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute 3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb 4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below) This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added. <rdar://problem/19145455> llvm-svn: 223851
2014-12-10 07:31:02 +08:00
BreakpointSiteSP bp_site_sp =
GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
return true;
}
}
}
return false;
}
Status Thread::StepIn(bool source_step,
LazyBool step_in_avoids_code_without_debug_info,
LazyBool step_out_avoids_code_without_debug_info)
{
Status error;
Process *process = GetProcess().get();
if (StateIsStoppedState(process->GetState(), true)) {
StackFrameSP frame_sp = GetStackFrameAtIndex(0);
ThreadPlanSP new_plan_sp;
const lldb::RunMode run_mode = eOnlyThisThread;
const bool abort_other_plans = false;
if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
new_plan_sp = QueueThreadPlanForStepInRange(
abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,
step_in_avoids_code_without_debug_info,
step_out_avoids_code_without_debug_info);
} else {
new_plan_sp = QueueThreadPlanForStepSingleInstruction(
false, abort_other_plans, run_mode, error);
}
new_plan_sp->SetIsMasterPlan(true);
new_plan_sp->SetOkayToDiscard(false);
// Why do we need to set the current thread by ID here???
process->GetThreadList().SetSelectedThreadByID(GetID());
error = process->Resume();
} else {
error.SetErrorString("process not stopped");
}
return error;
}
Status Thread::StepOver(bool source_step,
LazyBool step_out_avoids_code_without_debug_info) {
Status error;
Process *process = GetProcess().get();
if (StateIsStoppedState(process->GetState(), true)) {
StackFrameSP frame_sp = GetStackFrameAtIndex(0);
ThreadPlanSP new_plan_sp;
const lldb::RunMode run_mode = eOnlyThisThread;
const bool abort_other_plans = false;
if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
new_plan_sp = QueueThreadPlanForStepOverRange(
abort_other_plans, sc.line_entry, sc, run_mode, error,
step_out_avoids_code_without_debug_info);
} else {
new_plan_sp = QueueThreadPlanForStepSingleInstruction(
true, abort_other_plans, run_mode, error);
}
new_plan_sp->SetIsMasterPlan(true);
new_plan_sp->SetOkayToDiscard(false);
// Why do we need to set the current thread by ID here???
process->GetThreadList().SetSelectedThreadByID(GetID());
error = process->Resume();
} else {
error.SetErrorString("process not stopped");
}
return error;
}
Status Thread::StepOut() {
Status error;
Process *process = GetProcess().get();
if (StateIsStoppedState(process->GetState(), true)) {
const bool first_instruction = false;
const bool stop_other_threads = false;
const bool abort_other_plans = false;
ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(
abort_other_plans, nullptr, first_instruction, stop_other_threads,
eVoteYes, eVoteNoOpinion, 0, error));
new_plan_sp->SetIsMasterPlan(true);
new_plan_sp->SetOkayToDiscard(false);
// Why do we need to set the current thread by ID here???
process->GetThreadList().SetSelectedThreadByID(GetID());
error = process->Resume();
} else {
error.SetErrorString("process not stopped");
}
return error;
}
ValueObjectSP Thread::GetCurrentException() {
if (auto frame_sp = GetStackFrameAtIndex(0))
if (auto recognized_frame = frame_sp->GetRecognizedFrame())
if (auto e = recognized_frame->GetExceptionObject())
return e;
// NOTE: Even though this behavior is generalized, only ObjC is actually
// supported at the moment.
for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
return e;
}
return ValueObjectSP();
}
ThreadSP Thread::GetCurrentExceptionBacktrace() {
ValueObjectSP exception = GetCurrentException();
if (!exception)
return ThreadSP();
// NOTE: Even though this behavior is generalized, only ObjC is actually
// supported at the moment.
for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
if (auto bt = runtime->GetBacktraceThreadFromException(exception))
return bt;
}
return ThreadSP();
}