OC的底层原理11之objc初始化

444 阅读11分钟

本章内容

  1. objc初始化的时候都做了什么
  2. map_images的分析
  3. load_images的分析

本章目的

了解从dyld到objc后,objc都做了什么,此过程也是pre-main的过程。我们已经从dyld的加载过程知道了objc最关键的两个函数执行。但是不清楚这两个函数具体的内容是什么。本章中最主要的需要了解map_images函数

objc_init源码 分析

该方法可以算是objc的开始地方, 里面包含了各种初始化。以及沟通dyld的执行回调。请看源码注释,先了解大概,然后一个一个方法进行剖析,只分析前面几个就行了,其他都不怎么重要

void _objc_init(void)
{
    // 保证初始化方法只执行一次
    static bool initialized = false;

    if (initialized) return;

    initialized = true;


    // fixme defer initialization until an objc-using image is found?
    // 读取影响运行时的环境变量,例如,我们可以根据这个方法打印出那些关键key
    environ_init();
    // 关于线程key的锁定,tls(thread_local_storage)。例如,每个线程数据的析构函数
    tls_init();
    // 运行c++静态构造函数。在dyld调用之前,objc自己调用其构造函数
    static_init();
    // 运行时环境初始化,主要是建表
    runtime_init();
    // 异常处理初始化
    exception_init();

#if __OBJC2__
    // 缓存条件初始化
    cache_t::init();

#endif
    // 启动回调机制,通常不做什么,因为所有初始化都是惰性的
    // 但对于某些进程,我们要立马加载trampoline dylib
    _imp_implementationWithBlock_init();
    // 注册dyld与objc的通知,&map_images,加一个&符号是代表同步进行
    // map_images是很耗时的操作,而映射镜像是很重要的必须保证dyld与objc的函数指针同步
    _dyld_objc_notify_register(&map_images, load_images, unmap_image);


#if __OBJC2__

    didCallDyldNotifyRegister = true;

#endif

}

environ_init 分析

源码就不再发出来,有兴趣自行查看,在这个方法我们可以打印出相关的环境变量。用于控制台输出,设置方式如下:Edit Scheme -> Run -> Arguments -> Environment Variables

至于打印其影响环境变量的方式有两种:

  1. 运行源码环境,并且把这个代码的条件语句删除。

image.png 2. 终端输入export OBJC_HELP=1

image.png

举例说明

例如关键字OBJC_PRINT_LOAD_METHODS效果就是打印出所有的load方法,或者OBJC_PRINT_INITIALIZE_METHODS是打印initialize方法,你只要按照上面的进行查看就会有其备注

image.png image.png

tls_init 分析

这个方法,没什么看的,源码就是根据条件语句执行一个方法而已,pthread_key_init_np就是为了TLS_DIRECT_KEY设置析构函数。我们不必关心这个函数,或许以后会说关于tls的内容,但不是现在

void tls_init(void)
{
    // 其实就是走这个方法,看宏定义是存在 __PTK_FRAMEWORK_OBJC_KEY0这个key的
#if SUPPORT_DIRECT_THREAD_KEYS
    pthread_key_init_np(TLS_DIRECT_KEY, &_objc_pthread_destroyspecific);

#else
    _objc_pthread_key = tls_create(&_objc_pthread_destroyspecific);
#endif

}

static_init 分析

苹果给我们的这个函数的注释是:运行c++静态构造函数,libc在dyld调用静态构造函数之前调用_objc_init(),所以我们必须自己做。 而从objc源码调试的时候也已经证明了一个顺序,c++函数是在load方法之前调用的。注意,我说的意思C++构造函数是在objc源码中,如果说是我们实际开发的时候是不可能写在源码中的。所以实际开发中顺序是先load调用再是c++(此时的c++是dyld发起的)例如:

image.png image.png 其结果是

image.png

runtime_init 分析

这是运行时做准备,也就是运行时的初始化。我们都知道runtime维护了几张表,其中这个初始化就是表的创建。其本质都是类ExplicitInit。这只是其中两张表,类表(全局的所有已加载或未加载的类)没有在这里创建

void runtime_init(void)
{
    // 创建分类的表
    objc::unattachedCategories.init(32);
    // 创建已分配的类、元类的表
    objc::allocatedClasses.init();
}

map_images 镜像文件加载分析

