Objective-C 小記(6)alloc & init

本文使用的 runtime 版本為 objc4-706

+alloc-init 是我們經(jīng)常使用的兩個(gè)方法,通常它們也是以 [[SomeClass alloc] init] 這個(gè)形式出現(xiàn)的,本篇文章對(duì)它們的實(shí)現(xiàn)做一點(diǎn)記錄。

alloc

NSObject.mm 中,可以找到 +alloc 的實(shí)現(xiàn):

+ (id)alloc {
    return _objc_rootAlloc(self);
}

+alloc 的實(shí)現(xiàn)就是簡(jiǎn)單的將事情甩給了 _objc_rootAlloc,接著看 _objc_rootAlloc 的實(shí)現(xiàn):

// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

_objc_rootAlloc 也是一個(gè)甩鍋俠,將鍋甩給了 callAlloc,繼續(xù)看 callAlloc 的實(shí)現(xiàn):

// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    if (slowpath(checkNil && !cls)) return nil;

#if __OBJC2__
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        // No alloc/allocWithZone implementation. Go straight to the allocator.
        // fixme store hasCustomAWZ in the non-meta class and 
        // add it to canAllocFast's summary
        if (fastpath(cls->canAllocFast())) {
            // No ctors, raw isa, etc. Go straight to the metal.
            bool dtor = cls->hasCxxDtor();
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            obj->initInstanceIsa(cls, dtor);
            return obj;
        }
        else {
            // Has ctor or raw isa or something. Use the slower path.
            id obj = class_createInstance(cls, 0);
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            return obj;
        }
    }
#endif

    // No shortcuts available.
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}

其中 slowpathfastpath 宏的定義如下:

#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))

__builtin_expect 起的是優(yōu)化性能的作用,表示分支預(yù)測(cè)時(shí)第一個(gè)參數(shù)較大概率會(huì)是第二個(gè)參數(shù),所以 fastpath(x) 表示 x 較大概率為真,slowpath(x) 表示 x 較大概率為假,返回值就是 x 本身。

回到 callAlloc,剛開(kāi)始的一句 if (slowpath(checkNil && !cls)) return nil; 進(jìn)行了對(duì) cls 參數(shù)為 nil 的判斷,使用的是 slowpath,表示這是比較不可能出現(xiàn)的情況。

接下來(lái)從 #if __OBJC2__ 開(kāi)始至 #endif,都是在 Objective-C 2.0 下才會(huì)有的代碼,那當(dāng)然是我們需要關(guān)注的地方了,畢竟我們現(xiàn)在使用的就是 Objective-C 2.0。

其中,首先要進(jìn)行一下判斷:if (fastpath(!cls->ISA()->hasCustomAWZ())) { ... },這里判斷一個(gè)類是否有自定義的 +allocWithZone: 實(shí)現(xiàn),有的話,就不能走這里面的默認(rèn)實(shí)現(xiàn)了。

繼續(xù)關(guān)注默認(rèn)實(shí)現(xiàn),接下來(lái)進(jìn)行判斷 if (fastpath(cls->canAllocFast())) { ... } else { ... }。首先關(guān)于 canAllocFast 的定義是這樣的,在 objc-runtime-new.h 中:

#if FAST_ALLOC

    ...

    bool canAllocFast() {
        return bits & FAST_ALLOC;
    }
#else
    size_t fastInstanceSize() {
        abort();
    }
    void setFastInstanceSize(size_t) {
        // nothing
    }
    bool canAllocFast() {
        return false;
    }
#endif

同樣還是在 objc-runtime-new.h 中,可以看到有關(guān) FAST_ALLOC 的定義:

#if !__LP64__

...

#elif 1
// Leaks-compatible version that steals low bits only.

... 根本沒(méi)有 FAST_ALLOC ...

#else
// Leaks-incompatible version that steals lots of bits.

...

// summary bit for fast alloc path: !hasCxxCtor and 
//   !instancesRequireRawIsa and instanceSize fits into shiftedSize
#define FAST_ALLOC              (1UL<<50)
// instance size in units of 16 bytes
//   or 0 if the instance size is too big in this field
//   This field must be LAST
#define FAST_SHIFTED_SIZE_SHIFT 51

// FAST_ALLOC means
//   FAST_HAS_CXX_CTOR is set
//   FAST_REQUIRES_RAW_ISA is not set
//   FAST_SHIFTED_SIZE is not zero
// FAST_ALLOC does NOT check FAST_HAS_DEFAULT_AWZ because that 
// bit is stored on the metaclass.
#define FAST_ALLOC_MASK  (FAST_HAS_CXX_CTOR | FAST_REQUIRES_RAW_ISA)
#define FAST_ALLOC_VALUE (0)

#endif

其中的 #elif 1 真是亮瞎狗眼。所以現(xiàn)在使用的 runtime 里根本就沒(méi)有 FAST_ALLOC 這個(gè)玩意……所以現(xiàn)在 canAllocFast 其實(shí)是一個(gè)永遠(yuǎn)返回 false 的函數(shù)了,那我們只需要關(guān)心上面判斷中 else 里的代碼了。

