iOS的OC類的加載

前言

筆者整理了一系列有關OC的底層文章,但願能夠幫助到你。c++

1.iOS的OC對象建立的alloc原理swift

2.iOS的OC對象的內存對齊數組

3.iOS的OC的isa的底層原理緩存

4.iOS的OC源碼分析之類的結構分析bash

5.iOS的OC的方法緩存的源碼分析app

6.iOS的OC的方法的查找原理函數

7.iOS的OC的方法的決議與消息轉發原理oop

8.iOS的App的加載流程源碼分析

dyld的加載流程中,從dyld源碼過分到objc源碼的過程是在objc_init這個函數。接下來會先介紹objc_initpost

1. objc_init

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    lock_init();
    exception_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
複製代碼

_objc_init函數是在運行時執行到的,下面對裏面的各個函數的簡單介紹。

  • environ_init():讀取影響運行時的環境變量,這些環境變量能夠在Xcode中設置打印出來。
  • tls_init():關於線程的key的綁定。好比線程數據的析構函數。
  • static_init():初始化調用系統的c++的構造函數。
  • lock_init():這個什麼都沒有實現,可能c++層面的鎖也適合oc(只是猜測)。
  • exception_init():異常初始化,監控異常的回調,就是異常出錯會回調在這個函數裏面的_objc_terminate
  • _dyld_objc_notify_register:是dyld加載映射回調到objc的函數,而且這個也是_objc_init函數中最主要的函數。

接下來就是對_dyld_objc_notify_register函數中的map_images來作詳細的介紹,而且類的加載也是在這裏。

1.1 map_images

void
map_images(unsigned count, const char * const paths[],
           const struct mach_header * const mhdrs[])
{
    mutex_locker_t lock(runtimeLock);
    return map_images_nolock(count, paths, mhdrs);
}

void 
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
                  const struct mach_header * const mhdrs[])
{
.....省略部分代碼.......

    // Find all images with Objective-C metadata.
    hCount = 0;

    // Count classes. Size various table based on the total.
    int totalClasses = 0;
    int unoptimizedTotalClasses = 0;
.....省略部分代碼.......
    if (hCount > 0) {
        _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
    }
}
複製代碼

map_images函數中調用map_images_nolock函數,其中_read_images函數是這些函數中最重要的。由函數名稱能夠知道是讀取鏡像文件到內存中。

  • hList:鏡像頭文件的信息列表。
  • hCount:全部的鏡像的元數據的數量。
  • totalClasses:全部類的總數量。
  • unoptimizedTotalClasses:沒有優化的類的總數量

2. _read_images

因爲_read_images代碼過多,只能部分代碼來解析。

if (!doneOnce) {
    doneOnce = YES;
...省略部分代碼..

        if (DisableTaggedPointers) {
            disableTaggedPointers();
        }
        
        initializeTaggedPointerObfuscator();

        if (PrintConnecting) {
            _objc_inform("CLASS: found %d classes during launch", totalClasses);
        }

        // namedClasses
        // Preoptimized classes don't go in this table. // 4/3 is NXMapTable's load factor
        int namedClassesSize = 
            (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
        gdb_objc_realized_classes =
            NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
        
        allocatedClasses = NXCreateHashTable(NXPtrPrototype, 0, nil);
        
        ts.log("IMAGE TIMES: first time tasks");
}


// This is a misnomer: gdb_objc_realized_classes is actually a list of 
// named classes not in the dyld shared cache, whether realized or not.
NXMapTable *gdb_objc_realized_classes;  // exported for debuggers in objc-gdb.h

/***********************************************************************
* allocatedClasses
* A table of all classes (and metaclasses) which have been allocated
* with objc_allocateClassPair.
**********************************************************************/
static NXHashTable *allocatedClasses = nil;
複製代碼

doneOnce只是執行一次,若是是初次進來的就會執行括號裏面的代碼。 initializeTaggedPointerObfuscator()這個函數是對TaggedPointer作優化的。其中gdb_objc_realized_classesallocatedClasses是兩張哈希表,gdb_objc_realized_classes這張表保存的是主要不是共享緩存裏面的類,不管實現了仍是沒有實現的類都在這張表裏面;allocatedClasses這張表保存的是全部被分配內存後的類和元類。從中能夠看出gdb_objc_realized_classes是包含了allocatedClasses的內容。

2.1 全部類的重映射

// Discover classes. Fix up unresolved future classes. Mark bundle classes.
    for (EACH_HEADER) {
        // 從編譯後的類列表中取出全部類,獲取到的是一個classref_t類型的指針
        classref_t *classlist = _getObjc2ClassList(hi, &count);
        
        if (! mustReadClasses(hi)) {
            // Image is sufficiently optimized that we need not call readClass()
            continue;
        }

        bool headerIsBundle = hi->isBundle();
        bool headerIsPreoptimized = hi->isPreoptimized();
        
        for (i = 0; i < count; i++) {
             // 數組中會取出OS_dispatch_queue_concurrent、OS_xpc_object、NSRunloop等系統類,例如CF、Fundation、libdispatch中的類。以及本身建立的類
            Class cls = (Class)classlist[i];
            
            // 經過readClass函數獲取處理後的新類,
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);

            // 初始化全部懶加載的類須要的內存空間 - 如今數據沒有加載到的 - 連類都沒有初始化的
            if (newCls != cls  &&  newCls) {
                // Class was moved but not deleted. Currently this occurs 
                // only when the new class resolved a future class.
                // Non-lazily realize the class below.

                // 將懶加載的類添加到數組中
                resolvedFutureClasses = (Class *)
                    realloc(resolvedFutureClasses, 
                            (resolvedFutureClassCount+1) * sizeof(Class));
                resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
            }
        }
    }

    ts.log("IMAGE TIMES: discover classes");
