底层原理

block 底层原理分析(二)

2021-08-31  本文已影响0人  晨曦的简书

通过clang分析block

#include "stdio.h"
int main(){
    int a = 8;
    void(^block)(void) = ^{
        printf("chenxi - %d",a);
    };
     block();
    return 0;
}

类似这样一段代码,我们通过 clang 之后生成 c++ 代码如下:

int main(){
    int a = 8;
    // ((void (*)())& 代表一个类型
    // __main_block_impl_0 代表一个名字,函数调用
    // (void *) 类型强转
    void(*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, a));

    // void (*) 类型强转
    // (__block_impl *) 类型强转
     ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
    return 0;
}

通过简化之后我们又能得到如下代码:

int main(){
    int a = 8;
    // __main_block_impl_0 函数
    void(*block)(void) = __main_block_impl_0(__main_block_func_0, &__main_block_desc_0_DATA, a));

    block->FuncPtr(block);
    return 0;
}

这里我们可以看到,block 其实就相当于 __main_block_impl_0,那么我们来看下 __main_block_impl_0 的结构:

// 结构体
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  // 捕获外部的 a,生成响应的成员变量
  int a;
  // __main_block_impl_0 代表结构体的构造函数
  // a(_a) 代表外部传入进来的 _a 对成员变量 a 赋值
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int _a, int flags=0) : a(_a) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  int a = __cself->a; // bound by copy

        printf("chenxi - %d",a);
    }

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};

这里可以看到 __main_block_impl_0 其实就是一个结构体,他的值就是结构体的构造函数 __main_block_impl_0,在这里我们可以得出几点结论:

int main(){
    __block int a = 8;
    void(^block)(void) = ^{
        a++;
        printf("chenxi - %d",a);
    };
    block();
    return 0;
}
struct __Block_byref_a_0 {
  void *__isa;
// __forwarding 指向 a
__Block_byref_a_0 *__forwarding;
 int __flags;
 int __size;
 int a;
};

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __Block_byref_a_0 *a; // by ref
    // 这里吧 a 的 __forwarding 赋值给了 __forwarding
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_a_0 *_a, int flags=0) : a(_a->__forwarding) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

// 这里的 a 与 c 函数中 block 中传入的 a 相同,因为指向的都是同一个地址
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  __Block_byref_a_0 *a = __cself->a; // bound by ref

        (a->__forwarding->a)++;
        printf("chenxi - %d",(a->__forwarding->a));
    }
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->a, (void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);}

static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(){

    // int a = 8
    // 这一步相当于 __Block_byref_a_0 结构体的初始化,并对 a 取地址
    __Block_byref_a_0 a = {
        (void*)0,
        (__Block_byref_a_0 *)&a,
        0,
        sizeof(__Block_byref_a_0), 8
    };
    
    void(*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_a_0 *)&a, 570425344));

     ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
    return 0;
}

block 汇编分析得到签名 copy 的过程

这里我们通过汇编分析的方式来追踪一下 block 的执流程。


首先我们在 block 中不使用外部变量,断点之后定位到 objc_retainBlock,然后我们一步一步的往下执行。

之后我们可以定位到 _Block_copy 函数,在这里输出 x0 可以看到是 __NSStackBlock__ 类型。现在我们修改 block 使用外部变量再来输出一下。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSObject *object = [[NSObject alloc] init];
    void (^block)(void) = ^{
        NSLog(@"block --- %@",object);
    };
    block();
}

使用了外部变量再输出之后这里就变为了 __NSStackBlock__ 类型,这里因为还没有经过 copy 所以是栈 block。我们在 _Block_copyreturn 执行这里再打断点输出。

这里 x0 就是返回值,输出之后可以看到是 __NSMallocBlock__ 类型,是堆 block,说明经过 _Block_copy 之后,block 由栈区被拷贝到了堆区。下面我们再来看下源码中 _Block_copy 的执行逻辑:

