Skip to content

[lldb] Assortment of cherry-picks from upstream LLVM #10866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions lldb/examples/synthetic/libcxx.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,13 @@ def get_child_index(self, name):
except:
return -1

@staticmethod
def _subscript(ptr: lldb.SBValue, idx: int, name: str) -> lldb.SBValue:
"""Access a pointer value as if it was an array. Returns ptr[idx]."""
deref_t = ptr.GetType().GetPointeeType()
offset = idx * deref_t.GetByteSize()
return ptr.CreateChildAtOffset(name, offset, deref_t)

def get_child_at_index(self, index):
logger = lldb.formatters.Logger.Logger()
logger.write("Fetching child " + str(index))
Expand All @@ -703,11 +710,8 @@ def get_child_at_index(self, index):
return None
try:
i, j = divmod(self.start + index, self.block_size)

return self.first.CreateValueFromExpression(
"[" + str(index) + "]",
"*(*(%s + %d) + %d)" % (self.map_begin.get_expr_path(), i, j),
)
val = stddeque_SynthProvider._subscript(self.map_begin, i, "")
return stddeque_SynthProvider._subscript(val, j, f"[{index}]")
except:
return None

Expand Down Expand Up @@ -764,9 +768,10 @@ def update(self):
map_.GetChildMemberWithName("__end_cap_")
)
else:
map_endcap = map_.GetChildMemberWithName(
"__end_cap_"
).GetValueAsUnsigned(0)
map_endcap = map_.GetChildMemberWithName("__cap_")
if not map_endcap.IsValid():
map_endcap = map_.GetChildMemberWithName("__end_cap_")
map_endcap = map_endcap.GetValueAsUnsigned(0)

# check consistency
if not map_first <= map_begin <= map_end <= map_endcap:
Expand Down
116 changes: 12 additions & 104 deletions lldb/source/Plugins/ExpressionParser/Clang/IRDynamicChecks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

#include "lldb/Expression/UtilityFunction.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Language.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/Target.h"
Expand All @@ -32,36 +33,27 @@ using namespace lldb_private;

static char ID;

#define VALID_POINTER_CHECK_NAME "_$__lldb_valid_pointer_check"
#define VALID_OBJC_OBJECT_CHECK_NAME "$__lldb_objc_object_check"

static const char g_valid_pointer_check_text[] =
"extern \"C\" void\n"
"_$__lldb_valid_pointer_check (unsigned char *$__lldb_arg_ptr)\n"
"{\n"
" unsigned char $__lldb_local_val = *$__lldb_arg_ptr;\n"
"}";

ClangDynamicCheckerFunctions::ClangDynamicCheckerFunctions()
: DynamicCheckerFunctions(DCF_Clang) {}

ClangDynamicCheckerFunctions::~ClangDynamicCheckerFunctions() = default;