複製代碼

這段代碼主要是從編譯後的類列表中讀取全部類的classref_t指針,經過遍歷出類地址cls,經過readClass函數讀取編譯器的類和元類信息。

2.1.1 readClass函數
Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
    const char *mangledName = cls->mangledName();
    
    if (missingWeakSuperclass(cls)) {
        // No superclass (probably weak-linked). 
        // Disavow any knowledge of this subclass.
        if (PrintConnecting) {
            _objc_inform("CLASS: IGNORING class '%s' with "
                         "missing weak-linked superclass", 
                         cls->nameForLogging());
        }
        addRemappedClass(cls, nil);
        cls->superclass = nil;
        return nil;
    }
    
    // Note: Class __ARCLite__'s hack does not go through here. // Class structure fixups that apply to it also need to be // performed in non-lazy realization below. // These fields should be set to zero because of the // binding of _objc_empty_vtable, but OS X 10.8's dyld 
    // does not bind shared cache absolute symbols as expected.
    // This (and the __ARCLite__ hack below) can be removed 
    // once the simulator drops 10.8 support.
#if TARGET_OS_SIMULATOR
    if (cls->cache._mask) cls->cache._mask = 0;
    if (cls->cache._occupied) cls->cache._occupied = 0;
    if (cls->ISA()->cache._mask) cls->ISA()->cache._mask = 0;
    if (cls->ISA()->cache._occupied) cls->ISA()->cache._occupied = 0;