这个函数为什么这么重要,我们知道,编译时(1. LLVM去分配mach-o的东西,其中包括ro的数据分配,这些跟我们没什么关系,因为ro是已经加载好的数据不能够更改存放在磁盘中)我们就已经确定了我们项目工程里面创建的类,方法等等内存大小且分配好地址(其实不完全正确,因为当有load方法的时候就有可能打破这种格局,在类的加载里面会描述)在mach-o里面了。启动后dyld(2. 将mach-o的文件去加载,可以看上一篇内容)去链接镜像文件,初始化主程序等等内容并去勾起objc的初始化。而在这个函数中,又做了什么,需要看源码去研究。我们直接看函数map_images_nolock,因为map_images就是去调用它,其实map_images_nolock也不怎么重要

map_images_nolock

了解一下,去创建了几张表,一个是关联对象的表初始化,一个是散列表(用来存储引用计数、弱引用,相当于包含了,引用计数表,和弱引用表)初始化,AutoreleasePoolPage表初始化(这几张表是runtime去维护的),当然后面也会创建一个类表。这个函数其实不怎么重要,真正重要的就是_read_images函数,这个函数你也可以当做中间过渡流程。下面的源码,我能备注的都备注,你不需要了解这个函数的任何东西,么意义

void map_images_nolock(unsigned mhCount, const char * const mhPaths[], const struct mach_header * const mhdrs[])
{
    // 第一次进来,一直到镜像文件被读取才行
    static bool firstTime = YES;
    header_info *hList[mhCount];
    // 这个是所有mach-o里面我们项目中的镜像文件的数量
    uint32_t hCount;
    //下面代码就是统计mach-o里面的各种数量,sel,message等等
    size_t selrefCount = 0;

    // Perform first-time initialization if necessary.
    // This function is called before ordinary library initializers. 
    // fixme defer initialization until an objc-using image is found?
    if (firstTime) {
    //做了一些初始化,我们记得共享缓存那些东西,它里面就是获取共享缓存占用的内存区域然后做了一些操作,也搞了一些我们上面介绍过的环境变量等等去进行控制,对我们没什么意义
        preopt_init();

    }
    //这个也是环境变量,如果我们设置的话就会打印一些东西,像这种我不再备注
    if (PrintImages) {
        _objc_inform("IMAGES: processing %u newly-mapped images...\n", mhCount);

    }
    // Find all images with Objective-C metadata.

    hCount = 0;
    // Count classes. Size various table based on the total.
    int totalClasses = 0;
    int unoptimizedTotalClasses = 0;
    {
        uint32_t i = mhCount;
        while (i--) {
        //你可以理解为mach-o的header,也就是头,都是通过这样方式访问mach-o
            const headerType *mhdr = (const headerType *)mhdrs[i];
            auto hi = addHeader(mhdr, mhPaths[i], totalClasses, unoptimizedTotalClasses);
            if (!hi) {
                // no objc data in this entry
                continue;
            }
            if (mhdr->filetype == MH_EXECUTE) {
                // Size some data structures based on main executable's size
#if __OBJC2__
                // If dyld3 optimized the main executable, then there shouldn't
                // be any selrefs needed in the dynamic map so we can just init
                // to a 0 sized map
                // 这里不重要,就是看看mach-o里面有没有选择器
                if ( !hi->hasPreoptimizedSelectors() ) {
                  size_t count;
                  _getObjc2SelectorRefs(hi, &count);
                  selrefCount += count;
                  _getObjc2MessageRefs(hi, &count);
                  selrefCount += count;
                }
#else
                _getObjcSelectorRefs(hi, &selrefCount);

#endif
#if SUPPORT_GC_COMPAT
                // Halt if this is a GC app.
                if (shouldRejectGCApp(hi)) {
                    _objc_fatal_with_reason
                        (OBJC_EXIT_REASON_GC_NOT_SUPPORTED, 
                         OS_REASON_FLAG_CONSISTENT_FAILURE, 
                         "Objective-C garbage collection " 
                         "is no longer supported.");
                }
#endif
            }
            hList[hCount++] = hi;
            if (PrintImages) {
                _objc_inform("IMAGES: loading image for %s%s%s%s%s\n", 
                             hi->fname(),
                             mhdr->filetype == MH_BUNDLE ? " (bundle)" : "",
                             hi->info()->isReplacement() ? " (replacement)" : "",
                             hi->info()->hasCategoryClassProperties() ? " (has class properties)" : "",
                             hi->info()->optimizedByDyld()?" (preoptimized)":"");
            }
        }
    }
    // Perform one-time runtime initialization that must be deferred until 
    // the executable itself is found. This needs to be done before 
    // further initialization.
    // (The executable may not be present in this infoList if the 
    // executable does not contain Objective-C code but Objective-C 
    // is dynamically loaded later.
    //不重要,不需要了解,照着备注看看就行
    //执行一次性的运行时初始化,该初始化必须延迟到找到可执行文件本身。这需要在进一步初始化之前完成。(如果可执行文件不包含Objective-C代码,但是Objective-C稍后会动态加载,那么这个可执行文件可能不会出现在这个infoList中。
    if (firstTime) {
        sel_init(selrefCount);
        // 建表的函数
        arr_init();
        
#if SUPPORT_GC_COMPAT
        // Reject any GC images linked to the main executable.
        // We already rejected the app itself above.
        // Images loaded after launch will be rejected by dyld.
        for (uint32_t i = 0; i < hCount; i++) {
            auto hi = hList[i];
            auto mh = hi->mhdr();
            if (mh->filetype != MH_EXECUTE  &&  shouldRejectGCImage(mh)) {
                _objc_fatal_with_reason
                    (OBJC_EXIT_REASON_GC_NOT_SUPPORTED, 
                     OS_REASON_FLAG_CONSISTENT_FAILURE, 
                     "%s requires Objective-C garbage collection "
                     "which is no longer supported.", hi->fname());
            }
        }
#endif

#if TARGET_OS_OSX
        // Disable +initialize fork safety if the app is too old (< 10.13).
        // Disable +initialize fork safety if the app has a
        //   __DATA,__objc_fork_ok section.

//       if(!dyld_program_sdk_at_least(dyld_platform_version_macOS_10_13)) {
//            DisableInitializeForkSafety = true;
//            if (PrintInitializing) {
//                _objc_inform("INITIALIZE: disabling +initialize fork "
//                             "safety enforcement because the app is "
//                             "too old.)");
//            }
//        }


        for (uint32_t i = 0; i < hCount; i++) {

            auto hi = hList[i];
            auto mh = hi->mhdr();
            if (mh->filetype != MH_EXECUTE) continue;
            unsigned long size;
            if (getsectiondata(hi->mhdr(), "__DATA", "__objc_fork_ok", &size)) {
                DisableInitializeForkSafety = true;
                if (PrintInitializing) {
                    _objc_inform("INITIALIZE: disabling +initialize fork "
                                 "safety enforcement because the app has "
                                 "a __DATA,__objc_fork_ok section");
                }
            }

            break;  // assume only one MH_EXECUTE image
        }

#endif
    }
    //该函数才是核心,因为它是去设置镜像文件,读取到内存等等。上面的知道着没用
    if (hCount > 0) {
        _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);

    }
    firstTime = NO;
    // Call image load funcs after everything is set up.
    // 经历过读取,才能去调用,例如load方法
    for (auto func : loadImageFuncs) {
        for (uint32_t i = 0; i < mhCount; i++) {
            func(mhdrs[i]);
        }
    }

}

