RuntimeiOS 收藏篇

谈谈 OC 属性修饰符的本质是什么!

2018-09-27  本文已影响24人  丿行随心动

属性修饰符的本质


示例代码
注: 结合 runtime 源码,利用汇编反推出每一个修饰符的本质
1.使用 lldb 为每一个属性的 set 方法下断点
2.分析调试汇编代码,找到真正的操作函数
3.去 runtime 源码中找到对应的源码

@interface ViewController ()
@property (assign) NSInteger assignProperty;
@property (copy)   NSString *copytext;
@property (strong) NSObject *strongProperty;
@property (weak)   NSObject *weakProperty;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self test];
}
- (void)test {
    NSObject *obj = [NSObject new];
    self.assignProperty = 100;
    self.copytext = @"text";
    self.strongProperty = obj;
    self.weakProperty = obj;
}
@end

assign 修饰符

Demo`-[ViewController setAssignProperty:]:
    01. 0x102f4def8 <+0>:  sub    sp, sp, #0x20             ; =0x20 
    // 取出指向 _assignProperty 成员相对偏移量的指针
    02. 0x102f4defc <+4>:  adrp   x8, 4
    03. 0x102f4df00 <+8>:  add    x8, x8, #0x328            ; =0x328 
   
    04. 0x102f4df04 <+12>: str    x0, [sp, #0x18]
    05. 0x102f4df08 <+16>: str    x1, [sp, #0x10]
    06. 0x102f4df0c <+20>: str    x2, [sp, #0x8]
    07. 0x102f4df10 <+24>: ldr    x0, [sp, #0x8]
    08. 0x102f4df14 <+28>: ldr    x1, [sp, #0x18]
    // 取出 _assignProperty 成员相对偏移量(ldrsw 读取一个字(2个byte)的内存数据)
    09. 0x102f4df18 <+32>: ldrsw  x8, [x8]
    // 计算出 _assignProperty 的内存地址
    10. 0x102f4df1c <+36>: add    x8, x1, x8
    // 赋值
    11. 0x102f4df20 <+40>: str    x0, [x8]
    12. 0x102f4df24 <+44>: add    sp, sp, #0x20             ; =0x20 
    13. 0x102f4df28 <+48>: ret    
结论: assign 修饰符没有做任何操作,本质就是得到内存空间,直接赋值

copy 修饰符

Demo`-[ViewController setCopytext:]:
    0x100f79f68 <+0>:  sub    sp, sp, #0x30             ; =0x30 
    0x100f79f6c <+4>:  stp    x29, x30, [sp, #0x20]
    0x100f79f70 <+8>:  add    x29, sp, #0x20            ; =0x20 
    0x100f79f74 <+12>: adrp   x8, 4
    0x100f79f78 <+16>: add    x8, x8, #0x32c            ; =0x32c 
    0x100f79f7c <+20>: stur   x0, [x29, #-0x8]
    0x100f79f80 <+24>: str    x1, [sp, #0x10]
    0x100f79f84 <+28>: str    x2, [sp, #0x8]
    0x100f79f88 <+32>: ldr    x1, [sp, #0x10]
    0x100f79f8c <+36>: ldur   x0, [x29, #-0x8]
    0x100f79f90 <+40>: ldrsw  x3, [x8]
    0x100f79f94 <+44>: ldr    x8, [sp, #0x8]
    0x100f79f98 <+48>: mov    x2, x8
    0x100f79f9c <+52>: bl     0x100f7a8c4               ; symbol stub for: objc_setProperty_nonatomic_copy
    0x100f79fa0 <+56>: ldp    x29, x30, [sp, #0x20]
    0x100f79fa4 <+60>: add    sp, sp, #0x30             ; =0x30 
    0x100f79fa8 <+64>: ret 
结论: 第14行可以明显看出,copy 修饰符下,编译器为你调用了 objc_setProperty_nonatomic_copy, 
    幸运的是它确实就是 runtime 中的源码
void objc_setProperty_nonatomic_copy(id self, SEL _cmd, id newValue, ptrdiff_t offset)
{
    reallySetProperty(self, _cmd, newValue, offset, false, true, false);
}
static inline void reallySetProperty(id self, 
                                    SEL _cmd, 
                                    id newValue,
                                    ptrdiff_t offset,
                                    bool atomic, 
                                    bool copy, 
                                    bool mutableCopy)
{
    if (offset == 0) {
        object_setClass(self, newValue);
        return;
    }
    id oldValue;
    id *slot = (id*) ((char*)self + offset);
    if (copy) {
        newValue = [newValue copyWithZone:nil];
    } else if (mutableCopy) {
        newValue = [newValue mutableCopyWithZone:nil];
    } else {
        if (*slot == newValue) return;
        newValue = objc_retain(newValue);
    }
    if (!atomic) {
        oldValue = *slot;
        *slot = newValue;
    } else {
        spinlock_t& slotlock = PropertyLocks[slot];
        slotlock.lock();
        oldValue = *slot;
        *slot = newValue;        
        slotlock.unlock();
    }
    objc_release(oldValue);
}
reallySetProperty 函数分析:
    1. 检查成员偏移量是否合法
    2. 计算出成员的地址
    3. 检查成员是否需要深浅拷贝
    4. 检查是否需要原子锁操作
    5. 取出 oldValue, 赋值 newValue
    6. release oldValue
结论: copy 的本质就是编译器,为你调用 objc_setProperty_nonatomic_copy 函数

atomic 修饰符

由 copy 的本质, 我们可以看出实质是调用了 reallySetProperty 做了一系列操作,
所以这里就不再进行汇编分析,有兴趣的可以自己去实践

strong 修饰符

Demo`-[ViewController setStrongProperty:]:
    0x102271fd4 <+0>:  sub    sp, sp, #0x30             ; =0x30 
    0x102271fd8 <+4>:  stp    x29, x30, [sp, #0x20]
    0x102271fdc <+8>:  add    x29, sp, #0x20            ; =0x20 
    0x102271fe0 <+12>: adrp   x8, 4
    0x102271fe4 <+16>: add    x8, x8, #0x330            ; =0x330 
    0x102271fe8 <+20>: stur   x0, [x29, #-0x8]
    0x102271fec <+24>: str    x1, [sp, #0x10]
    0x102271ff0 <+28>: str    x2, [sp, #0x8]
    0x102271ff4 <+32>: ldr    x0, [sp, #0x8]
    0x102271ff8 <+36>: ldur   x1, [x29, #-0x8]
    0x102271ffc <+40>: ldrsw  x8, [x8]
    0x102272000 <+44>: add    x8, x1, x8
    0x102272004 <+48>: str    x0, [sp]
    0x102272008 <+52>: mov    x0, x8
    0x10227200c <+56>: ldr    x1, [sp]
    0x102272010 <+60>: bl     0x1022728cc               ; symbol stub for: objc_storeStrong
    0x102272014 <+64>: ldp    x29, x30, [sp, #0x20]
    0x102272018 <+68>: add    sp, sp, #0x30             ; =0x30 
    0x10227201c <+72>: ret   
结论: strong 修饰符下,编译器为你调用了 objc_storeStrong 函数, 
    它也是一个 runtime 源码中的函数
void objc_storeStrong(id *location, id obj)
{
    id prev = *location;
    if (obj == prev) {
        return;
    }
    objc_retain(obj);
    *location = obj;
    objc_release(prev);
}
objc_storeStrong 函数分析:
    1. 取出 oldValue, 对比 newValue
    2. retain newValue
    3. 赋值
    4. release oldValue
结论: 以上可以看出 strong 修饰的成员变量, 本质是一个对应类型二级指针, 
    且编译器为我们调用了 objc_storeStrong 函数来操作成员变量

weak 修饰符

Demo`-[ViewController setWeakProperty:]:
    0x102272054 <+0>:  sub    sp, sp, #0x40             ; =0x40 
    0x102272058 <+4>:  stp    x29, x30, [sp, #0x30]
    0x10227205c <+8>:  add    x29, sp, #0x30            ; =0x30 
    0x102272060 <+12>: adrp   x8, 3
    0x102272064 <+16>: add    x8, x8, #0x334            ; =0x334 
    0x102272068 <+20>: stur   x0, [x29, #-0x8]
    0x10227206c <+24>: stur   x1, [x29, #-0x10]
    0x102272070 <+28>: str    x2, [sp, #0x18]
    0x102272074 <+32>: ldr    x0, [sp, #0x18]
    0x102272078 <+36>: ldur   x1, [x29, #-0x8]
    0x10227207c <+40>: ldrsw  x8, [x8]
    0x102272080 <+44>: add    x8, x1, x8
    0x102272084 <+48>: str    x0, [sp, #0x10]
    0x102272088 <+52>: mov    x0, x8
    0x10227208c <+56>: ldr    x1, [sp, #0x10]
    0x102272090 <+60>: bl     0x1022728d8               ; symbol stub for: objc_storeWeak
    0x102272094 <+64>: str    x0, [sp, #0x8]
    0x102272098 <+68>: ldp    x29, x30, [sp, #0x30]
    0x10227209c <+72>: add    sp, sp, #0x40             ; =0x40 
    0x1022720a0 <+76>: ret  
结论: weak 修饰符下,编译器为你调用了 objc_storeWeak 函数, 它也是一个 runtime 源码中的函数
id objc_storeWeak(id *location, id newObj)
{
    return storeWeak<DoHaveOld, DoHaveNew, DoCrashIfDeallocating>
        (location, (objc_object *)newObj);
}
static id storeWeak(id *location, objc_object *newObj)
{
    // 检查参数
    assert(haveOld  ||  haveNew);
    if (!haveNew) assert(newObj == nil);
    Class previouslyInitializedClass = nil;
    id oldObj;
    SideTable *oldTable;
    SideTable *newTable;
    // 检查新值和旧值
 retry:
    if (haveOld) {
        // 取出旧值
        oldObj = *location;
        // 取出旧值所在的 hashTable
        oldTable = &SideTables()[oldObj];
    } else {
        oldTable = nil;
    }
    if (haveNew) {
        // 分配新值所在的 hashTable
        newTable = &SideTables()[newObj];
    } else {
        newTable = nil;
    }
    // 对 hashTable 加锁
    SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);
    // 检查旧值与 hashTable 中取出的值是否对应(hashTable 碰撞容错机制)
    if (haveOld  &&  *location != oldObj) {
        SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
        goto retry;
    }
    if (haveNew  &&  newObj) {
        // 取出新值的类对象
        Class cls = newObj->getIsa();
        // 检查类对象是否被初始化
        if (cls != previouslyInitializedClass  &&  
            !((objc_class *)cls)->isInitialized()) 
        {
            SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
            _class_initialize(_class_getNonMetaClass(cls, (id)newObj));
            previouslyInitializedClass = cls;
            goto retry;
        }
    }
    if (haveOld) {
        // 从 hashTable 中移除旧值
        weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
    }
    if (haveNew) {
        // 向 hashTable 中插入新值
        newObj = (objc_object *)
            weak_register_no_lock(&newTable->weak_table, 
                                    (id)newObj,
                                    location, 
                                    crashIfDeallocating);
        if (newObj  &&  !newObj->isTaggedPointer()) {
            newObj->setWeaklyReferenced_nolock();
        }
        // 给成员变量赋新值
        *location = (id)newObj;
    }
    else {
        // No new value. The storage is not changed.
    }
    // 为 hashTable 开锁
    SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
    return (id)newObj;
}
结论: 综上所述,我们可以得出,weak 修饰的成员变量实际也是一个对应类型的二级指针,
    且编译器为我们调用了 objc_storeWeak 函数,来操作成员变量和对应的hashTable, 
    接下来将继续深入 weakTable 实现原理

weakTable 实现原理

alignas(StripedMap<SideTable>) static uint8_t 
    SideTableBuf[sizeof(StripedMap<SideTable>)];
static void SideTableInit() {
    new (SideTableBuf) StripedMap<SideTable>();
}
static StripedMap<SideTable>& SideTables() {
    return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
}
注: weakTable 是由一个静态的 SideTableBuf 对象所维护,其类型为 <StripedMap<SideTable> *>
template<typename T>
class StripedMap {
    enum { CacheLineSize = 64 };
#if TARGET_OS_EMBEDDED
    enum { StripeCount = 8 };
#else
    enum { StripeCount = 64 };
#endif
    struct PaddedT {
        T value alignas(CacheLineSize);
    };
    PaddedT array[StripeCount];
    static unsigned int indexForPointer(const void *p) {
        uintptr_t addr = reinterpret_cast<uintptr_t>(p);
        return ((addr >> 4) ^ (addr >> 9)) % StripeCount;
    }
 public:
    T& operator[] (const void *p) { 
        return array[indexForPointer(p)].value; 
    }
    const T& operator[] (const void *p) const { 
        return const_cast<StripedMap<T>>(this)[p]; 
    }
    .
    .
    .
}
注: StripeMap 是一个散列表,其成员 PaddedT array[StripeCount](这里分为64个桶),
    PaddedT 内部维护着 SideTable 类型的对象,
    函数 static unsigned int indexForPointer(const void *p) 将 weak 对象指针的 hash % 64 分发入桶.
enum HaveOld { DontHaveOld = false, DoHaveOld = true };
enum HaveNew { DontHaveNew = false, DoHaveNew = true };
struct SideTable {
    spinlock_t slock;
    RefcountMap refcnts;
    weak_table_t weak_table;
    SideTable() {
        memset(&weak_table, 0, sizeof(weak_table));
    }
    ~SideTable() {
        _objc_fatal("Do not delete SideTable.");
    }
    void lock() { slock.lock(); }
    void unlock() { slock.unlock(); }
    void forceReset() { slock.forceReset(); }
    // Address-ordered lock discipline for a pair of side tables.
    template<HaveOld, HaveNew>
    static void lockTwo(SideTable *lock1, SideTable *lock2);
    template<HaveOld, HaveNew>
    static void unlockTwo(SideTable *lock1, SideTable *lock2);
};
注: SideTable 中 slock 负责资源的线程安全, 并维护着真正的 weakTable
struct weak_table_t {
    weak_entry_t *weak_entries;
    size_t    num_entries;
    uintptr_t mask;
    uintptr_t max_hash_displacement;
};
/// Adds an (object, weak pointer) pair to the weak table.
id weak_register_no_lock(weak_table_t *weak_table, id referent, 
                         id *referrer, bool crashIfDeallocating);
/// Removes an (object, weak pointer) pair from the weak table.
void weak_unregister_no_lock(weak_table_t *weak_table, id referent, id *referrer);
#if DEBUG
/// Returns true if an object is weakly referenced somewhere.
bool weak_is_registered_no_lock(weak_table_t *weak_table, id referent);
#endif
/// Called on object destruction. Sets all remaining weak pointers to nil.
void weak_clear_no_lock(weak_table_t *weak_table, id referent);

struct weak_entry_t {
    DisguisedPtr<objc_object> referent;
    .
    .
    .
}
注: 这里可以看出 weak_table_t 管理着一个数组, 每个元素为 <weak_entry_t *>,
    weak_entry_t 才真正存储着我们需要的 weak 对象容器
    回到函数 static id storeWeak(id *location, objc_object *newObj)
    我们可以看到:
        1.元素移除函数为 void weak_unregister_no_lock(weak_table_t *weak_table, id referent, id *referrer);
        2.元素插入函数为 id weak_register_no_lock(weak_table_t *weak_table, id referent, id *referrer, bool crashIfDeallocating);
void weak_unregister_no_lock(weak_table_t *weak_table, id referent_id, 
                        id *referrer_id)
{
    objc_object *referent = (objc_object *)referent_id;
    objc_object **referrer = (objc_object **)referrer_id;
    weak_entry_t *entry;
    if (!referent) return;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        remove_referrer(entry, referrer);
        bool empty = true;
        if (entry->out_of_line()  &&  entry->num_refs != 0) {
            empty = false;
        }
        else {
            for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
                if (entry->inline_referrers[i]) {
                    empty = false; 
                    break;
                }
            }
        }
        if (empty) {
            weak_entry_remove(weak_table, entry);
        }
    }
    // Do not set *referrer = nil. objc_storeWeak() requires that the 
    // value not change.
}
注: 遍历数组找到 weak 对象,根据 num_refs(weak 对象引用计数)进行移除
id weak_register_no_lock(weak_table_t *weak_table, id referent_id, 
                      id *referrer_id, bool crashIfDeallocating)
{
    objc_object *referent = (objc_object *)referent_id;
    objc_object **referrer = (objc_object **)referrer_id;
    if (!referent  ||  referent->isTaggedPointer()) return referent_id;
    // ensure that the referenced object is viable
    bool deallocating;
    if (!referent->ISA()->hasCustomRR()) {
        deallocating = referent->rootIsDeallocating();
    }
    else {
        BOOL (*allowsWeakReference)(objc_object *, SEL) = 
            (BOOL(*)(objc_object *, SEL))
            object_getMethodImplementation((id)referent, 
                                           SEL_allowsWeakReference);
        if ((IMP)allowsWeakReference == _objc_msgForward) {
            return nil;
        }
        deallocating =
            ! (*allowsWeakReference)(referent, SEL_allowsWeakReference);
    }
    if (deallocating) {
        if (crashIfDeallocating) {
            _objc_fatal("Cannot form weak reference to instance (%p) of "
                        "class %s. It is possible that this object was "
                        "over-released, or is in the process of deallocation.",
                        (void*)referent, object_getClassName((id)referent));
        } else {
            return nil;
        }
    }
    // now remember it and where it is being stored
    weak_entry_t *entry;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        append_referrer(entry, referrer);
    } 
    else {
        weak_entry_t new_entry(referent, referrer);
        weak_grow_maybe(weak_table);
        weak_entry_insert(weak_table, &new_entry);
    }
    // Do not set *referrer. objc_storeWeak() requires that the 
    // value not change.
    return referent_id;
}
static void weak_entry_insert(weak_table_t *weak_table, weak_entry_t *new_entry)
{
    weak_entry_t *weak_entries = weak_table->weak_entries;
    assert(weak_entries != nil);
    size_t begin = hash_pointer(new_entry->referent) & (weak_table->mask);
    size_t index = begin;
    size_t hash_displacement = 0;
    while (weak_entries[index].referent != nil) {
        index = (index+1) & weak_table->mask;
        if (index == begin) bad_weak_table(weak_entries);
        hash_displacement++;
    }
    weak_entries[index] = *new_entry;
    weak_table->num_entries++;
    if (hash_displacement > weak_table->max_hash_displacement) {
        weak_table->max_hash_displacement = hash_displacement;
    }
}
static void weak_resize(weak_table_t *weak_table, size_t new_size)
{
    size_t old_size = TABLE_SIZE(weak_table);
    weak_entry_t *old_entries = weak_table->weak_entries;
    weak_entry_t *new_entries = (weak_entry_t *)
        calloc(new_size, sizeof(weak_entry_t));
    weak_table->mask = new_size - 1;
    weak_table->weak_entries = new_entries;
    weak_table->max_hash_displacement = 0;
    weak_table->num_entries = 0;  // restored by weak_entry_insert below
    if (old_entries) {
        weak_entry_t *entry;
        weak_entry_t *end = old_entries + old_size;
        for (entry = old_entries; entry < end; entry++) {
            if (entry->referent) {
                weak_entry_insert(weak_table, entry);
            }
        }
        free(old_entries);
    }
}
注: 该函数负责 weak_table_t 的插入(weak_entry_insert)和扩容(weak_grow_maybe)
    其中 weak_entry_insert 也是采用的散列分布的方式插入元素,使用了一次线性探测法来解决 hash 碰撞问题

github: https://github.com/huxiaoluder
掘金: https://juejin.im/user/5b76e3a3f265da435a484d37
邮箱: huxiaoluder@163.com

上一篇下一篇

猜你喜欢

热点阅读