iOS底層探索之map_images

在上一篇文章 objc_init 分析 中,最後有三個函數 map_imagesload_imagesunmap_image

一、map_images

/***********************************************************************
* map_images
* Process the given images which are being mapped in by dyld.
* Calls ABI-agnostic code after taking ABI-specific locks.
*
* Locking: write-locks runtimeLock
**********************************************************************/
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);
}
1.1 map_images_nolock
void 
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
                  const struct mach_header * const mhdrs[])
{
    // 省略準備邏輯...

    if (hCount > 0) {
        _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
    }

    firstTime = NO;
    
    // Call image load funcs after everything is set up.
    for (auto func : loadImageFuncs) {
        for (uint32_t i = 0; i < mhCount; i++) {
            func(mhdrs[i]);
        }
    }
}

因爲代碼比較多,省略了很多代碼,瀏覽代碼後,會發現重要的是 _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses); 這一行代碼。

二、_read_images

因爲源碼比較長,這裏就不貼了。

void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
    // 省略代碼...

    // Discover classes. Fix up unresolved future classes. Mark bundle classes.
    bool hasDyldRoots = dyld_shared_cache_some_image_overridden();

    for (EACH_HEADER) {
        if (! mustReadClasses(hi, hasDyldRoots)) {
            // Image is sufficiently optimized that we need not call readClass()
            continue;
        }

        classref_t const *classlist = _getObjc2ClassList(hi, &count);

        bool headerIsBundle = hi->isBundle();
        bool headerIsPreoptimized = hi->hasPreoptimizedClasses();

        for (i = 0; i < count; i++) {
            // 斷點1
            Class cls = (Class)classlist[i];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);  // 讀取類
        }
    }
    // 省略 protocol 處理...

    // Realize non-lazy classes (for +load methods and static instances) 
    // 實現非惰性類(用於+ load方法和靜態實例)
    for (EACH_HEADER) {
        classref_t const *classlist = 
            _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;

            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
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }
}

主要流程如下:

  1. 條件控制進行一次的加載
  2. 修復預編譯階段的 @selector 的混亂問題
  3. 錯誤混亂的類處理
  4. 修復重映射⼀些沒有被鏡像⽂件加載進來的類
  5. 修復⼀些消息
  6. 當我們類⾥⾯有協議的時候 : readProtocol
  7. 修復沒有被加載的協議
  8. 分類處理
  9. 類的加載處理
  10. 沒有被處理的類 優化那些被侵犯的類

在上面代碼中 斷點1 打個斷點,運行

(lldb) po cls
0x000000010048dfe8
--- 走過斷點1和readClass之後再打印
(lldb) po newCls
OS_dispatch_io

在沒有 readClass 之前,classlist 裏面存的還是內存地址,readClass 之後,就有名字了。下面看下 readClass 具體做了什麼?

2.1 readClass

讀取編譯器編寫的類和元類。返回新的類指針。

Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
    const char *mangledName = cls->mangledName();
    
    if (missingWeakSuperclass(cls)) {
        // 省略...
    }
    
    cls->fixupBackwardDeployingStableSwift();

    Class replacing = nil;
    if (Class newCls = popFutureNamedClass(mangledName)) {
        // 省略...
    }
    
    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;
}

mangleName 打個斷點

發現是系統的類。我們還是研究自定義類 GLPerson,在mangleName 下面添加如下代碼:

    // godlong test begin
    const char *GLPersonName = "GLPerson";
    if (strcmp(mangledName, GLPersonName) == 0) {
        printf("%s 來到了自定義類 %s", __func__, mangledName);
    }
    // godlong test end

斷點到 if 條件裏面,運行工程,成功進入斷點

2.2 addNamedClass

走到 addNamedClass 斷點查看

可以發現這時 cls 還是地址,而 mangledName 就是我們的類名。

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

解釋將類的名稱添加到非元類的類映射表中。警告有關重複的類名,並保留舊的映射