_read_images

该函数才是map_images流程的核心开始。很重要了,它做了很多事情,去读取mach-o,以header开始进行读取。你可以直接理解为读取镜像文件到内存中去。它大致分为以下几个步骤:

  1. 第一次进来的时候去创建一个类表,该类表包含了类名等(不是runtime的,是全局的已经被加载或没被加载的类,我说的加载不加载意思是是否被实现,其实像其他语言一样类的内存大小等在编译阶段就已经确定了,之所以说OC是运行时动态,因为提供api去改变类的结构,但是你要知道,改变的结构是指的rw,并不是ro。ro在编译后就已经确定),略微重要,需要知道类表创建

  2. 将mach-o已经编译后的sel,进行修复。不重要

  3. 先将所有的类都加到1流程锁创建的大类表中,并且将类的地址和名字进行绑定,也就是给类赋予名字。然后将混乱错误类处理(就是我们删除的类,但是删除后内存中依旧有这块地址没被清除,我们成为futureClass。)略微重要,需要知道类被加表,以及赋予名字

  4. 修复一些重映射类,就是重映射没被加载进来的,不重要

  5. 修复objc_msgSend_fixup,不重要

  6. 看看有没有协议,如果有的话修复一下。可以当做发现协议,不重要

  7. 修复重映射协议,不重要

  8. 对分类进行处理,但是在启动的时候并不会走,也就是说分类加载并不在这时候,不重要

  9. 对非懒加载类进行处理,里面包含了类的实现。重要

  10. 如果有3流程的错误类被修复了,会进行优化。不重要

