Object-C語言Block的實現方式

滴水微瀾發表於2019-01-05
開場白
Block基本概念
中間態轉換方法
Block編譯後結果分析
Block執行時狀態與編譯狀態對比
 
開場白
 
Object-C語言是對C語言的擴充套件,所以將OC原始碼進行編譯的時候,會將OC原始碼會被轉換成C\C++,所以想了解OC原始碼的實現細節,還是需要手動編譯成中間狀態進行觀察。
命令1:
clang -rewrite-objc main.m

如果Xcode版本較高,可能會出現報錯:

./block_VC.h:9:9: fatal error: 'UIKit/UIKit.h' file not found

此時可嘗試另一個命令:

clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk main.m
命令好長,每次輸入這麼長的指令很麻煩,此時可以考慮使用命令別名:alias

 

Block的基本概念

_NSConcreteGlobalBlock 全域性的靜態 block,不會訪問任何外部變數。
_NSConcreteStackBlock 儲存在棧中的 block,當函式返回時會被銷燬。
_NSConcreteMallocBlock 儲存在堆中的 block,當引用計數為 0 時會被銷燬。

 

堆中的 block何時轉換:
1.呼叫copy方法時
2.從一個函式返回時
3.將block傳入dispatch等系統IPA引數block或者傳遞給帶有usingBlock的Cocoa框架函式時。
4.將block賦給帶有__strong修飾符的id型別或者Block型別時。

 

Block型別變換方式

1.沒有捕獲任何區域性變數的block為_NSConcreteGlobalBlock,它以static函式的形式儲存在程式碼區

2.捕獲了區域性變數的block為_NSConcreteStackBlock

3.當_NSConcreteStackBlock出現上面四種情況時,會變成_NSConcreteMallocBlock。(注意此時是呼叫了Block_Copy函式後)

 

Block編譯後結果分析

基本型別變數

OC原始碼:

NSInteger age = 10;
void(^completeBlock)(NSString *) = ^(NSString *name) {
    NSString *info = [NSString stringWithFormat:@"name:%@ - age:%d",name,age];
    NSLog(@"%@",info);
};

completeBlock(@"jack");

編譯後的C\C++原始碼:

// __block_impl為block的基礎struct
//1.*isa:當前block物件所屬的型別(注意:在OC語言中帶有isa指標的都是物件)
//2.Flags:標示位,當型別為NSConcreteMallocBlock時,表示需要ARC記憶體管理,其他預設不需要記憶體管理
//3.Reserved:預留標示位,暫時不管它
//4.block的實際static內部函式地址指標
struct __block_impl {
    void *isa;
    int Flags;
    int Reserved;
    void *FuncPtr;
};

// __main_block_impl_0為block的最終struct
//1.impl:為上面的__block_impl結構體例項
//2.Desc:為block的描述結構體__main_block_desc_0,裡面包含了block結構體的資訊描述,在下面講解
//3.age:從外面補貨的變數,block採用的方式是直接在block例項中定義一個變數,將捕獲的值賦給它
//4.__main_block_impl_0:為block結構體的建構函式,引數中包含從外面捕獲的變數值
struct __main_block_impl_0 {
    struct __block_impl impl;
    struct __main_block_desc_0* Desc;
    NSInteger age;
    __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, NSInteger _age, int flags=0) : age(_age) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
    }
};