else 里只有 3 行代碼:

  1. id obj = class_createInstance(cls, 0);
  2. if (slowpath(!obj)) return callBadAllocHanlder(cls);
  3. return obj;

很明顯,1 就是創(chuàng)建對(duì)象的調(diào)用,2 用來(lái)進(jìn)行錯(cuò)誤處理。對(duì)于我們現(xiàn)在所關(guān)心的,那就是 class_createInstance 函數(shù)了。在 objc-runtime-new.mm,可以找到它的實(shí)現(xiàn):

id 
class_createInstance(Class cls, size_t extraBytes)
{
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}

可以看到它只是調(diào)用了 _class_createInstanceFromZone,其第三個(gè)參數(shù)是 zone,用來(lái)表示 NSZone,但是 NSZone 已經(jīng)是個(gè)沒(méi)有使用的東西,所以這里直接傳入了 nil。

還是在 objc-runtime-new.mm 中,可以看到 _class_createInstanceFromZone 的實(shí)現(xiàn):

static __attribute__((always_inline)) 
id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, 
                              bool cxxConstruct = true, 
                              size_t *outAllocatedSize = nil)
{
    if (!cls) return nil;

    assert(cls->isRealized());

    // Read class's info bits all at once for performance
    bool hasCxxCtor = cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();

    size_t size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (!zone  &&  fast) {
        obj = (id)calloc(1, size);
        if (!obj) return nil;
        obj->initInstanceIsa(cls, hasCxxDtor);
    } 
    else {
        if (zone) {
            obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
        } else {
            obj = (id)calloc(1, size);
        }
        if (!obj) return nil;

        // Use raw pointer isa on the assumption that they might be 
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (cxxConstruct && hasCxxCtor) {
        obj = _objc_constructOrFree(obj, cls);
    }

    return obj;
}

函數(shù)一開(kāi)始會(huì)對(duì) cls 判斷 nil,如果 clsnil 的話就直接返回 nil,這算是遵循著 Objective-C 中對(duì) nil 發(fā)送消息不會(huì)崩潰的一致性吧。

接下來(lái)的 assert(cls->isRealized());,斷言 cls 是已經(jīng) realize 了,關(guān)于類的 realize 是什么,可以看一下「Objective-C 小記(5)類的加載」,其中有簡(jiǎn)略的介紹。

接下來(lái)的 hasCxxCtorhasCxxDtor 是對(duì) Objective-C++ 的支持,表示這個(gè)類是否有 C++ 類構(gòu)造函數(shù)和析構(gòu)函數(shù),如果有的話,需要進(jìn)行額外的工作。而 fast,是對(duì) isa 的類型的區(qū)分,如果一個(gè)類的實(shí)例不能使用 isa_t 類型的 isa 的話,fast 就為 false,但是在 Objective-C 2.0 中,大部分類都是支持的。關(guān)于 isa 的類型,可以看看「Objective-C 小記(1)Messaging」和「Objective-C 小記(2)對(duì)象 2.0」。

接著要獲得 size,想要?jiǎng)?chuàng)建一個(gè)對(duì)象當(dāng)然要知道它有多大,才能給它分配合適大小的內(nèi)存,size 是通過(guò) cls->instanceSize(extraBytes) 來(lái)獲得的,可以看一下 instanceSize 的實(shí)現(xiàn):

     // May be unaligned depending on class's ivars.
    uint32_t unalignedInstanceSize() {
        assert(isRealized());
        return data()->ro->instanceSize;
    }

    // Class's ivar size rounded up to a pointer-size boundary.
    uint32_t alignedInstanceSize() {
        return word_align(unalignedInstanceSize());
    }

    size_t instanceSize(size_t extraBytes) {
        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        if (size < 16) size = 16;
        return size;
    }

不難看出就是從 clsro 中獲得 instanceSize 然后將它對(duì)齊,并加上 extraBytes,最后 Core Foundation 需要對(duì)象至少要有 16 字節(jié),小于 16 的統(tǒng)統(tǒng)返回 16。

在進(jìn)行了 id obj; 的聲明后,就要真正的創(chuàng)建 obj 這個(gè)對(duì)象了,首先對(duì) zonefast 進(jìn)行判斷,如果沒(méi)有 zone 并且 fast 為真,這是現(xiàn)在最常見(jiàn)的情況了,因?yàn)?zone 肯定是沒(méi)有的,NSZone 已經(jīng)棄用了,fast 幾乎也都是真,在這個(gè)分支里面,obj 首先使用大家都熟悉的 C 標(biāo)準(zhǔn)庫(kù)這套內(nèi)存申請(qǐng)函數(shù)中的 calloc 申請(qǐng)了一個(gè) size 大小的空間,然后使用 initInstanceIsa 進(jìn)行初始化。對(duì)于下面的分支,zone 也肯定還是沒(méi)有的,所以還是會(huì)調(diào)用 obj = (id)calloc(1, size); 申請(qǐng)空間,之后會(huì)調(diào)用 initIsa