源码

源码太长可以不看

void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
    header_info *hi;
    uint32_t hIndex;
    size_t count;
    size_t i;
    Class *resolvedFutureClasses = nil;
    size_t resolvedFutureClassCount = 0;
    static bool doneOnce;
    bool launchTime = NO;
    TimeLogger ts(PrintImageTimes);

    runtimeLock.assertLocked();

#define EACH_HEADER \
    hIndex = 0;         \
    hIndex < hCount && (hi = hList[hIndex]); \
    hIndex++
    // 1.第一次进来
    if (!doneOnce) {
        doneOnce = YES;
        launchTime = YES;

#if SUPPORT_NONPOINTER_ISA
        // Disable non-pointer isa under some conditions.

# if SUPPORT_INDEXED_ISA
        // Disable nonpointer isa if any image contains old Swift code
        for (EACH_HEADER) {
            if (hi->info()->containsSwift()  &&
                hi->info()->swiftUnstableVersion() < objc_image_info::SwiftVersion3)
            {
                DisableNonpointerIsa = true;
                if (PrintRawIsa) {
                    _objc_inform("RAW ISA: disabling non-pointer isa because "
                                 "the app or a framework contains Swift code "
                                 "older than Swift 3.0");
                }
                break;
            }
        }
# endif

# if TARGET_OS_OSX
        // Disable non-pointer isa if the app is too old
        // (linked before OS X 10.11)
//        if (!dyld_program_sdk_at_least(dyld_platform_version_macOS_10_11)) {
//            DisableNonpointerIsa = true;
//            if (PrintRawIsa) {
//                _objc_inform("RAW ISA: disabling non-pointer isa because "
//                             "the app is too old.");
//            }
//        }

        // Disable non-pointer isa if the app has a __DATA,__objc_rawisa section
        // New apps that load old extensions may need this.
        for (EACH_HEADER) {
            if (hi->mhdr()->filetype != MH_EXECUTE) continue;
            unsigned long size;
            if (getsectiondata(hi->mhdr(), "__DATA", "__objc_rawisa", &size)) {
                DisableNonpointerIsa = true;
                if (PrintRawIsa) {
                    _objc_inform("RAW ISA: disabling non-pointer isa because "
                                 "the app has a __DATA,__objc_rawisa section");
                }
            }
            break;  // assume only one MH_EXECUTE image
        }
# endif

#endif

        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
        // objc::unattachedCategories.init(32);
        // objc::allocatedClasses.init();
        
        int namedClassesSize = 
            (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
        //gdb_objc_realized_classes
        gdb_objc_realized_classes =
            NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);

        ts.log("IMAGE TIMES: first time tasks");
    }

    // Fix up @selector references
    // 2.将mach-o的sel也就是预编译与编译后的sel进行比对修复
    static size_t UnfixedSelectors;
    {
        mutex_locker_t lock(selLock);
        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) 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 sel = sel_registerNameNoLock(name, isBundle);
                if (sels[i] != sel) {
                    sels[i] = sel;
                }
            }
        }
    }

    ts.log("IMAGE TIMES: fix up selector references");

    // Discover classes. Fix up unresolved future classes. Mark bundle classes.
    bool hasDyldRoots = dyld_shared_cache_some_image_overridden();
    // 3.对一些错误混乱的类处理
    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++) {
            Class cls = (Class)classlist[i];
            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");

    // Fix up remapped classes
    // Class list and nonlazy class list remain unremapped.
    // Class refs and super refs are remapped for message dispatching.
    // 4.修复重映射一些没有被镜像文件加载进来的类
    if (!noClassesRemapped()) {
        for (EACH_HEADER) {
            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]);
            }
        }
    }

    ts.log("IMAGE TIMES: remap classes");