2.3 addClassTableEntry
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.
    auto &set = objc::allocatedClasses.get();

    ASSERT(set.find(cls) == set.end());

    if (!isKnownClass(cls))
        set.insert(cls);
    if (addMeta)
        addClassTableEntry(cls->ISA(), false);
}

解釋 : 將一個類添加到所有類的表中。如果 addMetatrue,也自動添加該類的元類

三、realizeClassWithoutSwift

先重點關注的加載,在 read_images 的源碼中,往下看的時候,發現註釋

Realize non-lazy classes (for +load methods and static instances)
【譯】實現非懶加載類(用於+ load方法和靜態實例)

那什麼是 non-lazy classes 呢?

3.1 non-lazy classes 非懶加載類

如果一個類實現了 + load 方法,那這個類就是 non-lazy class(非懶加載類)。

反之,沒實現 + load 方法,就是懶加載類。

3.2 進入自定義類的 realizeClassWithoutSwift

GLPerson 類添加 + load 方法,然後把 for(EACH_HEADER) 循環裏面的代碼改成如下:

    // Realize non-lazy classes (for +load methods and static instances)
    for (EACH_HEADER) {
        classref_t const *classlist = 
            _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;
            
            // loong test begin
            const char *mangledName = cls->mangledName();
            const char *GLPersonName = "GLPerson";
            if (strcmp(mangledName, GLPersonName) == 0) {
                printf("%s 來到了自定義類 %s", __func__, mangledName); // 斷點2
            }
            // loong test end

            addClassTableEntry(cls);
            // class is a Swift class from the stable Swift ABI 所以不會走這裏
            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
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }

斷點到上面代碼的 斷點2,確認來到了自定義類 GLPerson

3.3【重點】realizeClassWithoutSwift 源碼

realizeClassWithoutSwift 雖然很長,但是都比較重要,所以也沒有省略,全貼出來了。

方法註釋:

  • Performs first-time initialization on class cls,
  • including allocating its read-write data.
  • Does not perform any Swift-side initialization.
  • Returns the real class structure for the class.
    【譯】* 對類 cls 進行首次初始化,包括分配其讀寫數據。不執行任何 Swift 端初始化。返回該類的真實類結構。
static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    class_rw_t *rw; // 讀寫數據
    Class supercls; // 父類
    Class metacls;  // 元類

    if (!cls) return nil; // 如果爲空,返回nil
    if (cls->isRealized()) return cls;  // 如果已經實現,直接返回
    ASSERT(cls == remapClass(cls));

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

    auto ro = (const class_ro_t *)cls->data(); // 讀取類的數據
    auto isMeta = ro->flags & RO_META; // 是否是元類
    if (ro->flags & RO_FUTURE) { // rw已經有值的話走這裏
        // This was a future class. rw data is already allocated.
        rw = cls->data();
        ro = cls->data()->ro();
        ASSERT(!isMeta);
        cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
    } else { // 正常的類走這裏
        // Normal class. Allocate writeable class data.
        rw = objc::zalloc<class_rw_t>(); // 開闢rw
        rw->set_ro(ro); // 把cls的數據ro賦值給rw
        rw->flags = RW_REALIZED|RW_REALIZING|isMeta; // 更新flags
        cls->setData(rw); // 再把rw設置爲cls的data數據
    }

#if FAST_CACHE_META
    if (isMeta) cls->cache.setBit(FAST_CACHE_META);
#endif

    // 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.
    //對於根類,需要在上面設置了RW_REALIZED之後執行此操作。
    // 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.
    // 遞歸調用 realizeClassWithoutSwift ,實現父類和元類
    supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);

#if SUPPORT_NONPOINTER_ISA
    if (isMeta) { // 如果是元類,對isa處理
        // Metaclasses do not need any features from non pointer ISA
        // This allows for a faspath for classes in objc_retain/objc_release.
        cls->setInstancesRequireRawIsa();
    } else { // 不是元類,也是對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  &&  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->setInstancesRequireRawIsaRecursively(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
    // 賦值一些 ro 中的 flags標識位 到 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.
    // 從ro或父類傳播關聯的對象禁止標誌。
    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, previously);

    return cls;
}