void *_Block_copy(const void *arg) {
   struct Block_layout *aBlock;
   if (!arg) return NULL;
   aBlock = (struct Block_layout *)arg;
   // 判断 flags 标识且引用计数是释放状态就直接返回
   if (aBlock->flags & BLOCK_NEEDS_FREE) {
       latching_incr_int(&aBlock->flags);
       return aBlock;
   }
   // 如果是 BLOCK_IS_GLOBAL 就直接返回
   else if (aBlock->flags & BLOCK_IS_GLOBAL) {
       return aBlock;
   }
   // 到了这里就是栈 block 跟堆 block 两种,但是在编译器没有内存的开辟,只是标识为栈 block
   else {// 栈 - 堆 (编译期)
       // 运行时的时候判断是栈区 block 就会按相同大小在堆区开辟相同的大小空间,并标识为堆 block
       size_t size = Block_size(aBlock);
       struct Block_layout *result = (struct Block_layout *)malloc(size);
       if (!result) return NULL;
       // 对相关数据都进行拷贝一份
       memmove(result, aBlock, size); // bitcopy first
#if __has_feature(ptrauth_calls)
       // Resign the invoke pointer as it uses address authentication.
       result->invoke = aBlock->invoke;

#if __has_feature(ptrauth_signed_block_descriptors)
       if (aBlock->flags & BLOCK_SMALL_DESCRIPTOR) {
           uintptr_t oldDesc = ptrauth_blend_discriminator(
                   &aBlock->descriptor,
                   _Block_descriptor_ptrauth_discriminator);
           uintptr_t newDesc = ptrauth_blend_discriminator(
                   &result->descriptor,
                   _Block_descriptor_ptrauth_discriminator);

           result->descriptor =
                   ptrauth_auth_and_resign(aBlock->descriptor,
                                           ptrauth_key_asda, oldDesc,
                                           ptrauth_key_asda, newDesc);
       }
#endif
#endif
       result->flags &= ~(BLOCK_REFCOUNT_MASK|BLOCK_DEALLOCATING);    // XXX not needed
       result->flags |= BLOCK_NEEDS_FREE | 2;  // logical refcount 1
       _Block_call_copy_helper(result, aBlock);
       // 标识为堆 block
       result->isa = _NSConcreteMallocBlock;
       return result;
   }
}

block 签名

v8@?0 代表占 8 个字节,从 0 号位置开始,@ 代表 id 类型。输出也可以看到 block 的签名是 @?。签名在消息转发的时候需要用到。

blocklayout 的结构

struct Block_layout {
    // isa 指针
    void * __ptrauth_objc_isa_pointer isa;
    // 标识符
    volatile int32_t flags;
    int32_t reserved;
    // 函数指针
    BlockInvokeFunction invoke;
    struct Block_descriptor_1 *descriptor;
    // imported variables
};

struct Block_descriptor_1 {
    uintptr_t reserved;
    // 代表 size 大小
    uintptr_t size;
};

通过源码我们可以看到 Block_layout 数据结构,但是我们看不到 signature, copy, dispose 这些数据。但是我们搜索可以看到 copy, dispose 存在于 Block_descriptor_2 中,signature 存在于 Block_descriptor_3 中。

#define BLOCK_DESCRIPTOR_2 1
struct Block_descriptor_2 {
    // requires BLOCK_HAS_COPY_DISPOSE
    BlockCopyFunction copy;
    BlockDisposeFunction dispose;
};

#define BLOCK_DESCRIPTOR_3 1
struct Block_descriptor_3 {
    // requires BLOCK_HAS_SIGNATURE
    const char *signature;
    const char *layout;     // contents depend on BLOCK_HAS_EXTENDED_LAYOUT
};

我们再来看看 Block_descriptor_2Block_descriptor_3 的获取。

static struct Block_descriptor_2 * _Block_descriptor_2(struct Block_layout *aBlock)
{
    uint8_t *desc = (uint8_t *)_Block_get_descriptor(aBlock);
    desc += sizeof(struct Block_descriptor_1);
    return (struct Block_descriptor_2 *)desc;
}

static struct Block_descriptor_3 * _Block_descriptor_3(struct Block_layout *aBlock)
{
    uint8_t *desc = (uint8_t *)_Block_get_descriptor(aBlock);
    desc += sizeof(struct Block_descriptor_1);
    if (aBlock->flags & BLOCK_HAS_COPY_DISPOSE) {
        desc += sizeof(struct Block_descriptor_2);
    }
    return (struct Block_descriptor_3 *)desc;
}

在代码中我们可以看到,Block_descriptor_2 是通过内存平移 Block_descriptor_1 的大小得到的,Block_descriptor_3 是通过内存平移 Block_descriptor_2 的大小得到的,但是这里会判断 Block_descriptor_2 存不存在,不存在的话,原来 Block_descriptor_2 的位置就好存放 Block_descriptor_3。这里也说明 Block_layoutsignature, copy, dispose 这些数据是根据类型的不同是可选的。

block 的捕获变量生命周期

#include "stdio.h"
int main(){
    int a = 8;
    void(^block)(void) = ^{
        printf("chenxi - %d",a);
    };
     block();
    return 0;
}

在我们最开始的时候讲到,这样一段代码通过 clang 可以生成如下的 c++ 代码:

static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->a, (void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);}

static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->a, 8/*BLOCK_FIELD_IS_BYREF*/);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(){

    // int a = 18;
    __Block_byref_a_0 a = {
        (void*)0,
        (__Block_byref_a_0 *)&a,
        0,
        sizeof(__Block_byref_a_0),
        18};
    
    void(*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_a_0 *)&a, 570425344));

     ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
    return 0;
}