#if SUPPORT_FIXUP
    // Fix up old objc_msgSend_fixup call sites
    // 5.修复一些消息
    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


    // Discover protocols. Fix up protocol refs.
    // 6.如果类里面有协议,读取一下
    for (EACH_HEADER) {
        extern objc_class OBJC_CLASS_$_Protocol;
        Class cls = (Class)&OBJC_CLASS_$_Protocol;
        ASSERT(cls);
        NXMapTable *protocol_map = protocols();
        bool isPreoptimized = hi->hasPreoptimizedProtocols();

        // Skip reading protocols if this is an image from the shared cache
        // and we support roots
        // Note, after launch we do need to walk the protocol as the protocol
        // in the shared cache is marked with isCanonical() and that may not
        // be true if some non-shared cache binary was chosen as the canonical
        // definition
        if (launchTime && isPreoptimized) {
            if (PrintProtocols) {
                _objc_inform("PROTOCOLS: Skipping reading protocols in image: %s",
                             hi->fname());
            }
            continue;
        }

        bool isBundle = hi->isBundle();

        protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);
        }
    }

    ts.log("IMAGE TIMES: discover protocols");

    // Fix up @protocol references
    // Preoptimized images may have the right 
    // answer already but we don't know for sure.
    // 7.修复一些没有被加载的协议
    for (EACH_HEADER) {
        // At launch time, we know preoptimized image refs are pointing at the
        // shared cache definition of a protocol.  We can skip the check on
        // launch, but have to visit @protocol refs for shared cache images
        // loaded later.
        if (launchTime && hi->isPreoptimized())
            continue;
        protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
        for (i = 0; i < count; i++) {
            remapProtocolRef(&protolist[i]);
        }
    }

    ts.log("IMAGE TIMES: fix up @protocol references");

    // Discover categories. Only do this after the initial category
    // attachment has been done. For categories present at startup,
    // discovery is deferred until the first load_images call after
    // the call to _dyld_objc_notify_register completes. rdar://problem/53119145
    // 8.对于分类的处理,这里条件为默认false
    if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }

    ts.log("IMAGE TIMES: discover categories");

    // Category discovery MUST BE Late to avoid potential races
    // when other threads call the new category code before
    // this thread finishes its fixups.

    // +load handled by prepare_load_methods()

    // Realize non-lazy classes (for +load methods and static instances)
    // 9.对于哪些非懒加载类的加载处理(懒加载类与非懒加载类,加载的时机其实不同)
    for (EACH_HEADER) {
        classref_t const *classlist = hi->nlclslist(&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);
        }
    }

    ts.log("IMAGE TIMES: realize non-lazy classes");

    // Realize newly-resolved future classes, in case CF manipulates them
    // 10.上面3的时候如果有类是混乱后被修复,优化一下被侵犯的类
    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, nil);
            cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);
        }
        free(resolvedFutureClasses);
    }

    ts.log("IMAGE TIMES: realize future classes");

    if (DebugNonFragileIvars) {
        realizeAllClasses();
    }


    // Print preoptimization statistics
    // 如果说我们设置环境变量OBJC_PRINT_PREOPTIMIZATION这个值会进行打印
    if (PrintPreopt) {
        static unsigned int PreoptTotalMethodLists;
        static unsigned int PreoptOptimizedMethodLists;
        static unsigned int PreoptTotalClasses;
        static unsigned int PreoptOptimizedClasses;

        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) {
                _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors "
                             "in %s", hi->fname());
            }
            else if (hi->info()->optimizedByDyld()) {
                _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors "
                             "in %s", hi->fname());
            }

            classref_t const *classlist = _getObjc2ClassList(hi, &count);
            for (i = 0; i < count; i++) {
                Class cls = remapClass(classlist[i]);
                if (!cls) continue;

                PreoptTotalClasses++;
                if (hi->hasPreoptimizedClasses()) {
                    PreoptOptimizedClasses++;
                }
                
                const method_list_t *mlist;
                if ((mlist = cls->bits.safe_ro()->baseMethods())) {
                    PreoptTotalMethodLists++;
                    if (mlist->isFixedUp()) {
                        PreoptOptimizedMethodLists++;
                    }
                }
                if ((mlist = cls->ISA()->bits.safe_ro()->baseMethods())) {
                    PreoptTotalMethodLists++;
                    if (mlist->isFixedUp()) {
                        PreoptOptimizedMethodLists++;
                    }
                }
            }
        }

        _objc_inform("PREOPTIMIZATION: %zu selector references not "
                     "pre-optimized", UnfixedSelectors);
        _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) method lists pre-sorted",
                     PreoptOptimizedMethodLists, PreoptTotalMethodLists, 
                     PreoptTotalMethodLists
                     ? 100.0*PreoptOptimizedMethodLists/PreoptTotalMethodLists 
                     : 0.0);
        _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) classes pre-registered",
                     PreoptOptimizedClasses, PreoptTotalClasses, 
                     PreoptTotalClasses 
                     ? 100.0*PreoptOptimizedClasses/PreoptTotalClasses
                     : 0.0);
        _objc_inform("PREOPTIMIZATION: %zu protocol references not "
                     "pre-optimized", UnfixedProtocolReferences);
    }