確認是 GLPerson 的時候進入 realizeClassWithoutSwift
,在 auto ro = (const class_ro_t *)cls->data(); 這行代碼打一個端點,這一步是 cls 讀取 data 數據賦值給 ro

然後往下走一步,看看讀取到了什麼數據?

3.4 遞歸調用 realizeClassWithoutSwift
    supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);

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

realizeClassWithoutSwift 的源碼中,遞歸調用了 realizeClassWithoutSwift,分別傳入的是父類和元類(ISA())。

這是爲了確定繼承鏈的關係。

3.5 懶加載類

知道了非懶加載類在 map_images 時,調用 realizeClassWithoutSwift 實現的,那懶加載類是什麼時候實現的呢?

還是上面的代碼,把 GLPerson 中的 + load 方法去掉,然後再realizeClassWithoutSwift 方法裏面添加如下代碼並斷點在 斷點3

static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    class_rw_t *rw;
    Class supercls;
    Class metacls;
    
    // loong test begin
    if (cls) {
        const char *mangledName = cls->mangledName();
        const char *GLPersonName = "GLPerson";
        if (strcmp(mangledName, GLPersonName) == 0) {
            printf("%s 來到了自定義類 %s", __func__, mangledName); // 斷點3
        }
    }
    // loong test end
    // 省略...
}

main.m 中添加,並添加斷點

        GLPerson *p = [GLPerson alloc];

運行工程,首先斷點在 GLPerson *p = [GLPerson alloc];

繼續運行,發現走到了 斷點3。查看堆棧

可知:懶加載類 是在第一次發送消息的時候,調用 realizeClassWithoutSwift 實現類的。

3.6 懶加載類的優點

因爲正常的工程中,實現 + load 方法的類很少,大部分類都是懶加載類。

如果所有的類都在啓動的時候實現完成,就會非常慢,懶加載類等到調用的時候再去實現,這樣會加快啓動速度。

再就是每個類都有很多的代碼,包括變量,方法等,會佔用很多內存,而如果你這個類在工程中就沒調用,或者在很深的頁面纔會調用,正常情況下很少人會使用到,如果在啓動加載了,就會造成內存浪費。

懶加載類優點:

  • 加快啓動速度
  • 節省應用初始內存

四、methodizeClass 附加分類

作用:修復 cls 的方法列表,協議列表和屬性列表。附加任何未解決的分類。

源碼:

static void methodizeClass(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    bool isMeta = cls->isMetaClass();
    auto rw = cls->data();
    auto ro = rw->ro(); // 讀取ro數據
    auto rwe = rw->ext(); // 讀取ext,賦值給rwe

    // 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(); // 獲取ro中的方法列表
    if (list) {
        // 對方法列表list重新排序
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
        if (rwe) rwe->methods.attachLists(&list, 1); // 如果有rwe,添加方法列表list到rwe的methodsList
    }

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

    protocol_list_t *protolist = ro->baseProtocols;
    if (rwe && protolist) {
        rwe->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 根元類添加initialize方法
        addMethod(cls, @selector(initialize), (IMP)&objc_noop_imp, "", NO);
    }

    // Attach categories. 附加分類
    if (previously) {
        if (isMeta) {
            objc::unattachedCategories.attachToClass(cls, previously,
                                                     ATTACH_METACLASS);
        } else {
            // When a class relocates, categories with class methods
            // may be registered on the class itself rather than on
            // the metaclass. Tell attachToClass to look for those.
            objc::unattachedCategories.attachToClass(cls, previously,
                                                     ATTACH_CLASS_AND_METACLASS);
        }
    }
    objc::unattachedCategories.attachToClass(cls, cls,
                                             isMeta ? ATTACH_METACLASS : ATTACH_CLASS);

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章