#endif
    cls->fixupBackwardDeployingStableSwift();
    Class replacing = nil;
    if (Class newCls = popFutureNamedClass(mangledName)) {
        // This name was previously allocated as a future class.
        // Copy objc_class to future class's struct. // Preserve future's rw data block.
        
        if (newCls->isAnySwift()) {
            _objc_fatal("Can't complete future class request for '%s' "
                        "because the real class is too big.", 
                        cls->nameForLogging());
        }
        
        class_rw_t *rw = newCls->data();
        const class_ro_t *old_ro = rw->ro;
        memcpy(newCls, cls, sizeof(objc_class));
        rw->ro = (class_ro_t *)newCls->data();
        newCls->setData(rw);
        freeIfMutable((char *)old_ro->name);
        free((void *)old_ro);
        
        addRemappedClass(cls, newCls);
        
        replacing = cls;
        cls = newCls;
    }
    
    if (headerIsPreoptimized  &&  !replacing) {
        // class list built in shared cache
        // fixme strict assert doesn't work because of duplicates // assert(cls == getClass(name)); assert(getClassExceptSomeSwift(mangledName)); } else { addNamedClass(cls, mangledName, replacing); addClassTableEntry(cls); } // for future reference: shared cache never contains MH_BUNDLEs if (headerIsBundle) { cls->data()->flags |= RO_FROM_BUNDLE; cls->ISA()->data()->flags |= RO_FROM_BUNDLE; } return cls; } static void addNamedClass(Class cls, const char *name, Class replacing = nil) { runtimeLock.assertLocked(); Class old; if ((old = getClassExceptSomeSwift(name)) && old != replacing) { inform_duplicate(name, old, cls); // getMaybeUnrealizedNonMetaClass uses name lookups. // Classes not found by name lookup must be in the // secondary meta->nonmeta table. addNonMetaClass(cls); } else { NXMapInsert(gdb_objc_realized_classes, name, cls); } assert(!(cls->data()->flags & RO_META)); // wrong: constructed classes are already realized when they get here // assert(!cls->isRealized()); } static void addClassTableEntry(Class cls, bool addMeta = true) { runtimeLock.assertLocked(); // This class is allowed to be a known class via the shared cache or via // data segments, but it is not allowed to be in the dynamic table already. assert(!NXHashMember(allocatedClasses, cls)); if (!isKnownClass(cls)) NXHashInsert(allocatedClasses, cls); if (addMeta) addClassTableEntry(cls->ISA(), false); } 複製代碼

readClass函數中,if (Class newCls = popFutureNamedClass(mangledName))這個判斷的是對將來須要處理的類纔會進入到if條件的流程中,通常的狀況下是不會進入這個流程的。而且這個函數中最主要的仍是執行了addNamedClass(cls, mangledName, replacing);addClassTableEntry(cls);這兩個函數,由源碼能夠知道,addNamedClass函數是將類的名字和地址添加到gdb_objc_realized_classes這個總的哈希表中,addClassTableEntry函數是將類的地址添加到allocatedClasses這張子的哈希表。此時就是將類的地址信息等插入到哈希表中了。從readClass函數返回的Class,再次回到Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);這段代碼,其中在上面的源碼中有newClscls對比的判斷,意思就是若是從readClass函數返回的newCls和獲取到的cls不相等(只有在進入popFutureNamedClass的判斷條件纔會不想等的,由於這裏面對rw中的ro作了處理)。說明此時的newCls與通常的類不同了,以後會執行到以下的源碼:

// Realize newly-resolved future classes, in case CF manipulates them
    if (resolvedFutureClasses) {
        for (i = 0; i < resolvedFutureClassCount; i++) {
            Class cls = resolvedFutureClasses[i];
            if (cls->isSwiftStable()) {
                _objc_fatal("Swift class is not allowed to be future");
            }
            realizeClassWithoutSwift(cls);
            cls->setInstancesRequireRawIsa(false/*inherited*/);
        }
        free(resolvedFutureClasses);
    }    

    ts.log("IMAGE TIMES: realize future classes");
複製代碼

可是通常狀況下是不會執行的。這個是將來須要特殊處理的而已。綜合得出的是在readClass函數中最要是判斷當前的cls是否是後期須要處理的類,若是是就要讀取cls的data()設置ro/rw(通常狀況下不會的),而且將類的地址信息等分別插入到gdb_objc_realized_classesallocatedClasses兩張哈希表中。

2.2 修復類的重映射

