Skip to content

[lldb] Resolve Swift-implemented Objective-C classes using Swift runtime #10548

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 1 commit into from
May 7, 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
25 changes: 21 additions & 4 deletions lldb/source/Plugins/ExpressionParser/Swift/SwiftREPL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -501,13 +501,30 @@ bool SwiftREPL::PrintOneVariable(Debugger &debugger, StreamFileSP &output_sp,
options.SetRevealEmptyAggregates(false);
options.SetHidePointerValue(true);
options.SetVariableFormatDisplayLanguage(lldb::eLanguageTypeSwift);
options.SetDeclPrintingHelper([](ConstString type_name,
ConstString var_name,
const DumpValueObjectOptions &options,
Stream &stream) -> bool {
options.SetDeclPrintingHelper([&](ConstString type_name,
ConstString var_name,
const DumpValueObjectOptions &options,
Stream &stream) -> bool {
if (!type_name || !var_name)
return false;

// Try to get the SwiftASTContext representation of the type. It
// will hide Objective-C implemention details that are not
// publicly declared in the SDK.
if (valobj_sp) {
auto static_valobj_sp = valobj_sp->GetStaticValue();
auto dynamic_valobj_sp =
valobj_sp->GetDynamicValue(lldb::eDynamicCanRunTarget);
if (static_valobj_sp && dynamic_valobj_sp) {
CompilerType static_type = static_valobj_sp->GetCompilerType();
CompilerType dynamic_type = dynamic_valobj_sp->GetCompilerType();
auto ts =
dynamic_type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>();
if (ts &&
ts->IsImportedType(dynamic_type.GetOpaqueQualType(), nullptr))
type_name = static_type.GetDisplayTypeName();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we always want to use the static type if the dynamic type is an Objective-C type? I guess in the REPL this makes sense

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, this is a very blunt tool to hide some of the Foundation implementation detail types that users are not meant to see / know / care about.
It doesn't not work for Swift-implemented types like _SwiftDeferredNSDictionary, which is going to be more prevalent going forward.

}
}
std::string type_name_str(type_name ? type_name.GetCString() : "");
for (auto iter = type_name_str.find(" *"); iter != std::string::npos;
iter = type_name_str.find(" *")) {
Expand Down
30 changes: 20 additions & 10 deletions lldb/source/Plugins/Language/Swift/SwiftHashedContainer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,9 @@ HashedCollectionConfig::RegisterSummaryProviders(
AddCXXSummary(swift_category_sp, summaryProvider,
m_summaryProviderName.AsCString(),
m_emptyStorage_demangled, flags, false);
AddCXXSummary(swift_category_sp, summaryProvider,
m_summaryProviderName.AsCString(),
m_nativeStorageRoot_demangled, flags, false);
AddCXXSummary(swift_category_sp, summaryProvider,
m_summaryProviderName.AsCString(),
m_deferredBridgedStorage_demangledRegex, flags, true);
Expand Down Expand Up @@ -231,6 +234,9 @@ HashedCollectionConfig::RegisterSyntheticChildrenCreators(
AddCXXSynthetic(swift_category_sp, creator,
m_syntheticChildrenName.AsCString(),
m_nativeStorage_demangledRegex, flags, true);
AddCXXSynthetic(swift_category_sp, creator,
m_syntheticChildrenName.AsCString(),
m_nativeStorageRoot_demangled, flags, false);
AddCXXSynthetic(swift_category_sp, creator,
m_syntheticChildrenName.AsCString(),
m_emptyStorage_demangled, flags, false);
Expand Down Expand Up @@ -648,18 +654,22 @@ HashedCollectionConfig::CreateHandler(ValueObject &valobj) const {
return CreateNativeHandler(valobj_sp, storage_sp);
}

ValueObjectSP variant_sp =
valobj_sp->GetChildMemberWithName(g__variant, true);
if (!variant_sp)
return nullptr;
lldb::addr_t storage_location = LLDB_INVALID_ADDRESS;
if (type_name_cs == m_nativeStorageRoot_demangled)
storage_location = valobj_sp->GetPointerValue();
else {
ValueObjectSP variant_sp =
valobj_sp->GetChildMemberWithName(g__variant, true);
if (!variant_sp)
return nullptr;

ValueObjectSP bobject_sp =
variant_sp->GetChildAtNamePath({g_object, g_rawValue});
if (!bobject_sp)
return nullptr;
ValueObjectSP bobject_sp =
variant_sp->GetChildAtNamePath({g_object, g_rawValue});
if (!bobject_sp)
return nullptr;

lldb::addr_t storage_location =
bobject_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
storage_location = bobject_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
}
if (storage_location == LLDB_INVALID_ADDRESS)
return nullptr;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2022,21 +2022,6 @@ bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_Pack(
return true;
}

static bool IsPrivateNSClass(NodePointer node) {
if (!node || node->getKind() != Node::Kind::Type ||
node->getNumChildren() == 0)
return false;
NodePointer classNode = node->getFirstChild();
if (!classNode || classNode->getKind() != Node::Kind::Class ||
classNode->getNumChildren() < 2)
return false;
for (NodePointer child : *classNode)
if (child->getKind() == Node::Kind::Identifier && child->hasText())
return child->getText().starts_with("__NS") ||
child->getText().starts_with("NSTaggedPointer");
return false;
}

CompilerType SwiftLanguageRuntime::GetDynamicTypeAndAddress_EmbeddedClass(
uint64_t instance_ptr, CompilerType class_type) {
ThreadSafeReflectionContext reflection_ctx = GetReflectionContext();
Expand Down Expand Up @@ -2091,44 +2076,41 @@ bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_Class(
return false;

auto tss = class_type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>();
if (!tss) {
// This could be an Objective-C type implemented in Swift. Get the
// Swift typesystem.
if (auto module_sp = in_value.GetModule()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why this is needed. If the type does not have a Swift type system (even if it's a swiftified objc type), then something has gone wrong, and we shouldn't be asking the Swift Language Runtime, no?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question! Let me try replacing this with an assert(false) to answer how we get here.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The answer is

bool ValueObjectDynamicValue::UpdateValue() {
...
#ifdef LLDB_ENABLE_SWIFT
  // An Objective-C object inside a Swift frame.
  if (known_type == eLanguageTypeObjC)
    if ((exe_ctx.GetFramePtr() && exe_ctx.GetFramePtr()->GetLanguage().name ==
                                      llvm::dwarf::DW_LNAME_Swift) ||
        (exe_ctx.GetTargetPtr() && exe_ctx.GetTargetPtr()->IsSwiftREPL())) {
      runtime = process->GetLanguageRuntime(lldb::eLanguageTypeSwift);
      if (runtime)
        found_dynamic_type = runtime->GetDynamicTypeAndAddress(
            *m_parent, m_use_dynamic, class_type_or_name, dynamic_address,
            value_type, local_buffer);
    }
#endif // LLDB_ENABLE_SWIFT

let me see if I can simplify this.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was able to eliminate the entire resolve_objc lambda. The interesting part is that it was also trying to solve the private implementation detail problem, however, this was no longer working.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that the resolve_objc lambda has been removed do we still need this block of code in case the type is a clang type then?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is still an actively used code block. I updated the comment to explain why.

auto type_system_or_err =
module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
return false;
}
auto ts_sp = *type_system_or_err;
tss =
llvm::cast<TypeSystemSwift>(ts_sp.get())->GetTypeSystemSwiftTypeRef();
} else if (auto target_sp = in_value.GetTargetSP()) {
auto type_system_or_err =
target_sp->GetScratchTypeSystemForLanguage(lldb::eLanguageTypeSwift);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
return false;
}
auto ts_sp = *type_system_or_err;
tss =
llvm::cast<TypeSystemSwift>(ts_sp.get())->GetTypeSystemSwiftTypeRef();
}
}
if (!tss)
return false;

address.SetRawAddress(instance_ptr);
auto ts = tss->GetTypeSystemSwiftTypeRef();
if (!ts)
return false;
// Ask the Objective-C runtime about Objective-C types.
if (tss->IsImportedType(class_type.GetOpaqueQualType(), nullptr))
if (auto *objc_runtime =
SwiftLanguageRuntime::GetObjCRuntime(GetProcess())) {
Value::ValueType value_type;
if (objc_runtime->GetDynamicTypeAndAddress(in_value, use_dynamic,
class_type_or_name, address,
value_type, local_buffer)) {
bool found = false;
// Return the most specific class which we can get the typeref.
ForEachSuperClassType(in_value, [&](SuperClassType sc) -> bool {
if (auto *tr = sc.get_typeref()) {
swift::Demangle::Demangler dem;
swift::Demangle::NodePointer node = tr->getDemangling(dem);
// Skip private Foundation types since it's unlikely that would be
// useful to users.
if (IsPrivateNSClass(node))
return false;
class_type_or_name.SetCompilerType(ts->RemangleAsType(
dem, node, swift::Mangle::ManglingFlavor::Default));
found = true;
return true;
}
return false;
});
return found;
}
return false;
}
Log *log(GetLog(LLDBLog::Types));
// Scope reflection_ctx to minimize its lock scope.
{

auto resolve_swift = [&]() {
// Scope reflection_ctx to minimize its lock scope.
ThreadSafeReflectionContext reflection_ctx = GetReflectionContext();
if (!reflection_ctx)
return false;
Expand Down Expand Up @@ -2172,10 +2154,17 @@ bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_Class(
return false;
}
}

LLDB_LOG(log, "dynamic type of instance_ptr {0:x} is {1}", instance_ptr,
class_type.GetMangledTypeName());
class_type_or_name.SetCompilerType(dynamic_type);
LLDB_LOG(GetLog(LLDBLog::Types),
"dynamic type of instance_ptr {0:x} is {1}", instance_ptr,
class_type.GetMangledTypeName());
return true;
};

if (!resolve_swift()) {
// When returning false here, the next compatible runtime (=
// Objective-C) will get ask to resolve this type.
return false;
}

#ifndef NDEBUG
Expand Down Expand Up @@ -2833,12 +2822,12 @@ bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_IndirectEnumCase(

return GetDynamicTypeAndAddress(*valobj_sp, use_dynamic, class_type_or_name,
address, value_type, local_buffer);
} else {
// This is most likely a statically known type.
address.SetLoadAddress(box_value, &GetProcess().GetTarget());
value_type = Value::GetValueTypeFromAddressType(eAddressTypeLoad);
return true;
}

// This is most likely a statically known type.
address.SetLoadAddress(box_value, &GetProcess().GetTarget());
value_type = Value::GetValueTypeFromAddressType(eAddressTypeLoad);
return true;
}

void SwiftLanguageRuntime::DumpTyperef(CompilerType type,
Expand Down Expand Up @@ -3156,22 +3145,27 @@ bool SwiftLanguageRuntime::GetDynamicTypeAndAddress(
return false;

LLDB_SCOPED_TIMER();
CompilerType val_type(in_value.GetCompilerType());
Value::ValueType static_value_type = Value::ValueType::Invalid;

// Try to import a Clang type into Swift.
if (in_value.GetObjectRuntimeLanguage() == eLanguageTypeObjC)
return GetDynamicTypeAndAddress_ClangType(in_value, use_dynamic,
class_type_or_name, address,
value_type, local_buffer);
if (in_value.GetObjectRuntimeLanguage() == eLanguageTypeObjC) {
if (GetDynamicTypeAndAddress_ClangType(in_value, use_dynamic,
class_type_or_name, address,
value_type, local_buffer))
return true;
return GetDynamicTypeAndAddress_Class(in_value, val_type, use_dynamic,
class_type_or_name, address,
static_value_type, local_buffer);
}

if (!CouldHaveDynamicValue(in_value))
return false;

CompilerType val_type(in_value.GetCompilerType());
Flags type_info(val_type.GetTypeInfo());
if (!type_info.AnySet(eTypeIsSwift))
return false;

Value::ValueType static_value_type = Value::ValueType::Invalid;
bool success = false;
bool is_indirect_enum_case = IsIndirectEnumCase(in_value);
// Type kinds with instance metadata don't need generic type resolution.
Expand Down
38 changes: 21 additions & 17 deletions lldb/source/Plugins/TypeSystem/Swift/SwiftASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -996,7 +996,7 @@ SwiftASTContext::SwiftASTContext()
}
#endif

SwiftASTContext::SwiftASTContext(std::string description,
SwiftASTContext::SwiftASTContext(std::string description, ModuleSP module_sp,
TypeSystemSwiftTypeRefSP typeref_typesystem)
: TypeSystemSwift(), m_typeref_typesystem(typeref_typesystem),
m_compiler_invocation_ap(new swift::CompilerInvocation()),
Expand All @@ -1006,6 +1006,7 @@ SwiftASTContext::SwiftASTContext(std::string description,
"Swift AST context instantiation is disabled!");

m_description = description;
m_module = module_sp.get();

// Set the clang modules cache path.
m_compiler_invocation_ap->setClangModuleCachePath(
Expand Down Expand Up @@ -2431,7 +2432,8 @@ SwiftASTContext::CreateInstance(lldb::LanguageType language, Module &module,
// If there is a target this may be a fallback scratch context.
std::shared_ptr<SwiftASTContext> swift_ast_sp(
static_cast<SwiftASTContext *>(new SwiftASTContextForModule(
m_description, typeref_typesystem.GetTypeSystemSwiftTypeRef())));
m_description, module.shared_from_this(),
typeref_typesystem.GetTypeSystemSwiftTypeRef())));
bool suppress_config_log = false;
auto defer_log =
llvm::make_scope_exit([swift_ast_sp, &suppress_config_log] {
Expand All @@ -2444,7 +2446,6 @@ SwiftASTContext::CreateInstance(lldb::LanguageType language, Module &module,

// This is a module AST context, mark it as such.
swift_ast_sp->m_is_scratch_context = false;
swift_ast_sp->m_module = &module;
swift_ast_sp->GetLanguageOptions().EnableAccessControl = false;
swift_ast_sp->GetLanguageOptions().EnableCXXInterop =
module.IsSwiftCxxInteropEnabled();
Expand Down Expand Up @@ -2781,7 +2782,8 @@ SwiftASTContext::CreateInstance(const SymbolContext &sc,
return {};
}
swift_ast_sp.reset(new SwiftASTContextForExpressions(
m_description, typeref_typesystem.GetTypeSystemSwiftTypeRef()));
m_description, module_sp,
typeref_typesystem.GetTypeSystemSwiftTypeRef()));
// This is a scratch AST context, mark it as such.
swift_ast_sp->m_is_scratch_context = true;
auto &lang_opts = swift_ast_sp->GetLanguageOptions();
Expand All @@ -2796,10 +2798,10 @@ SwiftASTContext::CreateInstance(const SymbolContext &sc,
}
swift_ast_sp.reset(
static_cast<SwiftASTContext *>(new SwiftASTContextForModule(
m_description, typeref_typesystem.GetTypeSystemSwiftTypeRef())));
m_description, module_sp,
typeref_typesystem.GetTypeSystemSwiftTypeRef())));
// This is a module AST context, mark it as such.
swift_ast_sp->m_is_scratch_context = false;
swift_ast_sp->m_module = module_sp.get();
auto &lang_opts = swift_ast_sp->GetLanguageOptions();
lang_opts.EnableAccessControl = false;
lang_opts.EnableCXXInterop = ShouldEnableCXXInterop(cu);
Expand Down Expand Up @@ -4695,14 +4697,10 @@ CompilerType SwiftASTContext::GetAsClangType(ConstString mangled_name) {
// that look like they might be come from Objective-C (or C) as
// Clang types. LLDB's Objective-C part is very robust against
// malformed object pointers, so this isn't very risky.
auto ts = GetTypeSystemSwiftTypeRef();
if (!ts)
return {};
Module *module = ts->GetModule();
if (!module)
if (!m_module)
return {};
auto type_system_or_err =
module->GetTypeSystemForLanguage(eLanguageTypeObjC);
m_module->GetTypeSystemForLanguage(eLanguageTypeObjC);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
return {};
Expand All @@ -4714,11 +4712,16 @@ CompilerType SwiftASTContext::GetAsClangType(ConstString mangled_name) {
return {};
DWARFASTParserClang *clang_ast_parser =
static_cast<DWARFASTParserClang *>(clang_ctx->GetDWARFParser());

SymbolContext sc;
m_module->CalculateSymbolContext(&sc);
CompilerType clang_type;
CompilerType imported_type = GetCompilerType(mangled_name);
if (auto ts =
imported_type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>())
ts->IsImportedType(imported_type.GetOpaqueQualType(), &clang_type);
if (auto ts = imported_type.GetTypeSystem()
.dyn_cast_or_null<TypeSystemSwiftTypeRef>())
if (ts->IsImportedType(imported_type.GetOpaqueQualType(), nullptr))
if (TypeSP result = ts->LookupClangType(mangled_name, sc))
clang_type = result->GetForwardCompilerType();

// Import the Clang type into the Clang context.
if (!clang_type)
Expand Down Expand Up @@ -8930,8 +8933,9 @@ SwiftASTContext::GetASTVectorForModule(const Module *module) {
}

SwiftASTContextForExpressions::SwiftASTContextForExpressions(
std::string description, TypeSystemSwiftTypeRefSP typeref_typesystem)
: SwiftASTContext(std::move(description), typeref_typesystem) {
std::string description, ModuleSP module_sp,
TypeSystemSwiftTypeRefSP typeref_typesystem)
: SwiftASTContext(std::move(description), module_sp, typeref_typesystem) {
assert(llvm::isa<TypeSystemSwiftTypeRefForExpressions>(
m_typeref_typesystem.lock().get()));
}
Expand Down
Loading