llvm::Error ClangDynamicCheckerFunctions::Install(
DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
Expected<std::unique_ptr<UtilityFunction>> utility_fn =
exe_ctx.GetTargetRef().CreateUtilityFunction(
g_valid_pointer_check_text, VALID_POINTER_CHECK_NAME,
lldb::eLanguageTypeC, exe_ctx);
if (!utility_fn)
return utility_fn.takeError();
m_valid_pointer_check = std::move(*utility_fn);

llvm::Error
ClangDynamicCheckerFunctions::Install(DiagnosticManager &diagnostic_manager,
ExecutionContext &exe_ctx) {
if (Process *process = exe_ctx.GetProcessPtr()) {
ObjCLanguageRuntime *objc_language_runtime =
ObjCLanguageRuntime::Get(*process);

if (objc_language_runtime) {
SourceLanguage lang = process->GetTarget().GetLanguage();
if (!lang)
if (auto *frame = exe_ctx.GetFramePtr())
lang = frame->GetLanguage();

if (objc_language_runtime &&
Language::LanguageIsObjC(lang.AsLanguageType())) {
Expected<std::unique_ptr<UtilityFunction>> checker_fn =
objc_language_runtime->CreateObjectChecker(VALID_OBJC_OBJECT_CHECK_NAME, exe_ctx);
if (!checker_fn)
Expand All @@ -78,11 +70,7 @@ bool ClangDynamicCheckerFunctions::DoCheckersExplainStop(lldb::addr_t addr,
// FIXME: We have to get the checkers to know why they scotched the call in
// more detail,
// so we can print a better message here.
if (m_valid_pointer_check && m_valid_pointer_check->ContainsAddress(addr)) {
message.Printf("Attempted to dereference an invalid pointer.");
return true;
} else if (m_objc_object_check &&
m_objc_object_check->ContainsAddress(addr)) {
if (m_objc_object_check && m_objc_object_check->ContainsAddress(addr)) {
message.Printf("Attempted to dereference an invalid ObjC Object or send it "
"an unrecognized selector");
return true;
Expand Down Expand Up @@ -224,29 +212,6 @@ class Instrumenter {
return true;
}

/// Build a function pointer for a function with signature void
/// (*)(uint8_t*) with a given address
///
/// \param[in] start_address
/// The address of the function.
///
/// \return
/// The function pointer, for use in a CallInst.
llvm::FunctionCallee BuildPointerValidatorFunc(lldb::addr_t start_address) {
llvm::Type *param_array[1];

param_array[0] = const_cast<llvm::PointerType *>(GetI8PtrTy());

ArrayRef<llvm::Type *> params(param_array, 1);

FunctionType *fun_ty = FunctionType::get(
llvm::Type::getVoidTy(m_module.getContext()), params, true);
PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
Constant *fun_addr_int =
ConstantInt::get(GetIntptrTy(), start_address, false);
return {fun_ty, ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty)};
}

/// Build a function pointer for a function with signature void
/// (*)(uint8_t*, uint8_t*) with a given address
///
Expand Down Expand Up @@ -301,53 +266,6 @@ class Instrumenter {
IntegerType *m_intptr_ty = nullptr;
};

class ValidPointerChecker : public Instrumenter {
public:
ValidPointerChecker(llvm::Module &module,
std::shared_ptr<UtilityFunction> checker_function)
: Instrumenter(module, checker_function),
m_valid_pointer_check_func(nullptr) {}

~ValidPointerChecker() override = default;

protected:
bool InstrumentInstruction(llvm::Instruction *inst) override {
Log *log = GetLog(LLDBLog::Expressions);

LLDB_LOGF(log, "Instrumenting load/store instruction: %s\n",
PrintValue(inst).c_str());

if (!m_valid_pointer_check_func)
m_valid_pointer_check_func =
BuildPointerValidatorFunc(m_checker_function->StartAddress());

llvm::Value *dereferenced_ptr = nullptr;

if (llvm::LoadInst *li = dyn_cast<llvm::LoadInst>(inst))
dereferenced_ptr = li->getPointerOperand();
else if (llvm::StoreInst *si = dyn_cast<llvm::StoreInst>(inst))
dereferenced_ptr = si->getPointerOperand();
else
return false;

// Insert an instruction to call the helper with the result
CallInst::Create(m_valid_pointer_check_func, dereferenced_ptr, "",
inst->getIterator());

return true;
}

bool InspectInstruction(llvm::Instruction &i) override {
if (isa<llvm::LoadInst>(&i) || isa<llvm::StoreInst>(&i))
RegisterInstruction(i);

return true;
}

private:
llvm::FunctionCallee m_valid_pointer_check_func;
};

class ObjcObjectChecker : public Instrumenter {
public:
ObjcObjectChecker(llvm::Module &module,
Expand Down Expand Up @@ -528,16 +446,6 @@ bool IRDynamicChecks::runOnModule(llvm::Module &M) {
return false;
}

if (m_checker_functions.m_valid_pointer_check) {
ValidPointerChecker vpc(M, m_checker_functions.m_valid_pointer_check);

if (!vpc.Inspect(*function))
return false;

if (!vpc.Instrument())
return false;
}

if (m_checker_functions.m_objc_object_check) {
ObjcObjectChecker ooc(M, m_checker_functions.m_objc_object_check);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ class ClangDynamicCheckerFunctions

bool DoCheckersExplainStop(lldb::addr_t addr, Stream &message) override;

std::shared_ptr<UtilityFunction> m_valid_pointer_check;
std::shared_ptr<UtilityFunction> m_objc_object_check;
};

Expand Down
21 changes: 14 additions & 7 deletions lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,22 @@ static bool isUnorderedMap(ConstString type_name) {

CompilerType lldb_private::formatters::LibcxxStdUnorderedMapSyntheticFrontEnd::
GetElementType(CompilerType table_type) {
auto element_type = table_type.GetTypedefedType().GetTypeTemplateArgument(0);
auto element_type =
table_type.GetDirectNestedTypeWithName("value_type").GetTypedefedType();

// In newer unordered_map layouts, the std::pair element type isn't wrapped
// in any helper types. So return it directly.
if (isStdTemplate(element_type.GetTypeName(), "pair"))
return element_type;

// This synthetic provider is used for both unordered_(multi)map and
// unordered_(multi)set. For unordered_map, the element type has an
// additional type layer, an internal struct (`__hash_value_type`)
// that wraps a std::pair. Peel away the internal wrapper type - whose
// structure is of no value to users, to expose the std::pair. This
// matches the structure returned by the std::map synthetic provider.
if (isUnorderedMap(m_backend.GetTypeName())) {
// unordered_(multi)set. For older unordered_map layouts, the element type has
// an additional type layer, an internal struct (`__hash_value_type`) that
// wraps a std::pair. Peel away the internal wrapper type - whose structure is
// of no value to users, to expose the std::pair. This matches the structure
// returned by the std::map synthetic provider.
if (isUnorderedMap(
m_backend.GetCompilerType().GetCanonicalType().GetTypeName())) {
std::string name;
CompilerType field_type =
element_type.GetFieldAtIndex(0, name, nullptr, nullptr, nullptr);
Expand Down
6 changes: 0 additions & 6 deletions lldb/test/API/tools/lldb-dap/save-core/TestDAP_save_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,7 @@ def test_save_core(self):
# Getting dap stack trace may trigger __lldb_caller_function JIT module to be created.
self.get_stackFrames(startFrame=0)

# Evaluating an expression that cause "_$__lldb_valid_pointer_check" JIT module to be created.
expression = 'printf("this is a test")'
self.dap_server.request_evaluate(expression, context="watch")

# Verify "_$__lldb_valid_pointer_check" JIT module is created.
modules = self.dap_server.get_modules()
self.assertTrue(modules["_$__lldb_valid_pointer_check"])
thread_count = len(self.dap_server.get_threads())

core_stack = self.getBuildArtifact("core.stack.dmp")
Expand Down