//__main_block_func_0為block具體實現的函式載體,具體的block的任務實現在此函式內
//引數:1是block的例項指標,2是block的外部傳參name
static void __main_block_func_0(struct __main_block_impl_0 *__cself, NSString *name) {
    //從block例項中獲取age變數的值
    NSInteger age = __cself->age; // bound by copy

    //生成字串NSString *info = [NSString stringWithFormat:@"name:%@ - age:%d",name,age];
    NSString *info = ((NSString * _Nonnull (*)(id, SEL, NSString * _Nonnull, ...))(void *)objc_msgSend)((id)objc_getClass("NSString"), sel_registerName("stringWithFormat:"), (NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_83d55e_mi_0, (NSString *)name, (NSInteger)age);
    
    //列印NSLog(@"%@",info);
    NSLog((NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_83d55e_mi_1,info);
}

//reserved:保留字0
//Block_size:block例項在記憶體中佔據記憶體大小
//__main_block_desc_0_DATA:預設desc結構體例項
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函式
int main(int argc, char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;

        NSInteger age = 10;
        void(*completeBlock)(NSString *) = ((void (*)(NSString *))&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, age));

        ((void (*)(__block_impl *, NSString *))((__block_impl *)completeBlock)->FuncPtr)((__block_impl *)completeBlock, (NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_83d55e_mi_2);

        return UIApplicationMain(argc, argv, __null, NSStringFromClass(((Class (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("AppDelegate"), sel_registerName("class"))));
    }
}

block簡單結構佈局

struct __block_impl
struct __main_block_impl_0
static void __main_block_func_0
static struct __main_block_desc_0
詳細解釋見上面的中間編譯狀態。
block例項中定義了一個age變數,並將外部的age傳了過去
 
__block基本型別變數
OC原始碼:
__block NSInteger age = 10;
void(^completeBlock)(NSString *) = ^(NSString *name) {
    NSString *info = [NSString stringWithFormat:@"name:%@ - age:%d",name,age];
    NSLog(@"%@",info);
};

completeBlock(@"jack");
編譯後的C\C++原始碼:
struct __block_impl {
    void *isa;
    int Flags;
    int Reserved;
    void *FuncPtr;
};

//age的block變數例項__Block_byref_age
//__isa:age的block變數例項所屬的型別
//__forwarding:age的block變數例項的指標
//__flags:變數是否被記憶體管理標示
//__size:所佔記憶體大小
//age:age變數值
struct __Block_byref_age_0 {
    void *__isa;
    __Block_byref_age_0 *__forwarding;
    int __flags;
    int __size;
    NSInteger age;
};

//原來的age變數值,變成了__Block_byref_age_0變數指標
struct __main_block_impl_0 {
    struct __block_impl impl;
    struct __main_block_desc_0* Desc;
    __Block_byref_age_0 *age; // by ref
    __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_age_0 *_age, int flags=0) : age(_age->__forwarding) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
    }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself, NSString *name) {
    //通過block例項獲取變數的指標
    __Block_byref_age_0 *age = __cself->age; // bound by ref

    NSLog((NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_7acc63_mi_0,name,(age->__forwarding->age));
}

//當block從棧複製到堆上時,會對__Block_byref_age_0變數進行拷貝,也會從棧拷貝到堆上
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->age, (void*)src->age, 8/*BLOCK_FIELD_IS_BYREF*/);}

//__Block_byref_age_0變數的解構函式,當block例項的引用計數為0時,是否__Block_byref_age_0變數的記憶體空間
static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->age, 8/*BLOCK_FIELD_IS_BYREF*/);}

