Objective-C 小記(6)alloc & init

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

+alloc-init 是我們經常使用的兩個方法,通常它們也是以 [[SomeClass alloc] init] 這個形式出現的,本篇文章對它們的實現做一點記錄。

alloc

NSObject.mm 中,可以找到 +alloc 的實現:

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

+alloc 的實現就是簡單的將事情甩給了 _objc_rootAlloc,接著看 _objc_rootAlloc 的實現:

// 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 也是一個甩鍋俠,將鍋甩給了 callAlloc,繼續看 callAlloc 的實現:

// 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 起的是優化性能的作用,表示分支預測時第一個參數較大概率會是第二個參數,所以 fastpath(x) 表示 x 較大概率為真,slowpath(x) 表示 x 較大概率為假,返回值就是 x 本身。

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

接下來從 #if __OBJC2__ 開始至 #endif,都是在 Objective-C 2.0 下才會有的代碼,那當然是我們需要關注的地方了,畢竟我們現在使用的就是 Objective-C 2.0。

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

繼續關注默認實現,接下來進行判斷 if (fastpath(cls->canAllocFast())) { ... } else { ... }。首先關于 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 中,可以看到有關 FAST_ALLOC 的定義:

#if !__LP64__

...

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

... 根本沒有 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 真是亮瞎狗眼。所以現在使用的 runtime 里根本就沒有 FAST_ALLOC 這個玩意……所以現在 canAllocFast 其實是一個永遠返回 false 的函數了,那我們只需要關心上面判斷中 else 里的代碼了。

else 里只有 3 行代碼:

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

很明顯,1 就是創建對象的調用,2 用來進行錯誤處理。對于我們現在所關心的,那就是 class_createInstance 函數了。在 objc-runtime-new.mm,可以找到它的實現:

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

可以看到它只是調用了 _class_createInstanceFromZone,其第三個參數是 zone,用來表示 NSZone,但是 NSZone 已經是個沒有使用的東西,所以這里直接傳入了 nil

還是在 objc-runtime-new.mm 中,可以看到 _class_createInstanceFromZone 的實現:

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

函數一開始會對 cls 判斷 nil,如果 clsnil 的話就直接返回 nil,這算是遵循著 Objective-C 中對 nil 發送消息不會崩潰的一致性吧。

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

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

接著要獲得 size,想要創建一個對象當然要知道它有多大,才能給它分配合適大小的內存,size 是通過 cls->instanceSize(extraBytes) 來獲得的,可以看一下 instanceSize 的實現:

     // 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 然后將它對齊,并加上 extraBytes,最后 Core Foundation 需要對象至少要有 16 字節,小于 16 的統統返回 16。

在進行了 id obj; 的聲明后,就要真正的創建 obj 這個對象了,首先對 zonefast 進行判斷,如果沒有 zone 并且 fast 為真,這是現在最常見的情況了,因為 zone 肯定是沒有的,NSZone 已經棄用了,fast 幾乎也都是真,在這個分支里面,obj 首先使用大家都熟悉的 C 標準庫這套內存申請函數中的 calloc 申請了一個 size 大小的空間,然后使用 initInstanceIsa 進行初始化。對于下面的分支,zone 也肯定還是沒有的,所以還是會調用 obj = (id)calloc(1, size); 申請空間,之后會調用 initIsa

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

initIsa 只是調用了另一個 initIsa,這個 initIsa 會在后面講到。

繼續關注最常見的 initInstanceIsa 的調用,它的實現可以在 objc-object.h 中看到:

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

    initIsa(cls, true, hasCxxDtor);
}

在進行了兩個斷言后,同樣將任務交給了 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;
    }
}

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

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

關于 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__ 這個宏的信息在網上完全找不到,但是我們可以發現在 Xcode 中,watchOS 的 valid architectures 是 armv7k,所以 __ARM_ARCH_7K__ 應該是在 Apple Watch 上的架構,并且可能它與 Apple Watch 的代數是有關系的(第一代和第二代)。因此 SUPPORT_INDEXED_ISA 這個所謂的 indexed isa,應該是對 watchOS 的優化(記憶中 Apple 有提及對 watchOS 進行過優化,我猜這也是一項了)。

當然,以上都只是我的猜測……

我們現在不關心 SUPPORT_INDEXED_ISA 里的內容,只看 #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++ 析構函數標示上,最后將位移(shift)后的 cls 存入 shiftcls(類指針按照 8 字節對齊,所以最后三位一定是 0,所以可以右移三位來節省位的使用)。

最后將 isa = newisa,工作就結束了。

至此,+alloc 的實現就告一段落了。

init

NSObject.mm 中,可以找到 -init 的實現:

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

簡單的調用了 _objc_rootInit 函數,在同一個文件中也能找到它的實現:

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 函數直接就將 obj 返回了,所以 -init 方法其實什么都沒有做。

但是開發者留下的注釋非常值得玩味,說到很多類沒有使用 [super init],所以這個函數非常靠不住(很可能不被調用)。看起來應該是個歷史遺留問題,從上面對 +alloc 的分析也能看出,+alloc 把所有的工作都做完了(初始化了 isa,我個人認為理論上初始化 isa 應該是 -init 的工作)。

總結

Objective-C 中創建對象,直白的看就是和 C 是一樣的,使用 calloc 申請內存空間,然后對結構體進行初始化,雖然夾雜著很多細節,但本質上就是這樣。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容