網站首頁 編程語言 正文
objc_msgSend
在iOS中調用方法其實就是在給對象發送某條消息。消息的發送在編譯的時候編譯器就會把方法轉 換為objc_msgSend這個函數。objc_msgSend有倆個隱式的參數,消息的接收者和消息的方法 名。objc_msgSend這個函數就能夠通過這倆個隱式的參數去找到方法具體的實現。如果消息的接 收者是實例對象,isa就指向類對象,后再通過第二個參數方法名,去類對象里面找對應的方法實 現。如果消息的接收者是類對象,isa就指向元類,就會去元類里面找對應的方法實現。
通過 clang -rewrite-objc main.m 編譯main文件生成main.cpp,可以看到ocmain.m被編譯成cpp文件后的樣子:
int main(int argc, const char * argv[]) {
@autoreleasepool {
LGPerson *p = [LGPerson alloc];
[p study];
[p happy];
}
return NSApplicationMain(argc, argv);
}
編譯cpp后
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
LGPerson *p = ((LGPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("LGPerson"), sel_registerName("alloc"));
((void (*)(id, SEL))(void *)objc_msgSend)((id)p, sel_registerName("study"));
((void (*)(id, SEL))(void *)objc_msgSend)((id)p, sel_registerName("happy"));
}
return NSApplicationMain(argc, argv);
}
由此可見 alloc study,happy都被轉換成objc_msgSend ,并帶兩個參數,消息的接受者,消息的方法名,手動調用objc_msgSend 需要導入 #import
objc_msgSendSuper
發送消息到父類(使用super關鍵字),消息會使用objc_msgSendSuper發送。 super調用方法和self調用方法的區別就在于去找方法的時候出發點不一樣而已。self會從當前類開 始去找,而super會從當前類的父類開始去找。
通過 clang -rewrite-objc LGTeacher.m 編譯LGTeacher文件生成LGTeacher.cpp,可以看到ocmain.m被編譯成cpp文件后的樣子:
-(instancetype)init {
if (self = [super init]) {
NSLog(@"%@",[self class]);
NSLog(@"%@",[super class]);
}
return self;
}
static instancetype _I_LGTeacher_init(LGTeacher * self, SEL _cmd) {
if (self = ((LGTeacher *(*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LGTeacher"))}, sel_registerName("init"))) {
NSLog((NSString *)&__NSConstantStringImpl__var_folders_64_v4jdthx95753k1gbfyy30w0w0000gn_T_LGTeacher_cbd05b_mi_0,((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("class")));
NSLog((NSString *)&__NSConstantStringImpl__var_folders_64_v4jdthx95753k1gbfyy30w0w0000gn_T_LGTeacher_cbd05b_mi_1,((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LGTeacher"))}, sel_registerName("class")));
}
return self;
}
由此可見通過super調用是執行了objc_msgSendSuper,并且攜帶了三個參數,消息的接受者,消息查找的超類,方法名稱。
手動實現[super study] 的調用
- (void)study {
// [super study];
struct objc_super lg_objc_super;
lg_objc_super.receiver = self;
lg_objc_super.super_class = LGPerson.class;
void* (*objc_msgSendSuperTyped)(struct objc_super *self,SEL _cmd) = (void *)objc_msgSendSuper;
objc_msgSendSuperTyped(&lg_objc_super,@selector(study));
}
官方文檔關于objc_msgSend和objc_msgSuperSend描述
When it encounters a method call, the compiler generates a call to one of the functions?objc_msgSend
,?objc_msgSend_stret
,?objc_msgSendSuper
, or?objc_msgSendSuper_stret
. Messages sent to an object’s superclass (using the?super
?keyword) are sent using?objc_msgSendSuper
; other messages are sent using?objc_msgSend
. Methods that have data structures as return values are sent using?objc_msgSendSuper_stret
?and?objc_msgSend_stret
.
翻譯:當遇到方法調用時,編譯器生成對objc_msgSend、objc_msgsend_street、objc_msgSendSuper或objc_msgsendsuper_street函數之一的調用。發送到對象的超類(使用super關鍵字)的消息使用objc_msgSendSuper發送;其他消息使用objc_msgSend發送。將數據結構作為返回值的方法使用objc_msgsendsuper_street和objc_msgsend_street發送。
從源碼 objc-msg-arm64可以看到objc_msgSend是基于匯編實現,匯編實現的有點是更快,勉去局部變量的拷貝操作。
//進入objc_msgSend流程
ENTRY _objc_msgSend
//流程開始,無需frame
UNWIND _objc_msgSend, NoFrame
//判斷p0(消息接受者)是否存在,不存在則重新開始執行objc_msgSend
cmp p0, #0 // nil check and tagged pointer check
//如果支持小對象類型。返回小對象或空
#if SUPPORT_TAGGED_POINTERS
//b是進行跳轉,b.le是小于判斷,也就是小于的時候LNilOrTagged
b.le LNilOrTagged // (MSB tagged pointer looks negative)
#else
//等于,如果不支持小對象,就LReturnZero
b.eq LReturnZero
#endif
//通過p13取isa
ldr p13, [x0] // p13 = isa
//通過isa取class并保存到p16寄存器中
GetClassFromIsa_p16 p13, 1, x0 // p16 = class
//LGetIsaDone是一個入口
LGetIsaDone:
// calls imp or objc_msgSend_uncached
//進入到緩存查找或者沒有緩存查找方法的流程
CacheLookup NORMAL, _objc_msgSend, __objc_msgSend_uncached
#if SUPPORT_TAGGED_POINTERS
LNilOrTagged:
// nil check判空處理,直接退出
b.eq LReturnZero // nil check
GetTaggedClass
b LGetIsaDone
// SUPPORT_TAGGED_POINTERS
#endif
消息的快速查找流程
1.判斷receiver(消息的接受者)是否存在 2.receiver -> isa -> class 3.class內存平移 -> cache
4.cache -> buckets
5.遍歷buckets -> bucket(sel,imp)對比sel 6.如果bucket(sel,imp)對比sel 相等 -->cacheHit-->調用imp 7.如果cache里面沒有找到對應的sel --> _objc_msgSend_uncached
消息的慢速查找流程
lookUpImpOrForward -- 先找當前類的methodList -- superClass的cache -- superClass的 methodList -- 直到superClass為nil。
objc_runtime_new sourse源碼文件遍歷發查找,
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
if (slowpath(!cls->isInitialized())) {
// The first message sent to a class is often +new or +alloc, or +self
// which goes through objc_opt_* or various optimized entry points.
//
// However, the class isn't realized/initialized yet at this point,
// and the optimized entry points fall down through objc_msgSend,
// which ends up here.
//
// We really want to avoid caching these, as it can cause IMP caches
// to be made with a single entry forever.
//
// Note that this check is racy as several threads might try to
// message a given class for the first time at the same time,
// in which case we might cache anyway.
behavior |= LOOKUP_NOCACHE;
}
// runtimeLock is held during isRealized and isInitialized checking
// to prevent races against concurrent realization.
// runtimeLock is held during method search to make
// method-lookup + cache-fill atomic with respect to method addition.
// Otherwise, a category could be added but ignored indefinitely because
// the cache was re-filled with the old value after the cache flush on
// behalf of the category.
runtimeLock.lock();
// We don't want people to be able to craft a binary blob that looks like
// a class but really isn't one and do a CFI attack.
//
// To make these harder we want to make sure this is a class that was
// either built into the binary or legitimately registered through
// objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
checkIsKnownClass(cls);
cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
// runtimeLock may have been dropped but is now locked again
runtimeLock.assertLocked();
curClass = cls;
// The code used to lookup the class's cache again right after
// we take the lock but for the vast majority of the cases
// evidence shows this is a miss most of the time, hence a time loss.
//
// The only codepath calling into this without having performed some
// kind of cache lookup is class_getInstanceMethod().
for (unsigned attempts = unreasonableClassCount();;) {
if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
imp = cache_getImp(curClass, sel);
if (imp) goto done_unlock;
curClass = curClass->cache.preoptFallbackClass();
#endif
} else {
// curClass method list.
method_t *meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp(false);
goto done;
}
if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;
break;
}
}
// Halt if there is a cycle in the superclass chain.
if (slowpath(--attempts == 0)) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (slowpath(imp == forward_imp)) {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
if (fastpath(imp)) {
// Found the method in a superclass. Cache it in this class.
goto done;
}
}
// No implementation found. Try method resolver once.
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
cls = cls->cache.preoptFallbackClass();
}
#endif
log_and_fill_cache(cls, imp, sel, inst, curClass);
}
done_unlock:
runtimeLock.unlock();
if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
return nil;
}
return imp;
}
?? 當前類的方法列表查找, method_t *meth = getMethodNoSuper_nolock(curClass, sel);方法跟蹤到調用le method_t *m = search_method_list_inline(*mlists, sel);
ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
int methodListIsFixedUp = mlist->isFixedUp();
int methodListHasExpectedSize = mlist->isExpectedSize();
if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
return findMethodInSortedMethodList(sel, mlist);
} else {
// Linear search of unsorted method list
if (auto *m = findMethodInUnsortedMethodList(sel, mlist))
return m;
}
#if DEBUG
// sanity-check negative results
if (mlist->isFixedUp()) {
for (auto& meth : *mlist) {
if (meth.name() == sel) {
_objc_fatal("linear search worked when binary search did not");
}
}
}
#endif
return nil;
}
ALWAYS_INLINE static method_t *
findMethodInUnsortedMethodList(SEL key, const method_list_t *list)
{
if (list->isSmallList()) {
if (CONFIG_SHARED_CACHE_RELATIVE_DIRECT_SELECTORS && objc::inSharedCache((uintptr_t)list)) {
return findMethodInUnsortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSEL(); });
} else {
return findMethodInUnsortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSELRef(); });
}
} else {
return findMethodInUnsortedMethodList(key, list, [](method_t &m) { return m.big().name; });
}
}
當前類查找,進行二分查找 ?
ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName)
{
ASSERT(list);
auto first = list->begin();
auto base = first;
decltype(first) probe;
uintptr_t keyValue = (uintptr_t)key;
uint32_t count;
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1);
uintptr_t probeValue = (uintptr_t)getName(probe);
if (keyValue == probeValue) {
// `probe` is a match.
// Rewind looking for the *first* occurrence of this value.
// This is required for correct category overrides.
while (probe > first && keyValue == (uintptr_t)getName((probe - 1))) {
probe--;
}
return &*probe;
}
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
原文鏈接:https://blog.csdn.net/wywinstonwy/article/details/124468132
- 上一篇:Android水波紋效果
- 下一篇:在 Dart 中更好地使用類和 Mixin
相關推薦
- 2022-08-07 Android?無障礙服務?performAction?調用過程分析_Android
- 2022-12-23 Kubernetes應用配置管理創建使用詳解_云其它
- 2023-07-25 使用POI導出Excel
- 2022-07-23 C語言詳解用char實現大小寫字母的轉換_C 語言
- 2022-08-18 nginx之queue的具體使用_nginx
- 2022-07-14 Android自定義相機、預覽區域裁剪_Android
- 2022-07-03 python爬蟲lxml庫解析xpath網頁過程示例_python
- 2022-08-07 QT實戰之打開最近文檔功能的實現_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支