inline void 
objc_object::initIsa(Class cls)
{
    initIsa(cls, false, false);
}

initIsa 只是調(diào)用了另一個(gè) initIsa,這個(gè) initIsa 會(huì)在后面講到。

繼續(xù)關(guān)注最常見(jiàn)的 initInstanceIsa 的調(diào)用,它的實(shí)現(xiàn)可以在 objc-object.h 中看到:

inline void 
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    assert(!cls->instancesRequireRawIsa());
    assert(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}

在進(jìn)行了兩個(gè)斷言后,同樣將任務(wù)交給了 initIsa

inline void 
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    assert(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa.cls = cls;
    } else {
        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;
    }
}

函數(shù)一開(kāi)始的 assert(!isTaggedPointer()); 是斷言對(duì)象的指針不是 Tagged Pointer,比如像 NSNumber,它的數(shù)值可以直接存在對(duì)象指針上,對(duì)象指針是一個(gè) Tagged Pointer,但是 NSNumber 是有自己的 +allocWithZone: 的實(shí)現(xiàn)的。因此我個(gè)人也不清楚這個(gè)斷言在這的用處大小了,但這不妨礙我們繼續(xù)看下面的代碼。

接下來(lái)就是對(duì) isa 類型的判斷 if (!nonpointer) { ... } else { ... },如果 isa 不是 nonpointer,也就是單純的指針(Class 類型),則 isa 就直接被賦值為 cls。如果 isanonpointer,也就是 isa_t 類型的話,則先初始化一個(gè)所有位為 0 的指針 isa_t newisa(0)。

關(guān)于 SUPPORT_INDEXED_ISA 宏,它的定義是這樣的:

// Define SUPPORT_INDEXED_ISA=1 on platforms that store the class in the isa 
// field as an index into a class table.
// Note, keep this in sync with any .s files which also define it.
// Be sure to edit objc-abi.h as well.
#if __ARM_ARCH_7K__ >= 2
#   define SUPPORT_INDEXED_ISA 1
#else
#   define SUPPORT_INDEXED_ISA 0
#endif

__ARM_ARCH_7K__ 這個(gè)宏的信息在網(wǎng)上完全找不到,但是我們可以發(fā)現(xiàn)在 Xcode 中,watchOS 的 valid architectures 是 armv7k,所以 __ARM_ARCH_7K__ 應(yīng)該是在 Apple Watch 上的架構(gòu),并且可能它與 Apple Watch 的代數(shù)是有關(guān)系的(第一代和第二代)。因此 SUPPORT_INDEXED_ISA 這個(gè)所謂的 indexed isa,應(yīng)該是對(duì) watchOS 的優(yōu)化(記憶中 Apple 有提及對(duì) watchOS 進(jìn)行過(guò)優(yōu)化,我猜這也是一項(xiàng)了)。

當(dāng)然,以上都只是我的猜測(cè)……

我們現(xiàn)在不關(guān)心 SUPPORT_INDEXED_ISA 里的內(nèi)容,只看 #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;

可以看到,先將 newisabits 賦值為常量 ISA_MAGIC_VALUE,里面包括了 magicnonpointer 的值。然后將是否有 C++ 析構(gòu)函數(shù)標(biāo)示上,最后將位移(shift)后的 cls 存入 shiftcls(類指針按照 8 字節(jié)對(duì)齊,所以最后三位一定是 0,所以可以右移三位來(lái)節(jié)省位的使用)。

最后將 isa = newisa,工作就結(jié)束了。

至此,+alloc 的實(shí)現(xiàn)就告一段落了。

init

NSObject.mm 中,可以找到 -init 的實(shí)現(xiàn):

- (id)init {
    return _objc_rootInit(self);
}

簡(jiǎn)單的調(diào)用了 _objc_rootInit 函數(shù),在同一個(gè)文件中也能找到它的實(shí)現(xiàn):

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;
}

_objc_rootInit 函數(shù)直接就將 obj 返回了,所以 -init 方法其實(shí)什么都沒(méi)有做。

但是開(kāi)發(fā)者留下的注釋非常值得玩味,說(shuō)到很多類沒(méi)有使用 [super init],所以這個(gè)函數(shù)非??坎蛔。ê芸赡懿槐徽{(diào)用)。看起來(lái)應(yīng)該是個(gè)歷史遺留問(wèn)題,從上面對(duì) +alloc 的分析也能看出,+alloc 把所有的工作都做完了(初始化了 isa,我個(gè)人認(rèn)為理論上初始化 isa 應(yīng)該是 -init 的工作)。

總結(jié)

Objective-C 中創(chuàng)建對(duì)象,直白的看就是和 C 是一樣的,使用 calloc 申請(qǐng)內(nèi)存空間,然后對(duì)結(jié)構(gòu)體進(jìn)行初始化,雖然夾雜著很多細(xì)節(jié),但本質(zhì)上就是這樣。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容