// Fix up remapped classes
    // Class list and nonlazy class list remain unremapped.
    // Class refs and super refs are remapped for message dispatching.
    if (!noClassesRemapped()) {
        for (EACH_HEADER) {
            // 重映射Class,注意是從_getObjc2ClassRefs函數中取出類的引用
            Class *classrefs = _getObjc2ClassRefs(hi, &count);
            for (i = 0; i < count; i++) {
                remapClassRef(&classrefs[i]);
            }
            // fixme why doesn't test future1 catch the absence of this? classrefs = _getObjc2SuperRefs(hi, &count); for (i = 0; i < count; i++) { remapClassRef(&classrefs[i]); } } } 複製代碼

這個代碼塊主要是修復類的重映射,就是將未映射的Class和Super Class重映射,其中被remap的類都是非懶加載的類。這個代碼塊通常狀況下是不會被執行到的。

2.3 註冊全部方法的SEL到namedSelectors表

// Fix up @selector references
    static size_t UnfixedSelectors;
    {
        mutex_locker_t lock(selLock);
        for (EACH_HEADER) {
            if (hi->isPreoptimized()) continue;
            
            bool isBundle = hi->isBundle();
            SEL *sels = _getObjc2SelectorRefs(hi, &count);
            UnfixedSelectors += count;
            for (i = 0; i < count; i++) {
                const char *name = sel_cname(sels[i]);
                // 註冊SEL的操做
                sels[i] = sel_registerNameNoLock(name, isBundle);
            }
        }
    }

    ts.log("IMAGE TIMES: fix up selector references");
 //====================
 
SEL sel_registerNameNoLock(const char *name, bool copy) {
    return __sel_registerName(name, 0, copy);  // NO lock, maybe copy
}

static SEL __sel_registerName(const char *name, bool shouldLock, bool copy) 
{
    SEL result = 0;

    if (shouldLock) selLock.assertUnlocked();
    else selLock.assertLocked();

    if (!name) return (SEL)0;

    result = search_builtins(name);
    if (result) return result;
    
    conditional_mutex_locker_t lock(selLock, shouldLock);
    if (namedSelectors) {
        result = (SEL)NXMapGet(namedSelectors, name);
    }
    if (result) return result;

    // No match. Insert.

    if (!namedSelectors) {
        namedSelectors = NXCreateMapTable(NXStrValueMapPrototype, 
                                          (unsigned)SelrefCount);
    }
    if (!result) {
        result = sel_alloc(name, copy);
        // fixme choose a better container (hash not map for starters)
        NXMapInsert(namedSelectors, sel_getName(result), result);
    }

    return result;
}
複製代碼

這段代碼就是將裏面的方法的SEL經過_getObjc2SelectorRefs函數獲取到SEL數組從中獲得方法的名字,而後經過sel_registerNameNoLock函數再次調用__sel_registerName函數,將方法名都註冊到namedSelectors這張哈希表中。

2.3 將全部Protocol註冊到protocol_map表

// Discover protocols. Fix up protocol refs.
    // 遍歷全部協議列表,而且將協議列表加載到Protocol的哈希表中
    for (EACH_HEADER) {
        extern objc_class OBJC_CLASS_$_Protocol;
        // cls = Protocol類,全部協議和對象的結構體都相似,isa都對應Protocol類
        Class cls = (Class)&OBJC_CLASS_$_Protocol;
        assert(cls);
        // 獲取protocol哈希表
        NXMapTable *protocol_map = protocols();
        bool isPreoptimized = hi->isPreoptimized();
        bool isBundle = hi->isBundle();

        // 從編譯器中讀取並初始化Protocol
        protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);
        }
    }

    ts.log("IMAGE TIMES: discover protocols");
複製代碼

2.4 修復舊的函數指針調用遺留

#if !(defined(__x86_64__) && (TARGET_OS_OSX || TARGET_OS_SIMULATOR))
# define SUPPORT_FIXUP 0
#else
# define SUPPORT_FIXUP 1
#endif

#if SUPPORT_FIXUP
    // Fix up old objc_msgSend_fixup call sites
    for (EACH_HEADER) {
        message_ref_t *refs = _getObjc2MessageRefs(hi, &count);
        if (count == 0) continue;

        if (PrintVtables) {
            _objc_inform("VTABLES: repairing %zu unsupported vtable dispatch "
                         "call sites in %s", count, hi->fname());
        }
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }

    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif
複製代碼

這段代碼塊通常狀況下是不會執行的,其中fixupMessageRef函數內部將經常使用的alloc、objc_msgSend等函數指針進行註冊,並fix爲新的函數指針。

2.5 實現非懶加載類

// Realize non-lazy classes (for +load methods and static instances)
    for (EACH_HEADER) {
        classref_t *classlist = 
            _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            // printf("non-lazy Class:%s\n",cls->mangledName());
            if (!cls) continue;

            // hack for class __ARCLite__, which didn't get this above #if TARGET_OS_SIMULATOR if (cls->cache._buckets == (void*)&_objc_empty_cache && (cls->cache._mask || cls->cache._occupied)) { cls->cache._mask = 0; cls->cache._occupied = 0; } if (cls->ISA()->cache._buckets == (void*)&_objc_empty_cache && (cls->ISA()->cache._mask || cls->ISA()->cache._occupied)) { cls->ISA()->cache._mask = 0; cls->ISA()->cache._occupied = 0; } #endif addClassTableEntry(cls); if (cls->isSwiftStable()) { if (cls->swiftMetadataInitializer()) { _objc_fatal("Swift class %s with a metadata initializer " "is not allowed to be non-lazy", cls->nameForLogging()); } // fixme also disallow relocatable classes // We can't disallow all Swift classes because of
                // classes like Swift.__EmptyArrayStorage
            }
            // 實現全部非懶加載的類(實例化類對象的一些信息,例如rw)
            realizeClassWithoutSwift(cls);
        }
    }

    ts.log("IMAGE TIMES: realize non-lazy classes");