//desc結構體中新增了copy函式和dispose函式指標
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 argc, char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
        //block變數例項
        __attribute__((__blocks__(byref))) __Block_byref_age_0 age = {(void*)0,(__Block_byref_age_0 *)&age, 0, sizeof(__Block_byref_age_0), 10};
        //block例項
        void(*completeBlock)(NSString *) = ((void (*)(NSString *))&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_age_0 *)&age, 570425344));

        ((void (*)(__block_impl *, NSString *))((__block_impl *)completeBlock)->FuncPtr)((__block_impl *)completeBlock, (NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_7acc63_mi_1);

        return UIApplicationMain(argc, argv, __null, NSStringFromClass(((Class (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("AppDelegate"), sel_registerName("class"))));
    }
}

簡單結構佈局

struct __block_impl
struct __main_block_impl_0
static void __main_block_func_0
static struct __main_block_desc_0
//新增
struct __Block_byref_age_0
static void __main_block_copy_0(
static void __main_block_dispose_0(

__block NSInteger age = 10;後,在簡單佈局結構中新增了3項

struct __Block_byref_age_0
static void __main_block_copy_0(
static void __main_block_dispose_0(
__Block_byref_age_0將基本變數轉換成__block變數結構體例項指標
__main_block_copy_0和__main_block_dispose_0是對__block變數結構體例項的記憶體管理方法。
__block變數結構體例項從棧拷貝到堆時,呼叫方法:__main_block_copy_0
__block變數結構體例項引用計數為0時,呼叫方法:__main_block_dispose_0
 
指標型別變數

OC原始碼:

NSMutableArray *friends = [NSMutableArray array];;
void(^completeBlock)(NSString *) = ^(NSString *name) {
    NSLog(@"%@--%@",name,friends);
};

completeBlock(@"jack");

編譯後的C\C++原始碼:

struct __block_impl {
    void *isa;
    int Flags;
    int Reserved;
    void *FuncPtr;
};

struct __main_block_impl_0 {
    struct __block_impl impl;
    struct __main_block_desc_0* Desc;
    NSMutableArray *friends;
    __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, NSMutableArray *_friends, int flags=0) : friends(_friends) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
    }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself, NSString *name) {
    NSMutableArray *friends = __cself->friends; // bound by copy

    NSLog((NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_1b4a2f_mi_0,name,friends);
}
//block例項從棧複製到堆上時,將指標變數引用計數加一
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->friends, (void*)src->friends, 3/*BLOCK_FIELD_IS_OBJECT*/);}

//block例項引用計數為0時,析構指標變數物件
static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->friends, 3/*BLOCK_FIELD_IS_OBJECT*/);}

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 argc, char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;

        NSMutableArray *friends = ((NSMutableArray * _Nonnull (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSMutableArray"), sel_registerName("array"));;
        void(*completeBlock)(NSString *) = ((void (*)(NSString *))&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, friends, 570425344));

        ((void (*)(__block_impl *, NSString *))((__block_impl *)completeBlock)->FuncPtr)((__block_impl *)completeBlock, (NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_1b4a2f_mi_1);

        return UIApplicationMain(argc, argv, __null, NSStringFromClass(((Class (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("AppDelegate"), sel_registerName("class"))));
    }
}

簡單結構佈局

struct __block_impl
struct __main_block_impl_0
static void __main_block_func_0
static struct __main_block_desc_0
static void __main_block_copy_0(
static void __main_block_dispose_0(
block例項中定義了一個NSMutableArray *friends;指標變數,並通過建構函式將指標傳遞給block例項
__main_block_copy_0:block例項從棧複製到堆上時,將指標變數引用計數加一
__main_block_dispose_0:block例項引用計數為0時,析構指標變數物件

 

__block指標型別變數

OC原始碼:

__block NSMutableArray *friends = [NSMutableArray array];;
void(^completeBlock)(NSString *) = ^(NSString *name) {
    NSLog(@"%@--%@",name,friends);
};

completeBlock(@"jack");

編譯後的C\C++原始碼:

struct __block_impl {
    void *isa;
    int Flags;
    int Reserved;
    void *FuncPtr;
};

//__Block_byref_friends_0結構體例項中包含了friends指標
//並且多了__Block_byref_id_object_copy函式:對friends進行copy
//多了__Block_byref_id_object_dispose函式:對friends進行析構
struct __Block_byref_friends_0 {
    void *__isa;
    __Block_byref_friends_0 *__forwarding;
    int __flags;
    int __size;
    void (*__Block_byref_id_object_copy)(void*, void*);
    void (*__Block_byref_id_object_dispose)(void*);
    NSMutableArray *friends;
};

struct __main_block_impl_0 {
    struct __block_impl impl;
    struct __main_block_desc_0* Desc;
    __Block_byref_friends_0 *friends; // by ref
    __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_friends_0 *_friends, int flags=0) : friends(_friends->__forwarding) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
    }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself, NSString *name) {
    __Block_byref_friends_0 *friends = __cself->friends; // bound by ref

    NSLog((NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_252d0c_mi_0,name,(friends->__forwarding->friends));
}

//block例項從棧複製到堆上時,__block變數結構體例項將指標變數引用計數加一,同時__block變數結構體例項內的NSMutableArray *friends變數也遞迴加一
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->friends, (void*)src->friends, 8/*BLOCK_FIELD_IS_BYREF*/);}

//block例項引用計數為0時,__block變數結構體例項被析構,同時__block變數結構體例項內的NSMutableArray *friends變數也遞迴析構
static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->friends, 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 argc, char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;

        __attribute__((__blocks__(byref))) __Block_byref_friends_0 friends = {(void*)0,(__Block_byref_friends_0 *)&friends, 33554432, sizeof(__Block_byref_friends_0), __Block_byref_id_object_copy_131, __Block_byref_id_object_dispose_131, ((NSMutableArray * _Nonnull (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSMutableArray"), sel_registerName("array"))};;
        void(*completeBlock)(NSString *) = ((void (*)(NSString *))&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_friends_0 *)&friends, 570425344));

        ((void (*)(__block_impl *, NSString *))((__block_impl *)completeBlock)->FuncPtr)((__block_impl *)completeBlock, (NSString *)&__NSConstantStringImpl__var_folders_4y_ks8945f50k51_0j95ytw7ss80000gn_T_main_252d0c_mi_1);

        return UIApplicationMain(argc, argv, __null, NSStringFromClass(((Class (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("AppDelegate"), sel_registerName("class"))));
    }
}

簡單結構變數

struct __block_impl
struct __main_block_impl_0
static void __main_block_func_0
static struct __main_block_desc_0
static void __main_block_copy_0(
static void __main_block_dispose_0(
//新增
struct __Block_byref_age_0
和__block普通變數一樣,出現了__Block_byref_age_0結構體
__Block_byref_friends_0結構體例項中包含了friends指標
並且多了__Block_byref_id_object_copy函式:對friends進行copy
多了__Block_byref_id_object_dispose函式:對friends進行析構
同時在函式__main_block_copy_0和__main_block_dispose_0中,出現的也是對__Block_byref_age_0結構體的呼叫。它是在將__Block_byref_age_0結構體析構之前,先析構friends物件。
 
Block編譯中間態與執行時狀態對比
利用lldb列印出來的結果
區域性自由變數
//區域性變數
__block NSMutableArray *friends = [NSMutableArray array];;
void(^completeBlock)(NSString *) = ^(NSString *name) {
    NSLog(@"%@--%@",name,friends);
};


(lldb) expression -P 5 -- completeBlock
(void (^)(NSString *)) $2 = 0x000000010a061130 {
  __isa = __NSMallocBlock__
  __flags = -1023410170
  __reserved = 0
  __FuncPtr = 0x000000010a061130 (iOS_KnowledgeStructure`__main_block_invoke at main.m:19) {}
}

利用clang轉換後的C\C++原始碼

struct __main_block_impl_0 {
    struct __block_impl impl;
    struct __main_block_desc_0* Desc;
    __Block_byref_friends_0 *friends; // by ref
    __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_friends_0 *_friends, int flags=0) : friends(_friends->__forwarding) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
    }
};
證明clang編譯器和llvm編譯器編譯後的結果有出入。發現isa指標不一致。
編譯後的為:impl.isa = &_NSConcreteStackBlock;
執行時的為:__isa = __NSMallocBlock__
原因是block型別轉換情況4:“將block賦給帶有__strong修飾符的id型別或者Block型別時。”
 
注意:
_NSConcreteMallocBlock一般不會在原始碼中出現,它通常在block copy到堆時出現,變化的原始碼:
static void *_Block_copy_internal(const void *arg, const int flags) {
struct Block_layout *aBlock;
const bool wantsOne = (WANTS_ONE & flags) == WANTS_ONE;
// 1
if (!arg) return NULL;
// 2
aBlock = (struct Block_layout *)arg;
// 3
if (aBlock->flags & BLOCK_NEEDS_FREE) {
// latches on high
latching_incr_int(&aBlock->flags);
return aBlock;
}
// 4
else if (aBlock->flags & BLOCK_IS_GLOBAL) {
return aBlock;
}
// 5
struct Block_layout *result = malloc(aBlock->descriptor->size);
if (!result) return (void *)0;
// 6
memmove(result, aBlock, aBlock->descriptor->size); // bitcopy first
// 7
result->flags &= ~(BLOCK_REFCOUNT_MASK); // XXX not needed
result->flags |= BLOCK_NEEDS_FREE | 1;
// 8
result->isa = _NSConcreteMallocBlock;
// 9
if (result->flags & BLOCK_HAS_COPY_DISPOSE) {
(*aBlock->descriptor->copy)(result, aBlock); // do fixup
}
return result;
}

 

 

相關文章