#undef EACH_HEADER
}

load_images ,load方法的加载调用

该方法包含了所有文件的load的方法的加载调用。其实最主要的也是调用load方法。(插一句题外话,就是当类与分类同时实现load方法的时候,也就打破了类的加载,进而分类的加载会从此处去进行。但是又有一种情况就是,当超过一个分类实现load方法,也就是两个及以上的时候虽说还会从此处走,但是走的方式又有所不同。)

void load_images(const char *path __unused, const struct mach_header *mh)
{
    // 当完成dyld通知注册回调后,这里看函数名意思是加载所有的分类,但是是这样吗?
    // 
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
        didInitialAttachCategories = true;
        loadAllCategories();
    }

    // Return without taking locks if there are no +load methods here.
    if (!hasLoadMethods((const headerType *)mh)) return;

    recursive_mutex_locker_t lock(loadMethodLock);

    // 去准备分类方法,看备注就知道
    // Discover load methods
    {
        mutex_locker_t lock2(runtimeLock);
        prepare_load_methods((const headerType *)mh);
    }
    // 这个没什么看的,就是去调用load方法了,但是先调用类的,再按顺序调用分类的
    // Call +load methods (without runtimeLock - re-entrant)
    call_load_methods();
}

loadAllCategories 分析

这个方法不重要,只执行了一次,我分析过,当类和分类同时实现load方法的时候才会进入这个方法,这一块跟分类加载有关,这里不做分析。而循环执行的是296次,可能不准确,不过无所谓,反正是玩的而已

static void loadAllCategories() {
    mutex_locker_t lock(runtimeLock);
    // 执行了296次
    for (auto *hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
        // 对于某种情况下,我们自己创建的分类加载会走这里,这里不做分析
        load_categories_nolock(hi);
    }
}

prepare_load_methods load方法的准备

这个方法是load的方法的准备,也跟我们分类加载的某种情况有关,在以后我会补上分类加载篇章。先看看源码里面备注能理解就理解不能的话,没有关系。

void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertLocked();
    // 获取非懒加载的类表
    classref_t const *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    // 将类加如需要执行load方法的表中,有兴趣看里面的add_class_to_loadable_list方法
    for (i = 0; i < count; i++) {
        schedule_class_load(remapClass(classlist[i]));
    }
    // 获取非懒加载的分类列表
    category_t * const *categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
    for (i = 0; i < count; i++) {
        category_t *cat = categorylist[i];
        Class cls = remapClass(cat->cls);
        if (!cls) continue;  // category for ignored weak-linked class
        /** 这里你可以写跟我一样的测试代码,进行打印看看
        const char *clsName = cls -> nonlazyMangledName();
        const char *perosn = "Person";
        const char *teacher = "Teacher";

        if (strcmp(clsName, perosn) == 0 || strcmp(clsName, teacher) == 0)
        {
            printf("-------%s----%s\n", __func__,clsName);
        }
        */
        
        if (cls->isSwiftStable()) {
            _objc_fatal("Swift class extensions and categories on Swift "
                        "classes are not allowed to have +load methods");
        }
        // 如果说对于非懒加载的分类它的类没有实现的话去实现
        // 类被动实现
        realizeClassWithoutSwift(cls, nil);
        ASSERT(cls->ISA()->isRealized());
        // 与类的add_class_to_loadable_list对照
        add_category_to_loadable_list(cat);
    }
}