複製代碼

所謂的非懶加載類就是實現了+load類方法,在這段源碼中對非懶加載類的bitsdata()裏面的rw操做就是在realizeClassWithoutSwift這個函數裏面。

2.5.1 realizeClassWithoutSwift
static Class realizeClassWithoutSwift(Class cls)
{
    runtimeLock.assertLocked();

    const class_ro_t *ro;
    class_rw_t *rw;
    Class supercls;
    Class metacls;
    bool isMeta;

    if (!cls) return nil;
    if (cls->isRealized()) return cls;
    assert(cls == remapClass(cls));

    // fixme verify class is not in an un-dlopened part of the shared cache?

    ro = (const class_ro_t *)cls->data();
    if (ro->flags & RO_FUTURE) {
        // This was a future class. rw data is already allocated.
        rw = cls->data();
        ro = cls->data()->ro;
        cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
    } else {
        // Normal class. Allocate writeable class data.
        rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1);
        rw->ro = ro;
        rw->flags = RW_REALIZED|RW_REALIZING;
        cls->setData(rw);
    }

    isMeta = ro->flags & RO_META;

    rw->version = isMeta ? 7 : 0;  // old runtime went up to 6


    // Choose an index for this class.
    // Sets cls->instancesRequireRawIsa if indexes no more indexes are available
    cls->chooseClassArrayIndex();

    if (PrintConnecting) {
        _objc_inform("CLASS: realizing class '%s'%s %p %p #%u %s%s",
                     cls->nameForLogging(), isMeta ? " (meta)" : "", 
                     (void*)cls, ro, cls->classArrayIndex(),
                     cls->isSwiftStable() ? "(swift)" : "",
                     cls->isSwiftLegacy() ? "(pre-stable swift)" : "");
    }

    // Realize superclass and metaclass, if they aren't already. // This needs to be done after RW_REALIZED is set above, for root classes. // This needs to be done after class index is chosen, for root metaclasses. // This assumes that none of those classes have Swift contents, // or that Swift's initializers have already been called.
    //   fixme that assumption will be wrong if we add support
    //   for ObjC subclasses of Swift classes.
    supercls = realizeClassWithoutSwift(remapClass(cls->superclass));
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()));

#if SUPPORT_NONPOINTER_ISA
    // Disable non-pointer isa for some classes and/or platforms.
    // Set instancesRequireRawIsa.
    bool instancesRequireRawIsa = cls->instancesRequireRawIsa();
    bool rawIsaIsInherited = false;
    static bool hackedDispatch = false;

    if (DisableNonpointerIsa) {
        // Non-pointer isa disabled by environment or app SDK version
        instancesRequireRawIsa = true;
    }
    else if (!hackedDispatch  &&  !(ro->flags & RO_META)  &&  
             0 == strcmp(ro->name, "OS_object")) 
    {
        // hack for libdispatch et al - isa also acts as vtable pointer
        hackedDispatch = true;
        instancesRequireRawIsa = true;
    }
    else if (supercls  &&  supercls->superclass  &&  
             supercls->instancesRequireRawIsa()) 
    {
        // This is also propagated by addSubclass() 
        // but nonpointer isa setup needs it earlier.
        // Special case: instancesRequireRawIsa does not propagate 
        // from root class to root metaclass
        instancesRequireRawIsa = true;
        rawIsaIsInherited = true;
    }
    
    if (instancesRequireRawIsa) {
        cls->setInstancesRequireRawIsa(rawIsaIsInherited);
    }
// SUPPORT_NONPOINTER_ISA
#endif

    // Update superclass and metaclass in case of remapping
    cls->superclass = supercls;
    cls->initClassIsa(metacls);

    // Reconcile instance variable offsets / layout.
    // This may reallocate class_ro_t, updating our ro variable.
    if (supercls  &&  !isMeta) reconcileInstanceVariables(cls, supercls, ro);

    // Set fastInstanceSize if it wasn't set already. cls->setInstanceSize(ro->instanceSize); // Copy some flags from ro to rw if (ro->flags & RO_HAS_CXX_STRUCTORS) { cls->setHasCxxDtor(); if (! (ro->flags & RO_HAS_CXX_DTOR_ONLY)) { cls->setHasCxxCtor(); } } // Propagate the associated objects forbidden flag from ro or from // the superclass. if ((ro->flags & RO_FORBIDS_ASSOCIATED_OBJECTS) || (supercls && supercls->forbidsAssociatedObjects())) { rw->flags |= RW_FORBIDS_ASSOCIATED_OBJECTS; } // Connect this class to its superclass's subclass lists
    if (supercls) {
        addSubclass(supercls, cls);
    } else {
        addRootClass(cls);
    }

    // Attach categories
    methodizeClass(cls);

    return cls;
}
複製代碼

