Path: blob/main/contrib/llvm-project/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp
39688 views
//===-- AppleObjCTrampolineHandler.cpp ------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "AppleObjCTrampolineHandler.h"9#include "AppleThreadPlanStepThroughObjCTrampoline.h"1011#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"12#include "lldb/Breakpoint/StoppointCallbackContext.h"13#include "lldb/Core/Debugger.h"14#include "lldb/Core/Module.h"15#include "lldb/Core/Value.h"16#include "lldb/Expression/DiagnosticManager.h"17#include "lldb/Expression/FunctionCaller.h"18#include "lldb/Expression/UserExpression.h"19#include "lldb/Expression/UtilityFunction.h"20#include "lldb/Symbol/Symbol.h"21#include "lldb/Target/ABI.h"22#include "lldb/Target/ExecutionContext.h"23#include "lldb/Target/Process.h"24#include "lldb/Target/RegisterContext.h"25#include "lldb/Target/Target.h"26#include "lldb/Target/Thread.h"27#include "lldb/Target/ThreadPlanRunToAddress.h"28#include "lldb/Utility/ConstString.h"29#include "lldb/Utility/FileSpec.h"30#include "lldb/Utility/LLDBLog.h"31#include "lldb/Utility/Log.h"3233#include "llvm/ADT/STLExtras.h"34#include "llvm/ADT/ScopeExit.h"3536#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"3738#include <memory>3940using namespace lldb;41using namespace lldb_private;4243const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name =44"__lldb_objc_find_implementation_for_selector";45const char *AppleObjCTrampolineHandler::46g_lookup_implementation_with_stret_function_code =47R"(48if (is_stret) {49return_struct.impl_addr =50class_getMethodImplementation_stret (return_struct.class_addr,51return_struct.sel_addr);52} else {53return_struct.impl_addr =54class_getMethodImplementation (return_struct.class_addr,55return_struct.sel_addr);56}57if (debug)58printf ("\n*** Returning implementation: %p.\n",59return_struct.impl_addr);6061return return_struct.impl_addr;62}63)";64const char *65AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code =66R"(67return_struct.impl_addr =68class_getMethodImplementation (return_struct.class_addr,69return_struct.sel_addr);70if (debug)71printf ("\n*** getMethodImpletation for addr: 0x%p sel: 0x%p result: 0x%p.\n",72return_struct.class_addr, return_struct.sel_addr, return_struct.impl_addr);7374return return_struct.impl_addr;75}76)";7778const char79*AppleObjCTrampolineHandler::g_lookup_implementation_function_common_code =80R"(81extern "C"82{83extern void *class_getMethodImplementation(void *objc_class, void *sel);84extern void *class_getMethodImplementation_stret(void *objc_class, void *sel);85extern void * object_getClass (id object);86extern void * sel_getUid(char *name);87extern int printf(const char *format, ...);88}89extern "C" void *90__lldb_objc_find_implementation_for_selector (void *object,91void *sel,92int is_str_ptr,93int is_stret,94int is_super,95int is_super2,96int is_fixup,97int is_fixed,98int debug)99{100struct __lldb_imp_return_struct {101void *class_addr;102void *sel_addr;103void *impl_addr;104};105106struct __lldb_objc_class {107void *isa;108void *super_ptr;109};110struct __lldb_objc_super {111void *receiver;112struct __lldb_objc_class *class_ptr;113};114struct __lldb_msg_ref {115void *dont_know;116void *sel;117};118119struct __lldb_imp_return_struct return_struct;120121if (debug)122printf ("\n*** Called with obj: %p sel: %p is_str_ptr: %d "123"is_stret: %d is_super: %d, "124"is_super2: %d, is_fixup: %d, is_fixed: %d\n",125object, sel, is_str_ptr, is_stret,126is_super, is_super2, is_fixup, is_fixed);127128if (is_str_ptr) {129if (debug)130printf("*** Turning string: '%s'", sel);131sel = sel_getUid((char *)sel);132if (debug)133printf("*** into sel to %p", sel);134}135if (is_super) {136if (is_super2) {137return_struct.class_addr138= ((__lldb_objc_super *) object)->class_ptr->super_ptr;139} else {140return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr;141}142if (debug)143printf("*** Super, class addr: %p\n", return_struct.class_addr);144} else {145// This code seems a little funny, but has its reasons...146// The call to [object class] is here because if this is a class, and has147// not been called into yet, we need to do something to force the class to148// initialize itself.149// Then the call to object_getClass will actually return the correct class,150// either the class if object is a class instance, or the meta-class if it151// is a class pointer.152void *class_ptr = (void *) [(id) object class];153return_struct.class_addr = (id) object_getClass((id) object);154if (debug) {155if (class_ptr == object) {156printf ("Found a class object, need to return the meta class %p -> %p\n",157class_ptr, return_struct.class_addr);158} else {159printf ("[object class] returned: %p object_getClass: %p.\n",160class_ptr, return_struct.class_addr);161}162}163}164165if (is_fixup) {166if (is_fixed) {167return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel;168} else {169char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel;170return_struct.sel_addr = sel_getUid (sel_name);171if (debug)172printf ("\n*** Got fixed up selector: %p for name %s.\n",173return_struct.sel_addr, sel_name);174}175} else {176return_struct.sel_addr = sel;177}178)";179180AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion(181AppleObjCVTables *owner, lldb::addr_t header_addr)182: m_valid(true), m_owner(owner), m_header_addr(header_addr) {183SetUpRegion();184}185186AppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() = default;187188void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() {189// The header looks like:190//191// uint16_t headerSize192// uint16_t descSize193// uint32_t descCount194// void * next195//196// First read in the header:197198char memory_buffer[16];199ProcessSP process_sp = m_owner->GetProcessSP();200if (!process_sp)201return;202DataExtractor data(memory_buffer, sizeof(memory_buffer),203process_sp->GetByteOrder(),204process_sp->GetAddressByteSize());205size_t actual_size = 8 + process_sp->GetAddressByteSize();206Status error;207size_t bytes_read =208process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error);209if (bytes_read != actual_size) {210m_valid = false;211return;212}213214lldb::offset_t offset = 0;215const uint16_t header_size = data.GetU16(&offset);216const uint16_t descriptor_size = data.GetU16(&offset);217const size_t num_descriptors = data.GetU32(&offset);218219m_next_region = data.GetAddress(&offset);220221// If the header size is 0, that means we've come in too early before this222// data is set up.223// Set ourselves as not valid, and continue.224if (header_size == 0 || num_descriptors == 0) {225m_valid = false;226return;227}228229// Now read in all the descriptors:230// The descriptor looks like:231//232// uint32_t offset233// uint32_t flags234//235// Where offset is either 0 - in which case it is unused, or it is236// the offset of the vtable code from the beginning of the237// descriptor record. Below, we'll convert that into an absolute238// code address, since I don't want to have to compute it over and239// over.240241// Ingest the whole descriptor array:242const lldb::addr_t desc_ptr = m_header_addr + header_size;243const size_t desc_array_size = num_descriptors * descriptor_size;244WritableDataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0'));245uint8_t *dst = (uint8_t *)data_sp->GetBytes();246247DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(),248process_sp->GetAddressByteSize());249bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error);250if (bytes_read != desc_array_size) {251m_valid = false;252return;253}254255// The actual code for the vtables will be laid out consecutively, so I also256// compute the start and end of the whole code block.257258offset = 0;259m_code_start_addr = 0;260m_code_end_addr = 0;261262for (size_t i = 0; i < num_descriptors; i++) {263lldb::addr_t start_offset = offset;264uint32_t voffset = desc_extractor.GetU32(&offset);265uint32_t flags = desc_extractor.GetU32(&offset);266lldb::addr_t code_addr = desc_ptr + start_offset + voffset;267m_descriptors.push_back(VTableDescriptor(flags, code_addr));268269if (m_code_start_addr == 0 || code_addr < m_code_start_addr)270m_code_start_addr = code_addr;271if (code_addr > m_code_end_addr)272m_code_end_addr = code_addr;273274offset = start_offset + descriptor_size;275}276// Finally, a little bird told me that all the vtable code blocks277// are the same size. Let's compute the blocks and if they are all278// the same add the size to the code end address:279lldb::addr_t code_size = 0;280bool all_the_same = true;281for (size_t i = 0; i < num_descriptors - 1; i++) {282lldb::addr_t this_size =283m_descriptors[i + 1].code_start - m_descriptors[i].code_start;284if (code_size == 0)285code_size = this_size;286else {287if (this_size != code_size)288all_the_same = false;289if (this_size > code_size)290code_size = this_size;291}292}293if (all_the_same)294m_code_end_addr += code_size;295}296297bool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::298AddressInRegion(lldb::addr_t addr, uint32_t &flags) {299if (!IsValid())300return false;301302if (addr < m_code_start_addr || addr > m_code_end_addr)303return false;304305std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end();306for (pos = m_descriptors.begin(); pos != end; pos++) {307if (addr <= (*pos).code_start) {308flags = (*pos).flags;309return true;310}311}312return false;313}314315void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump(316Stream &s) {317s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64318" Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n",319m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region);320size_t num_elements = m_descriptors.size();321for (size_t i = 0; i < num_elements; i++) {322s.Indent();323s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n",324m_descriptors[i].code_start, m_descriptors[i].flags);325}326}327328AppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables(329const ProcessSP &process_sp, const ModuleSP &objc_module_sp)330: m_process_wp(), m_trampoline_header(LLDB_INVALID_ADDRESS),331m_trampolines_changed_bp_id(LLDB_INVALID_BREAK_ID),332m_objc_module_sp(objc_module_sp) {333if (process_sp)334m_process_wp = process_sp;335}336337AppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() {338ProcessSP process_sp = GetProcessSP();339if (process_sp) {340if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID)341process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id);342}343}344345bool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() {346if (m_trampoline_header != LLDB_INVALID_ADDRESS)347return true;348349ProcessSP process_sp = GetProcessSP();350if (process_sp) {351Target &target = process_sp->GetTarget();352353if (!m_objc_module_sp) {354for (ModuleSP module_sp : target.GetImages().Modules()) {355if (ObjCLanguageRuntime::Get(*process_sp)356->IsModuleObjCLibrary(module_sp)) {357m_objc_module_sp = module_sp;358break;359}360}361}362363if (m_objc_module_sp) {364ConstString trampoline_name("gdb_objc_trampolines");365const Symbol *trampoline_symbol =366m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name,367eSymbolTypeData);368if (trampoline_symbol != nullptr) {369m_trampoline_header = trampoline_symbol->GetLoadAddress(&target);370if (m_trampoline_header == LLDB_INVALID_ADDRESS)371return false;372373// Next look up the "changed" symbol and set a breakpoint on that...374ConstString changed_name("gdb_objc_trampolines_changed");375const Symbol *changed_symbol =376m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name,377eSymbolTypeCode);378if (changed_symbol != nullptr) {379const Address changed_symbol_addr = changed_symbol->GetAddress();380if (!changed_symbol_addr.IsValid())381return false;382383lldb::addr_t changed_addr =384changed_symbol_addr.GetOpcodeLoadAddress(&target);385if (changed_addr != LLDB_INVALID_ADDRESS) {386BreakpointSP trampolines_changed_bp_sp =387target.CreateBreakpoint(changed_addr, true, false);388if (trampolines_changed_bp_sp) {389m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID();390trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this,391true);392trampolines_changed_bp_sp->SetBreakpointKind(393"objc-trampolines-changed");394return true;395}396}397}398}399}400}401return false;402}403404bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines(405void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,406lldb::user_id_t break_loc_id) {407AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton;408if (vtable_handler->InitializeVTableSymbols()) {409// The Update function is called with the address of an added region. So we410// grab that address, and411// feed it into ReadRegions. Of course, our friend the ABI will get the412// values for us.413ExecutionContext exe_ctx(context->exe_ctx_ref);414Process *process = exe_ctx.GetProcessPtr();415const ABI *abi = process->GetABI().get();416417TypeSystemClangSP scratch_ts_sp =418ScratchTypeSystemClang::GetForTarget(process->GetTarget());419if (!scratch_ts_sp)420return false;421422ValueList argument_values;423Value input_value;424CompilerType clang_void_ptr_type =425scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();426427input_value.SetValueType(Value::ValueType::Scalar);428// input_value.SetContext (Value::eContextTypeClangType,429// clang_void_ptr_type);430input_value.SetCompilerType(clang_void_ptr_type);431argument_values.PushValue(input_value);432433bool success =434abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values);435if (!success)436return false;437438// Now get a pointer value from the zeroth argument.439Status error;440DataExtractor data;441error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data,442nullptr);443lldb::offset_t offset = 0;444lldb::addr_t region_addr = data.GetAddress(&offset);445446if (region_addr != 0)447vtable_handler->ReadRegions(region_addr);448}449return false;450}451452bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() {453// The no argument version reads the start region from the value of454// the gdb_regions_header, and gets started from there.455456m_regions.clear();457if (!InitializeVTableSymbols())458return false;459Status error;460ProcessSP process_sp = GetProcessSP();461if (process_sp) {462lldb::addr_t region_addr =463process_sp->ReadPointerFromMemory(m_trampoline_header, error);464if (error.Success())465return ReadRegions(region_addr);466}467return false;468}469470bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions(471lldb::addr_t region_addr) {472ProcessSP process_sp = GetProcessSP();473if (!process_sp)474return false;475476Log *log = GetLog(LLDBLog::Step);477478// We aren't starting at the trampoline symbol.479InitializeVTableSymbols();480lldb::addr_t next_region = region_addr;481482// Read in the sizes of the headers.483while (next_region != 0) {484m_regions.push_back(VTableRegion(this, next_region));485if (!m_regions.back().IsValid()) {486m_regions.clear();487return false;488}489if (log) {490StreamString s;491m_regions.back().Dump(s);492LLDB_LOGF(log, "Read vtable region: \n%s", s.GetData());493}494495next_region = m_regions.back().GetNextRegionAddr();496}497498return true;499}500501bool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables(502lldb::addr_t addr, uint32_t &flags) {503region_collection::iterator pos, end = m_regions.end();504for (pos = m_regions.begin(); pos != end; pos++) {505if ((*pos).AddressInRegion(addr, flags))506return true;507}508return false;509}510511const AppleObjCTrampolineHandler::DispatchFunction512AppleObjCTrampolineHandler::g_dispatch_functions[] = {513// NAME STRET SUPER SUPER2 FIXUP TYPE514{"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone},515{"objc_msgSend_fixup", false, false, false,516DispatchFunction::eFixUpToFix},517{"objc_msgSend_fixedup", false, false, false,518DispatchFunction::eFixUpFixed},519{"objc_msgSend_stret", true, false, false,520DispatchFunction::eFixUpNone},521{"objc_msgSend_stret_fixup", true, false, false,522DispatchFunction::eFixUpToFix},523{"objc_msgSend_stret_fixedup", true, false, false,524DispatchFunction::eFixUpFixed},525{"objc_msgSend_fpret", false, false, false,526DispatchFunction::eFixUpNone},527{"objc_msgSend_fpret_fixup", false, false, false,528DispatchFunction::eFixUpToFix},529{"objc_msgSend_fpret_fixedup", false, false, false,530DispatchFunction::eFixUpFixed},531{"objc_msgSend_fp2ret", false, false, true,532DispatchFunction::eFixUpNone},533{"objc_msgSend_fp2ret_fixup", false, false, true,534DispatchFunction::eFixUpToFix},535{"objc_msgSend_fp2ret_fixedup", false, false, true,536DispatchFunction::eFixUpFixed},537{"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone},538{"objc_msgSendSuper_stret", true, true, false,539DispatchFunction::eFixUpNone},540{"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone},541{"objc_msgSendSuper2_fixup", false, true, true,542DispatchFunction::eFixUpToFix},543{"objc_msgSendSuper2_fixedup", false, true, true,544DispatchFunction::eFixUpFixed},545{"objc_msgSendSuper2_stret", true, true, true,546DispatchFunction::eFixUpNone},547{"objc_msgSendSuper2_stret_fixup", true, true, true,548DispatchFunction::eFixUpToFix},549{"objc_msgSendSuper2_stret_fixedup", true, true, true,550DispatchFunction::eFixUpFixed},551};552553// This is the table of ObjC "accelerated dispatch" functions. They are a set554// of objc methods that are "seldom overridden" and so the compiler replaces the555// objc_msgSend with a call to one of the dispatch functions. That will check556// whether the method has been overridden, and directly call the Foundation557// implementation if not.558// This table is supposed to be complete. If ones get added in the future, we559// will have to add them to the table.560const char *AppleObjCTrampolineHandler::g_opt_dispatch_names[] = {561"objc_alloc",562"objc_autorelease",563"objc_release",564"objc_retain",565"objc_alloc_init",566"objc_allocWithZone",567"objc_opt_class",568"objc_opt_isKindOfClass",569"objc_opt_new",570"objc_opt_respondsToSelector",571"objc_opt_self",572};573574AppleObjCTrampolineHandler::AppleObjCTrampolineHandler(575const ProcessSP &process_sp, const ModuleSP &objc_module_sp)576: m_process_wp(), m_objc_module_sp(objc_module_sp),577m_impl_fn_addr(LLDB_INVALID_ADDRESS),578m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS),579m_msg_forward_addr(LLDB_INVALID_ADDRESS),580m_msg_forward_stret_addr(LLDB_INVALID_ADDRESS) {581if (process_sp)582m_process_wp = process_sp;583// Look up the known resolution functions:584585ConstString get_impl_name("class_getMethodImplementation");586ConstString get_impl_stret_name("class_getMethodImplementation_stret");587ConstString msg_forward_name("_objc_msgForward");588ConstString msg_forward_stret_name("_objc_msgForward_stret");589590Target *target = process_sp ? &process_sp->GetTarget() : nullptr;591const Symbol *class_getMethodImplementation =592m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name,593eSymbolTypeCode);594const Symbol *class_getMethodImplementation_stret =595m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name,596eSymbolTypeCode);597const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType(598msg_forward_name, eSymbolTypeCode);599const Symbol *msg_forward_stret =600m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name,601eSymbolTypeCode);602603if (class_getMethodImplementation)604m_impl_fn_addr =605class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress(606target);607if (class_getMethodImplementation_stret)608m_impl_stret_fn_addr =609class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress(610target);611if (msg_forward)612m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target);613if (msg_forward_stret)614m_msg_forward_stret_addr =615msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target);616617// FIXME: Do some kind of logging here.618if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) {619// If we can't even find the ordinary get method implementation function,620// then we aren't going to be able to621// step through any method dispatches. Warn to that effect and get out of622// here.623if (process_sp->CanJIT()) {624process_sp->GetTarget().GetDebugger().GetErrorStream().Printf(625"Could not find implementation lookup function \"%s\""626" step in through ObjC method dispatch will not work.\n",627get_impl_name.AsCString());628}629return;630}631632// We will either set the implementation to the _stret or non_stret version,633// so either way it's safe to start filling the m_lookup_..._code here.634m_lookup_implementation_function_code.assign(635g_lookup_implementation_function_common_code);636637if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) {638// It there is no stret return lookup function, assume that it is the same639// as the straight lookup:640m_impl_stret_fn_addr = m_impl_fn_addr;641// Also we will use the version of the lookup code that doesn't rely on the642// stret version of the function.643m_lookup_implementation_function_code.append(644g_lookup_implementation_no_stret_function_code);645} else {646m_lookup_implementation_function_code.append(647g_lookup_implementation_with_stret_function_code);648}649650// Look up the addresses for the objc dispatch functions and cache651// them. For now I'm inspecting the symbol names dynamically to652// figure out how to dispatch to them. If it becomes more653// complicated than this we can turn the g_dispatch_functions char *654// array into a template table, and populate the DispatchFunction655// map from there.656657for (size_t i = 0; i != std::size(g_dispatch_functions); i++) {658ConstString name_const_str(g_dispatch_functions[i].name);659const Symbol *msgSend_symbol =660m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,661eSymbolTypeCode);662if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {663// FIXME: Make g_dispatch_functions static table of664// DispatchFunctions, and have the map be address->index.665// Problem is we also need to lookup the dispatch function. For666// now we could have a side table of stret & non-stret dispatch667// functions. If that's as complex as it gets, we're fine.668669lldb::addr_t sym_addr =670msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);671672m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i));673}674}675676// Similarly, cache the addresses of the "optimized dispatch" function.677for (size_t i = 0; i != std::size(g_opt_dispatch_names); i++) {678ConstString name_const_str(g_opt_dispatch_names[i]);679const Symbol *msgSend_symbol =680m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str,681eSymbolTypeCode);682if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) {683lldb::addr_t sym_addr =684msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target);685686m_opt_dispatch_map.emplace(sym_addr, i);687}688}689690// Build our vtable dispatch handler here:691m_vtables_up =692std::make_unique<AppleObjCVTables>(process_sp, m_objc_module_sp);693if (m_vtables_up)694m_vtables_up->ReadRegions();695}696697lldb::addr_t698AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread,699ValueList &dispatch_values) {700ThreadSP thread_sp(thread.shared_from_this());701ExecutionContext exe_ctx(thread_sp);702Log *log = GetLog(LLDBLog::Step);703704lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;705FunctionCaller *impl_function_caller = nullptr;706707// Scope for mutex locker:708{709std::lock_guard<std::mutex> guard(m_impl_function_mutex);710711// First stage is to make the ClangUtility to hold our injected function:712713if (!m_impl_code) {714if (!m_lookup_implementation_function_code.empty()) {715auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(716m_lookup_implementation_function_code,717g_lookup_implementation_function_name, eLanguageTypeC, exe_ctx);718if (!utility_fn_or_error) {719LLDB_LOG_ERROR(720log, utility_fn_or_error.takeError(),721"Failed to get Utility Function for implementation lookup: {0}.");722return args_addr;723}724m_impl_code = std::move(*utility_fn_or_error);725} else {726LLDB_LOGF(log, "No method lookup implementation code.");727return LLDB_INVALID_ADDRESS;728}729730// Next make the runner function for our implementation utility function.731TypeSystemClangSP scratch_ts_sp = ScratchTypeSystemClang::GetForTarget(732thread.GetProcess()->GetTarget());733if (!scratch_ts_sp)734return LLDB_INVALID_ADDRESS;735736CompilerType clang_void_ptr_type =737scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();738Status error;739740impl_function_caller = m_impl_code->MakeFunctionCaller(741clang_void_ptr_type, dispatch_values, thread_sp, error);742if (error.Fail()) {743LLDB_LOGF(log,744"Error getting function caller for dispatch lookup: \"%s\".",745error.AsCString());746return args_addr;747}748} else {749impl_function_caller = m_impl_code->GetFunctionCaller();750}751}752753// Now write down the argument values for this particular call.754// This looks like it might be a race condition if other threads755// were calling into here, but actually it isn't because we allocate756// a new args structure for this call by passing args_addr =757// LLDB_INVALID_ADDRESS...758759DiagnosticManager diagnostics;760if (!impl_function_caller->WriteFunctionArguments(761exe_ctx, args_addr, dispatch_values, diagnostics)) {762if (log) {763LLDB_LOGF(log, "Error writing function arguments.");764diagnostics.Dump(log);765}766return args_addr;767}768769return args_addr;770}771772const AppleObjCTrampolineHandler::DispatchFunction *773AppleObjCTrampolineHandler::FindDispatchFunction(lldb::addr_t addr) {774MsgsendMap::iterator pos;775pos = m_msgSend_map.find(addr);776if (pos != m_msgSend_map.end()) {777return &g_dispatch_functions[(*pos).second];778}779return nullptr;780}781782void AppleObjCTrampolineHandler::ForEachDispatchFunction(783std::function<void(lldb::addr_t, const DispatchFunction &)> callback) {784for (auto elem : m_msgSend_map) {785callback(elem.first, g_dispatch_functions[elem.second]);786}787}788789ThreadPlanSP790AppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread,791bool stop_others) {792ThreadPlanSP ret_plan_sp;793lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();794795DispatchFunction vtable_dispatch = {"vtable", false, false, false,796DispatchFunction::eFixUpFixed};797// The selector specific stubs are a wrapper for objc_msgSend. They don't get798// passed a SEL, but instead the selector string is encoded in the stub799// name, in the form:800// objc_msgSend$SelectorName801// and the stub figures out the uniqued selector. If we find ourselves in802// one of these stubs, we strip off the selector string and pass that to the803// implementation finder function, which looks up the SEL (you have to do this804// in process) and passes that to the runtime lookup function.805DispatchFunction sel_stub_dispatch = {"sel-specific-stub", false, false,806false, DispatchFunction::eFixUpNone};807808// First step is to see if we're in a selector-specific dispatch stub.809// Those are of the form _objc_msgSend$<SELECTOR>, so see if the current810// function has that name:811Address func_addr;812Target &target = thread.GetProcess()->GetTarget();813llvm::StringRef sym_name;814const DispatchFunction *this_dispatch = nullptr;815816if (target.ResolveLoadAddress(curr_pc, func_addr)) {817Symbol *curr_sym = func_addr.CalculateSymbolContextSymbol();818if (curr_sym)819sym_name = curr_sym->GetName().GetStringRef();820821if (!sym_name.empty() && !sym_name.consume_front("objc_msgSend$"))822sym_name = {};823else824this_dispatch = &sel_stub_dispatch;825}826bool in_selector_stub = !sym_name.empty();827// Second step is to look and see if we are in one of the known ObjC828// dispatch functions. We've already compiled a table of same, so829// consult it.830831if (!in_selector_stub)832this_dispatch = FindDispatchFunction(curr_pc);833834// Next check to see if we are in a vtable region:835836if (!this_dispatch && m_vtables_up) {837uint32_t flags;838if (m_vtables_up->IsAddressInVTables(curr_pc, flags)) {839vtable_dispatch.stret_return =840(flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) ==841AppleObjCVTables::eOBJC_TRAMPOLINE_STRET;842this_dispatch = &vtable_dispatch;843}844}845846// Since we set this_dispatch in both the vtable & sel specific stub cases847// this if will be used for all three of those cases.848if (this_dispatch) {849Log *log = GetLog(LLDBLog::Step);850851// We are decoding a method dispatch. First job is to pull the852// arguments out. If we are in a regular stub, we get self & selector,853// but if we are in a selector-specific stub, we'll have to get that from854// the string sym_name.855856lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);857858const ABI *abi = nullptr;859ProcessSP process_sp(thread.CalculateProcess());860if (process_sp)861abi = process_sp->GetABI().get();862if (abi == nullptr)863return ret_plan_sp;864865TargetSP target_sp(thread.CalculateTarget());866867TypeSystemClangSP scratch_ts_sp =868ScratchTypeSystemClang::GetForTarget(*target_sp);869if (!scratch_ts_sp)870return ret_plan_sp;871872ValueList argument_values;873Value void_ptr_value;874CompilerType clang_void_ptr_type =875scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();876void_ptr_value.SetValueType(Value::ValueType::Scalar);877// void_ptr_value.SetContext (Value::eContextTypeClangType,878// clang_void_ptr_type);879void_ptr_value.SetCompilerType(clang_void_ptr_type);880881int obj_index;882int sel_index;883884// If this is a selector-specific stub then just push one value, 'cause885// we only get the object.886// If this is a struct return dispatch, then the first argument is887// the return struct pointer, and the object is the second, and888// the selector is the third.889// Otherwise the object is the first and the selector the second.890if (in_selector_stub) {891obj_index = 0;892sel_index = 1;893argument_values.PushValue(void_ptr_value);894} else if (this_dispatch->stret_return) {895obj_index = 1;896sel_index = 2;897argument_values.PushValue(void_ptr_value);898argument_values.PushValue(void_ptr_value);899argument_values.PushValue(void_ptr_value);900} else {901obj_index = 0;902sel_index = 1;903argument_values.PushValue(void_ptr_value);904argument_values.PushValue(void_ptr_value);905}906907bool success = abi->GetArgumentValues(thread, argument_values);908if (!success)909return ret_plan_sp;910911lldb::addr_t obj_addr =912argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong();913if (obj_addr == 0x0) {914LLDB_LOGF(915log,916"Asked to step to dispatch to nil object, returning empty plan.");917return ret_plan_sp;918}919920ExecutionContext exe_ctx(thread.shared_from_this());921// isa_addr will store the class pointer that the method is being922// dispatched to - so either the class directly or the super class923// if this is one of the objc_msgSendSuper flavors. That's mostly924// used to look up the class/selector pair in our cache.925926lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS;927lldb::addr_t sel_addr = LLDB_INVALID_ADDRESS;928// If we are not in a selector stub, get the sel address from the arguments.929if (!in_selector_stub)930sel_addr =931argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong();932933// Figure out the class this is being dispatched to and see if934// we've already cached this method call, If so we can push a935// run-to-address plan directly. Otherwise we have to figure out936// where the implementation lives.937938if (this_dispatch->is_super) {939if (this_dispatch->is_super2) {940// In the objc_msgSendSuper2 case, we don't get the object941// directly, we get a structure containing the object and the942// class to which the super message is being sent. So we need943// to dig the super out of the class and use that.944945Value super_value(*(argument_values.GetValueAtIndex(obj_index)));946super_value.GetScalar() += process_sp->GetAddressByteSize();947super_value.ResolveValue(&exe_ctx);948949if (super_value.GetScalar().IsValid()) {950951// isa_value now holds the class pointer. The second word of the952// class pointer is the super-class pointer:953super_value.GetScalar() += process_sp->GetAddressByteSize();954super_value.ResolveValue(&exe_ctx);955if (super_value.GetScalar().IsValid())956isa_addr = super_value.GetScalar().ULongLong();957else {958LLDB_LOGF(log, "Failed to extract the super class value from the "959"class in objc_super.");960}961} else {962LLDB_LOGF(log, "Failed to extract the class value from objc_super.");963}964} else {965// In the objc_msgSendSuper case, we don't get the object966// directly, we get a two element structure containing the967// object and the super class to which the super message is968// being sent. So the class we want is the second element of969// this structure.970971Value super_value(*(argument_values.GetValueAtIndex(obj_index)));972super_value.GetScalar() += process_sp->GetAddressByteSize();973super_value.ResolveValue(&exe_ctx);974975if (super_value.GetScalar().IsValid()) {976isa_addr = super_value.GetScalar().ULongLong();977} else {978LLDB_LOGF(log, "Failed to extract the class value from objc_super.");979}980}981} else {982// In the direct dispatch case, the object->isa is the class pointer we983// want.984985// This is a little cheesy, but since object->isa is the first field,986// making the object value a load address value and resolving it will get987// the pointer sized data pointed to by that value...988989// Note, it isn't a fatal error not to be able to get the990// address from the object, since this might be a "tagged991// pointer" which isn't a real object, but rather some word992// length encoded dingus.993994Value isa_value(*(argument_values.GetValueAtIndex(obj_index)));995996isa_value.SetValueType(Value::ValueType::LoadAddress);997isa_value.ResolveValue(&exe_ctx);998if (isa_value.GetScalar().IsValid()) {999isa_addr = isa_value.GetScalar().ULongLong();1000} else {1001LLDB_LOGF(log, "Failed to extract the isa value from object.");1002}1003}10041005// Okay, we've got the address of the class for which we're resolving this,1006// let's see if it's in our cache:1007lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS;1008// If this is a regular dispatch, look up the sel in our addr to sel cache:1009if (isa_addr != LLDB_INVALID_ADDRESS) {1010ObjCLanguageRuntime *objc_runtime =1011ObjCLanguageRuntime::Get(*thread.GetProcess());1012assert(objc_runtime != nullptr);1013if (!in_selector_stub) {1014LLDB_LOG(log, "Resolving call for class - {0} and selector - {1}",1015isa_addr, sel_addr);1016impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr);1017} else {1018LLDB_LOG(log, "Resolving call for class - {0} and selector - {1}",1019isa_addr, sym_name);1020impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sym_name);1021}1022}1023// If it is a selector-specific stub dispatch, look in the string cache:10241025if (impl_addr != LLDB_INVALID_ADDRESS) {1026// Yup, it was in the cache, so we can run to that address directly.10271028LLDB_LOGF(log, "Found implementation address in cache: 0x%" PRIx64,1029impl_addr);10301031ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, impl_addr,1032stop_others);1033} else {1034// We haven't seen this class/selector pair yet. Look it up.1035StreamString errors;1036Address impl_code_address;10371038ValueList dispatch_values;10391040// We've will inject a little function in the target that takes the1041// object, selector/selector string and some flags,1042// and figures out the implementation. Looks like:1043// void *__lldb_objc_find_implementation_for_selector (void *object,1044// void *sel,1045// int1046// is_str_ptr,1047// int is_stret,1048// int is_super,1049// int is_super2,1050// int is_fixup,1051// int is_fixed,1052// int debug)1053// If we don't have an actual SEL, but rather a string version of the1054// selector WE injected, set is_str_ptr to true, and sel to the address1055// of the string.1056// So set up the arguments for that call.10571058dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index)));1059lldb::addr_t sel_str_addr = LLDB_INVALID_ADDRESS;1060if (!in_selector_stub) {1061// If we don't have a selector string, push the selector from arguments.1062dispatch_values.PushValue(1063*(argument_values.GetValueAtIndex(sel_index)));1064} else {1065// Otherwise, inject the string into the target, and push that value for1066// the sel argument.1067Status error;1068sel_str_addr = process_sp->AllocateMemory(1069sym_name.size() + 1, ePermissionsReadable | ePermissionsWritable,1070error);1071if (sel_str_addr == LLDB_INVALID_ADDRESS || error.Fail()) {1072LLDB_LOG(log,1073"Could not allocate memory for selector string {0}: {1}",1074sym_name, error);1075return ret_plan_sp;1076}1077process_sp->WriteMemory(sel_str_addr, sym_name.str().c_str(),1078sym_name.size() + 1, error);1079if (error.Fail()) {1080LLDB_LOG(log, "Could not write string to address {0}", sel_str_addr);1081return ret_plan_sp;1082}1083Value sel_ptr_value(void_ptr_value);1084sel_ptr_value.GetScalar() = sel_str_addr;1085dispatch_values.PushValue(sel_ptr_value);1086}10871088Value flag_value;1089CompilerType clang_int_type =1090scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(1091lldb::eEncodingSint, 32);1092flag_value.SetValueType(Value::ValueType::Scalar);1093// flag_value.SetContext (Value::eContextTypeClangType, clang_int_type);1094flag_value.SetCompilerType(clang_int_type);10951096if (in_selector_stub)1097flag_value.GetScalar() = 1;1098else1099flag_value.GetScalar() = 0;1100dispatch_values.PushValue(flag_value);11011102if (this_dispatch->stret_return)1103flag_value.GetScalar() = 1;1104else1105flag_value.GetScalar() = 0;1106dispatch_values.PushValue(flag_value);11071108if (this_dispatch->is_super)1109flag_value.GetScalar() = 1;1110else1111flag_value.GetScalar() = 0;1112dispatch_values.PushValue(flag_value);11131114if (this_dispatch->is_super2)1115flag_value.GetScalar() = 1;1116else1117flag_value.GetScalar() = 0;1118dispatch_values.PushValue(flag_value);11191120switch (this_dispatch->fixedup) {1121case DispatchFunction::eFixUpNone:1122flag_value.GetScalar() = 0;1123dispatch_values.PushValue(flag_value);1124dispatch_values.PushValue(flag_value);1125break;1126case DispatchFunction::eFixUpFixed:1127flag_value.GetScalar() = 1;1128dispatch_values.PushValue(flag_value);1129flag_value.GetScalar() = 1;1130dispatch_values.PushValue(flag_value);1131break;1132case DispatchFunction::eFixUpToFix:1133flag_value.GetScalar() = 1;1134dispatch_values.PushValue(flag_value);1135flag_value.GetScalar() = 0;1136dispatch_values.PushValue(flag_value);1137break;1138}1139if (log && log->GetVerbose())1140flag_value.GetScalar() = 1;1141else1142flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done.1143dispatch_values.PushValue(flag_value);11441145ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughObjCTrampoline>(1146thread, *this, dispatch_values, isa_addr, sel_addr, sel_str_addr,1147sym_name);1148if (log) {1149StreamString s;1150ret_plan_sp->GetDescription(&s, eDescriptionLevelFull);1151LLDB_LOGF(log, "Using ObjC step plan: %s.\n", s.GetData());1152}1153}1154}11551156// Finally, check if we have hit an "optimized dispatch" function. This will1157// either directly call the base implementation or dispatch an objc_msgSend1158// if the method has been overridden. So we just do a "step in/step out",1159// setting a breakpoint on objc_msgSend, and if we hit the msgSend, we1160// will automatically step in again. That's the job of the1161// AppleThreadPlanStepThroughDirectDispatch.1162if (!this_dispatch && !ret_plan_sp) {1163MsgsendMap::iterator pos;1164pos = m_opt_dispatch_map.find(curr_pc);1165if (pos != m_opt_dispatch_map.end()) {1166const char *opt_name = g_opt_dispatch_names[(*pos).second];1167ret_plan_sp = std::make_shared<AppleThreadPlanStepThroughDirectDispatch>(1168thread, *this, opt_name);1169}1170}11711172return ret_plan_sp;1173}11741175FunctionCaller *1176AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() {1177return m_impl_code->GetFunctionCaller();1178}117911801181