ランタイムを介してランタイムobjc4-779.1解析OCオブジェクト初期化ソースコード
一般的なオブジェクトの初期化コード
[[NSArray alloc] init]
[NSArray new]
レッツ・脳卒中へのalloc +初期化の方法、それを再度実行時の初期化処理の目的に応じて、私たちが学ぶことができることは価値がある参照してください。
以下の表記は、<ステップ番号> <コードが常駐するファイル> <行番号>
だから、好ましくは同期制御の記事を読んでobjc4-779.1でソースを
1つのNSObject.mmライン2317
+ (id)alloc {
return _objc_rootAlloc(self);
}
2 NSObject.mmライン1717
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
3 NSObject.mmライン1697
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
// 是否是Objective-C 2.0
#if __OBJC2__
// 3.1 判定是否检查cls是否为空,如果检查,为空则返回nil
if (slowpath(checkNil && !cls)) return nil;
// 3.2 检查本类、父类的继承链上是否有实现自己的allocWithZone方法,如果没有,就默认调用元类的
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// 3.3 判断是否要调用allocWithZone方法,使用runtime的方法调用常规操作.
// No shortcuts available.
if (allocWithZone) {
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
4 NSObject.mm line2321
// 替代 alloc方法
// Replaced by ObjectAlloc
+ (id)allocWithZone:(struct _NSZone *)zone {
return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}
5 NSObject.mm line2534
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
{
id obj;
if (fastpath(!zone)) {
// class_createInstance内部实质调用的是 _class_createInstanceFromZone 方法
obj = class_createInstance(cls, 0);
} else {
obj = class_createInstanceFromZone(cls, 0, zone);
}
if (slowpath(!obj)) obj = _objc_callBadAllocHandler(cls);
return obj;
}
したがって、このステップは、実際には一見発散にOBJの初期化処理、コレクションへの呼び出しで_class_createInstanceFromZone
6 objc-runtime-new.mm line7385
/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* Note: this function has been carefully written so that the fastpath
* takes no branch.
**********************************************************************/
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
int construct_flags = OBJECT_CONSTRUCT_NONE,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
// 6.1 如果类对象本身没有被实现,则发出警告,并终止程序
ASSERT(cls->isRealized());
// 6.2 通过位运算获取类的信息,以提高性能
// Read class's info bits all at once for performance
// 是否有C++ 构造函数
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
// 是否有C++ 析构函数
bool hasCxxDtor = cls->hasCxxDtor();
//如果isa_t指针可用,则为true,反之为false,2.0版本中绝大多数类都是支持isa_t的,如果对isa和isa_t不清楚的,可以看之前的博文 https://blog.csdn.net/wxs0124/article/details/84401718
bool fast = cls->canAllocNonpointer();
size_t size;
// 初始化的大小,instanceSize保证大小必须大于等于16bytes,内部总结就是用class_ro_t的isa_t的大小(8bytes)加上extraBytes,如果小于16bytes则补齐为16bytes, 这样做是为了内存对齐.
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
// 6.3开辟内存空间
if (zone) {
// 空间大小为size大小
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
// 空间初始化默认为0或者nil
obj = (id)calloc(1, size);
}
// 这里判断是否有构造函数,如果没有终止,到这里我们遇到了fastpath和slowpath,稍后我们看一下他的源码和作用
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
// 6.4 初始化isa_t
if (!zone && fast) {
//initInstanceIsa方法内部也是调用initIsa方法,只是因没有空间并且有isa_t指针而传参不同
obj->initInstanceIsa(cls, hasCxxDtor);
} else {
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
if (fastpath(!hasCxxCtor)) {
return obj;
}
construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
return object_cxxConstructFromClass(obj, cls, construct_flags);
}
7にObjC-object.h line214
inline void
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
ASSERT(!cls->instancesRequireRawIsa());
ASSERT(hasCxxDtor == cls->hasCxxDtor());
// 没有zone的情况下,该方法才回被调用,对应的,空间是默认为0或者nil的,需要创建isa_t
initIsa(cls, true, hasCxxDtor);
}
inline void
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
{
ASSERT(!isTaggedPointer());
// 7.1 如果有isa_t
if (!nonpointer) {
isa = isa_t((uintptr_t)cls);
} else {
// 7.2如果没有isa_t 则进行初始化isa_t
ASSERT(!DisableNonpointerIsa);
ASSERT(!cls->instancesRequireRawIsa());
isa_t newisa(0);
#if SUPPORT_INDEXED_ISA
ASSERT(cls->classArrayIndex() > 0);
newisa.bits = ISA_INDEX_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
newisa.bits = ISA_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
// This write must be performed in a single store in some cases
// (for example when realizing a class because other threads
// may simultaneously try to use the class).
// fixme use atomics here to guarantee single-store and to
// guarantee memory order w.r.t. the class index table
// ...but not too atomic because we don't want to hurt instantiation
isa = newisa;
}
}
8 NSObject.mm line2331
- (id)init {
return _objc_rootInit(self);
}
id _objc_rootInit(id obj)
{
// In practice, it will be hard to rely on this function.
// Many classes do not properly chain -init calls.
return obj;
}
この時点で、プロセスALLOC初期化を介してオブジェクトが完了すると、最終的な目標は、連邦isa_tコンテンツの割り当てでメモリの割り当て、およびオブジェクトへのポインタを返します
説明しますfastpath
slowpath
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
コアとしてこれら二つの方法は、定義されたマクロであり__builtin_expect(EXP,N)
され、gcc
EXP == Nが大きい確率を意味命令によって提供さ
彼は言ったfastpath
xの値は、おそらく本当だったslowpath
xの値は、おそらく偽物でした
新しい初期化メソッド
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
それは変わらない本質的にその新たな方法とはalloc +のinit的に表示されます
要約します
- コアオブジェクトの初期化プロセス
objc_class
のオープンスペースの状態、及びisa_t内容を初期化する、オブジェクトの次に割り当てメモリと、このメモリ領域を指すポインタを返します。 - オブジェクトOCアライメント制限CFメモリシステムのサイズので、すべてのオブジェクトがより大きいか等しいデフォルトの16バイト
- 使用すると、パフォーマンスを向上させるためにisa_t初期化プロセスにおける操作ビット日々の開発に適用することができ
fastpath
slowpath
アプリケーションgcc
命令は__builtin_expect(EXP,N)
、パフォーマンス上のオーバーヘッドを削減するコンパイル時のコードのレイアウトで、コンパイラによって、この命令の最適化は、ジャンプ命令を引き起こしました。