這部分的源碼就是經過cls->data()獲得ro,由於if (ro->flags & RO_FUTURE)這個判斷條件裏面的代碼通常狀況下是不會執行的,因此只會執行else裏面的,在else代碼塊裏面只是初始化rw,將其set到data()裏面而已,此時rw裏面的method_array_t methodsproperty_array_t propertiesprotocol_array_t protocols仍是沒有值的。繼續往下是

supercls = realizeClassWithoutSwift(remapClass(cls->superclass));
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()));
複製代碼

此時就是對父類元類的類信息進行遞歸,此時就能夠參考一下isa的走位圖就能夠很明白此時的遞歸了。在下面的代碼插入到繼承鏈和isa的走位鏈

// Update superclass and metaclass in case of remapping
    cls->superclass = supercls;
    cls->initClassIsa(metacls);
複製代碼

而且遞歸的結束點是在函數開始的地方

if (!cls) return nil;
    if (cls->isRealized()) return cls;
複製代碼

由於最終的父類的根類是繼承NSObject,元類的根元類是也是繼承NSObject,而NSObject的上一級終點是nil。這裏就很好地說明了這一切。

// Connect this class to its superclass's subclass lists if (supercls) { addSubclass(supercls, cls); } else { addRootClass(cls); } 複製代碼

上面這段代碼就是對父類和子類之間進行相似雙向鏈表的形式進行關聯。接着就是執行methodizeClass函數了。

2.5.2 methodizeClass函數
static void methodizeClass(Class cls)
{
    runtimeLock.assertLocked();

    bool isMeta = cls->isMetaClass();
    auto rw = cls->data();
    auto ro = rw->ro;

    // Methodizing for the first time
    if (PrintConnecting) {
        _objc_inform("CLASS: methodizing class '%s' %s", 
                     cls->nameForLogging(), isMeta ? "(meta)" : "");
    }

    // Install methods and properties that the class implements itself.
    method_list_t *list = ro->baseMethods();
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
        rw->methods.attachLists(&list, 1);
    }

    property_list_t *proplist = ro->baseProperties;
    if (proplist) {
        rw->properties.attachLists(&proplist, 1);
    }

    protocol_list_t *protolist = ro->baseProtocols;
    if (protolist) {
        rw->protocols.attachLists(&protolist, 1);
    }

    // Root classes get bonus method implementations if they don't have // them already. These apply before category replacements. if (cls->isRootMetaclass()) { // root metaclass addMethod(cls, SEL_initialize, (IMP)&objc_noop_imp, "", NO); } // Attach categories. category_list *cats = unattachedCategoriesForClass(cls, true /*realizing*/); attachCategories(cls, cats, false /*don't flush caches*/);

    if (PrintConnecting) {
        if (cats) {
            for (uint32_t i = 0; i < cats->count; i++) {
                _objc_inform("CLASS: attached category %c%s(%s)", 
                             isMeta ? '+' : '-', 
                             cls->nameForLogging(), cats->list[i].cat->name);
            }
        }
    }
    
    if (cats) free(cats);

#if DEBUG
    // Debug: sanity-check all SELs; log method list contents
    for (const auto& meth : rw->methods) {
        if (PrintConnecting) {
            _objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(meth.name));
        }
        assert(sel_registerName(sel_getName(meth.name)) == meth.name); 
    }
#endif
}
複製代碼

methodizeClass函數中能夠看到,此時從cls->data()獲取到的rw裏面的method_list_t,property_list_tprotocol_list_t的值仍是空的。須要從rw中的ro獲取到它們的值,並分別對rw中的methods,propertiesprotocols進行賦值,這個時候纔是真正的對rw裏面的屬性進行賦值。這些操做都是經過attachLists函數來完成的。