这里 __main_block_desc_0 就是 block 的结构体,这里要对结构体进行初始化,__main_block_copy_0 就是代表 Block_descriptor_2 中的 copy__main_block_dispose_0 就是代表 Block_descriptor_2 中的 dispose,而当 __main_block_copy_0 调用的时候就会执行 _Block_object_assign((void*)&dst->a, (void*)src->a, 8)

通过源码搜索 _Block_object_assign 可以看到这些类型代表对捕获变量类型的标识。我们这里 block 捕获的是 int 8,所以就是 BLOCK_FIELD_IS_BYREF 类型。下面我们来看一下 _Block_object_assign 函数。

_Block_object_assign 源码分析

void _Block_object_assign(void *destArg, const void *object, const int flags) {
    const void **dest = (const void **)destArg;
    switch (os_assumes(flags & BLOCK_ALL_COPY_DISPOSE_FLAGS)) {
      case BLOCK_FIELD_IS_OBJECT:
        _Block_retain_object(object);
        *dest = object;
        break;

      case BLOCK_FIELD_IS_BLOCK:
        *dest = _Block_copy(object);
        break;

      case BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK:
      case BLOCK_FIELD_IS_BYREF:
        *dest = _Block_byref_copy(object);
        break;

      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK:
        *dest = object;
        break;

      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK  | BLOCK_FIELD_IS_WEAK:
        *dest = object;
        break;

      default:
        break;
    }
}
*dest = object;
*dest = _Block_copy(object);
*dest = _Block_byref_copy(object);

_Block_byref_copy 源码分析

static struct Block_byref *_Block_byref_copy(const void *arg) {
    struct Block_byref *src = (struct Block_byref *)arg;

    // __block 内存是一样 同一个家伙
    if ((src->forwarding->flags & BLOCK_REFCOUNT_MASK) == 0) {
        // src points to stack
        struct Block_byref *copy = (struct Block_byref *)malloc(src->size);
        copy->isa = NULL;
        // byref value 4 is logical refcount of 2: one for caller, one for stack
        copy->flags = src->flags | BLOCK_BYREF_NEEDS_FREE | 4;
        copy->forwarding = copy; // patch heap copy to point to itself
        src->forwarding = copy;  // patch stack to point to heap copy
        copy->size = src->size;

        if (src->flags & BLOCK_BYREF_HAS_COPY_DISPOSE) {
            // Trust copy helper to copy everything of interest
            // If more than one field shows up in a byref block this is wrong XXX
            struct Block_byref_2 *src2 = (struct Block_byref_2 *)(src+1);
            struct Block_byref_2 *copy2 = (struct Block_byref_2 *)(copy+1);
            copy2->byref_keep = src2->byref_keep;
            copy2->byref_destroy = src2->byref_destroy;

            if (src->flags & BLOCK_BYREF_LAYOUT_EXTENDED) {
                struct Block_byref_3 *src3 = (struct Block_byref_3 *)(src2+1);
                struct Block_byref_3 *copy3 = (struct Block_byref_3*)(copy2+1);
                copy3->layout = src3->layout;
            }
            // 捕获到了外界的变量 - 内存处理 - 生命周期的保存
            (*src2->byref_keep)(copy, src);
        }
        else {
            // Bitwise copy.
            // This copy includes Block_byref_3, if any.
            memmove(copy+1, src+1, src->size - sizeof(*src));
        }
    }
    // already copied to heap
    else if ((src->forwarding->flags & BLOCK_BYREF_NEEDS_FREE) == BLOCK_BYREF_NEEDS_FREE) {
        latching_incr_int(&src->forwarding->flags);
    }
    return src->forwarding;
}
    copy->forwarding = copy;
    src->forwarding = copy;

Block_byref 的设计思路和 Block_layoutdescriptor 流程类似,通过 byref->flag 标识码判断对应的属性,以此来判断Block_byref_2 是否存在,Block_byref 定义见下图:

如果用 __block 修饰了外部变量,编译生成的 cpp 文件中,Block_byref 结构体中就会默认生成两个方法,即对应Block_byref_2keep 方法和 destory 方法,见下图:

cpp 文件中搜索这两个函数的实现,见下图:

此过程会再次调用 _Block_object_assign 函数,对 Block_byref结构体中的对象进行 BLOCK_FIELD_IS_OBJECT 流程处理。

至此 block 的三重拷贝已经摸清:

  • block 的拷贝,即将栈区 block 拷贝至堆区
  • __block 修饰的对象,对应的 Block_byref 结构体的拷贝
  • Block_byref 修饰的对象,调用 _Block_object_assign 函数进行修饰处理。
上一篇下一篇

猜你喜欢

热点阅读