2.5.3 attachLists函數
void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return;

        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;//10
            uint32_t newCount = oldCount + addedCount;//4
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
            array()->count = newCount;// 10+4
   
            memmove(array()->lists + addedCount, array()->lists,
                    oldCount * sizeof(array()->lists[0]));
            
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
        } 
        else {
            // 1 list -> many lists
            List* oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount;
            setArray((array_t *)malloc(array_t::byteSize(newCount)));
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList;
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
    }
複製代碼

從源碼能夠看到,這個attachLists函數中分別有多對多0對11對多這三種狀況。

其中,memmove和memcpy函數做用都是拷貝必定長度的內存內容。當內存發生局部重疊時memmove函數可以保證拷貝結果的正確性,而memcpy則不能保證拷貝結果的正確性;當內存沒有發生重疊的時候兩個函數的結果是同樣的。

  • 多對多:先對數組進行擴容,用memmove函數將舊的數組列表添加到擴容後的數組中(memmove能夠去掉重疊的內存),而後用memcpy函數將須要添加的列表添加在舊的列表的前面。因此新添加的列表是在舊的列表的前面的。
  • 0對1:直接對列表賦值了。
  • 1對多:先判斷舊數組是否有值,若是有數組的長度也只是1,而後進行擴容,在舊數組有值的狀況下,將舊數組放到新擴容數組最後的下標值保存,而後用memcpy函數進行拷貝。

其中attachLists函數除了在加載類處理方法,屬性和協議的時候會被調用,還在添加方法addMethods函數中,添加屬性_class_addProperty,添加協議class_addProtocol和分類的加載attachCategories中都會被調用。

2.6 懶加載類的實現

懶加載類和非懶加載類的主要區別就是是否實現了+load方法,上面介紹了非懶加載類,那麼懶加載類是怎麼實現的呢?其實懶加載類就是在調用的時候才實現的,那麼這就是在該類第一次調用方法的時候會被初始化加載進來,這個時候就須要去到lookUpImpOrForward這個函數裏面了。若是想了解這個函數的能夠看一下iOS的OC的方法的查找原理 這篇文章的介紹。其中有這麼一段源碼

if (!cls->isRealized()) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }
  ================================ 
    static Class
realizeClassMaybeSwiftAndLeaveLocked(Class cls, mutex_t& lock)
{
    return realizeClassMaybeSwiftMaybeRelock(cls, lock, true);
}

static Class
realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
{
    lock.assertLocked();

    if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
        // Non-Swift class. Realize it now with the lock still held.
        // fixme wrong in the future for objc subclasses of swift classes
        realizeClassWithoutSwift(cls);
        if (!leaveLocked) lock.unlock();
    } else {
        // Swift class. We need to drop locks and call the Swift
        // runtime to initialize it.
        lock.unlock();
        cls = realizeSwiftClass(cls);
        assert(cls->isRealized());    // callback must have provoked realization
        if (leaveLocked) lock.lock();
    }

    return cls;
}

複製代碼

從源碼中能夠看到,在方法查找的過程當中,若是當前的cls沒有實現的話,就會執行realizeClassMaybeSwiftAndLeaveLocked函數,最終會執行到realizeClassMaybeSwiftMaybeRelock函數中。在這個函數中分別有Non-Swift classSwift class的判斷,當前的是OC的類,最終仍是會執行到realizeClassWithoutSwift函數,而這個函數在上面也介紹了是對rw和ro的操做的。

3. 最後

經過上面的一系列源碼的分析了類的加載整個過程,接下來總結一下:

  • dyld加載過程當中,從dyld過分到objc是在_objc_init函數中_dyld_objc_notify_register函數回調回來的。
  • 經過_read_images函數讀取鏡像文件的內容到內存中,在而且在這個過程當中若是是初次進入會分別初始化gdb_objc_realized_classesallocatedClasses兩張哈希表,其中加載全部的類在gdb_objc_realized_classes表中,分配內存的類也會在allocatedClasses表中。
  • 對全部的類作重映射。
  • 將全部的SEL都註冊到namedSelectors表中。
  • 修復函數指針遺留。
  • 將全部Protocol註冊到protocol_map表。
  • 對全部的Protocol作重映射。
  • 初始化全部的非懶加載類,進行rwro操做。
  • 遍歷已標記的懶加載類,並作初始化操做。
  • 處理全部的Category,包括ClassMetaClass
相關文章
相關標籤/搜索