iOS 全网最新objc4 可调式/编译源码

编译好的源码的下载地址

序文

前面的文章中探求了类的结构,知道了类中都有哪些内容,那么今天就来探求一下,类到底是怎样加载进内存的呢?在什么时分加载到内存的呢?

咱们定义的类.h.m文件,首要需求经过编译器生产可履行文件,这个进程称为编译阶段,然后安装在设备上加载运转。

编译

  • 预编译:编译之前的一些先前的处理作业,处理一些#开头的文件,#include#define以及条件编译等;
  • 编译:对预编译后的文件进行词法剖析语法剖析语义剖析,并进行代码优化,生成汇编代码;
  • 汇编:将汇编文件代码转换为机器能够履行的指令,并生成方针文件.o
  • 链接:将一切方针文件以及链接的第三方库,链接成可履行文件macho;这一进程中,链接器将不同的方针文件链接起来,由于不同的方针文件之间可能有相互引证的变量或调用的函数,比如咱们常用的体系库。

动态办法决议-导出.png

动态库与静态库

  • 静态库:链接阶段将汇编生成的方针文件和引证库一同链接打包到可履行文件中,如:.a.lib
    • 长处:编译成功后可履行文件能够独立运转,不需求依靠外部环境;
    • 缺陷:编译的文件会变大,假如静态库更新有必要从头编译;
  • 动态库:链接时不仿制,程序运转时由体系加载到内存中,供体系调用,如:.dylib.framework
    • 长处:体系只需加载一次,屡次运用,共用节约内存,经过更新动态库,达到更新程序的目的;
    • 缺陷:可履行文件不能够独自运转,有必要依靠外部环境;

体系的framework是动态的,开发者创立的framework是静态的

3864017-0c111edb6fed43b2.webp

dyld动态链接器

  • dyld是iOS操作体系的一个重要组成部分,在体系内核做好程序准备作业之后,会交由dyld担任余下的作业。
  • dyld的效果:加载各个库,也便是image镜像文件,由dyld从内存中读到表中,加载主程序,link链接各个动静态库,进行主程序的初始化作业。

3864017-0c1deb5c8c79c239.png

dyld担任链接、加载程序,但是dyld的探究进程比较繁琐就不具体展开了,直接进入类的加载中心_objc_init办法探究。

_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();      // 关于线程key的绑定
    static_init();   // 运转C++静态结构函数
    runtime_init();  // runtime运转时环境初始化
    exception_init();// 初始化libobjc库的反常处理
#if __OBJC2__
    cache_t::init(); // 缓存条件初始化
#endif
    _imp_implementationWithBlock_init(); // 发动回调机制
    // 注册处理程序,以便在映射、取消映射和初始化objc图像时调用,仅供运转时Runtime运用
    _dyld_objc_notify_register(&map_images, load_images, unmap_image);
#if __OBJC2__
    didCallDyldNotifyRegister = **true**;
#endif
}

environ_init环境变量

/***********************************************************************
* environ_init
* Read environment variables that affect the runtime.
* Also print environment variable help, if requested.
************************************************************************ ** **/
void environ_init(void) 
{
// 部分中心代码
// Print OBJC_HELP and OBJC_PRINT_OPTIONS output.
    if (PrintHelp  ||  PrintOptions) {
        if (PrintHelp) {
            _objc_inform("Objective-C runtime debugging. Set variable=YES to enable.");
            _objc_inform("OBJC_HELP: describe available environment variables");
            if (PrintOptions) {
                _objc_inform("OBJC_HELP is set");
            }
            _objc_inform("OBJC_PRINT_OPTIONS: list which options are set");
        }
        if (PrintOptions) {
            _objc_inform("OBJC_PRINT_OPTIONS is set");
        }
        for (size_t i = 0; i < sizeof(Settings)/sizeof(Settings[0]); i++) {
            const option_t *opt = &Settings[i];
//            if (opt->internal
//                && !os_variant_allows_internal_security_policies("com.apple.obj-c"))
//                continue;
            if (PrintHelp) _objc_inform("%s: %s", opt->env, opt->help);
            if (PrintOptions && *opt->var) _objc_inform("%s is set", opt->env);
        }
    }
}

经过控制PrintHelpPrintOptions能够打印当时环境变量的配置信息,咱们在源码环境中把for循环代码仿制出来改一下,运转

image.png

image.png

也能够经过终端指令export OBJC_HELP = 1,在终端上显现

image.png

能够经过Edit shceme,在Environment Variables配置相关变量

  • OBJC_DISABLE_NONPOINTER_ISA: isa的优化开关,假如YES表明不运用,便是存指针;假如NO敞开指针优化,为nonpointer isa;
  • OBJC_PRINT_LOAD_METHODS:是否敞开打印一切load办法,能够判别哪些类运用了load办法,做相应的优化处理,以优化发动速度;

image.png

tls_init线程key的绑定

tls_init关于线程key的绑定,比如每个线程数据的析构函数

void tls_init(void)
{
#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++静态结构函数

运转C++静态结构函数。
libcdyld调用静态结构函数之前调用objc_init(),因此咱们有必要自己履行。

static void static_init()
{
    size_t count1;
    auto inits = getLibobjcInitializers(&_mh_dylib_header, &count1);
    for (size_t i = 0; i < count1; i++) {
        inits[i]();
    }
    size_t count2;
    auto offsets = getLibobjcInitializerOffsets(&_mh_dylib_header, &count2);
    for (size_t i = 0; i < count2; i++) {
        UnsignedInitializer init(offsets[i]);
        init();
    }
#if DEBUG
    if (count1 == 0 && count2 == 0)
        _objc_inform("No static initializers found in libobjc. This is unexpected for a debug build. Make sure the 'markgc' build phase ran on this dylib. This process is probably going to crash momentarily due to using uninitialized global data.");
#endif
}

runtime_init运转时环境初始化

Runtime运转时环境初始化,首要是unattachedCategoriesallocatedClasses两张表的初始化

void runtime_init(void)
{
    objc::disableEnforceClassRXPtrAuth = DisableClassRXSigningEnforcement;
    objc::unattachedCategories.init(32); // 分类表
    objc::allocatedClasses.init();       // 已拓荒类的表
}

exception_init 反常体系初始化

初始化libobjc的反常处理体系,由map_images()调用。注册反常处理的回调,从而监控反常的处理

void exception_init(void)
{
    old_terminate = std::set_terminate(&_objc_terminate);
}

反常处理体系初始化后,当程序运转不符合底层规矩时,比如:数组越界办法未完结等,体系就会发出反常信号。

image.png
有反常产生时,uncaught_handler函数会把反常信息e抛出

image.png
uncaught_handler便是这儿传进来的fn,这个fn便是咱们检测反常的句柄。咱们能够自定义反常处理类,经过NSSetUncaughtExceptionHandler把咱们句柄函数地址传进去

image.png
有反常产生时,体系会回调给咱们反常exception,然后自定义上传等处理操作。
image.png

cache_t::init缓存条件初始化

void cache_t::init()
{
#if HAVE_TASK_RESTARTABLE_RANGES
    mach_msg_type_number_t count = 0;
    kern_return_t kr;
    while (objc_restartableRanges[count].location) {
        count++;
    }
    kr = task_restartable_ranges_register(mach_task_self(),
                                 objc_restartableRanges, count);
    if (kr == KERN_SUCCESS) return;
    _objc_fatal("task_restartable_ranges_register failed (result 0x%x: %s)",
                kr, mach_error_string(kr));
#endif // HAVE_TASK_RESTARTABLE_RANGES
}

image.png

_imp_implementationWithBlock_init

通常情况下,这没有任何效果,由于一切的初始化都是慵懒的,但关于某些进程,咱们急迫地加载trampolines dylib。

在某些进程中急迫地加载libobjc-tropolines.dylib。一些程序(最著名的是前期版别的嵌入式Chromium运用的QtWebEngineProcess)启用了一个限制性很强的沙盒配置文件,该文件阻止对该dylib的访问。假如有任何东西调用imp_implementationWithBlock(正如AppKit现已开端做的那样),那么咱们将在尝试加载它时崩溃。在这儿加载它会在启用沙盒配置文件并阻止它之前设置它。

void
_imp_implementationWithBlock_init(void)
{
#if TARGET_OS_OSX
    // Eagerly load libobjc-trampolines.dylib in certain processes. Some
    // programs (most notably QtWebEngineProcess used by older versions of
    // embedded Chromium) enable a highly restrictive sandbox profile which
    // blocks access to that dylib. If anything calls
    // imp_implementationWithBlock (as AppKit has started doing) then we'll
    // crash trying to load it. Loading it here sets it up before the sandbox
    // profile is enabled and blocks it.
    //
    // This fixes EA Origin (rdar://problem/50813789)
    // and Steam (rdar://problem/55286131)
    if (__progname &&
        (strcmp(__progname, "QtWebEngineProcess") == 0 ||
         strcmp(__progname, "Steam Helper") == 0)) {
        Trampolines.Initialize();
    }
#endif
}

_dyld_objc_notify_register

void
_dyld_objc_notify_register(_dyld_objc_notify_mapped    mapped,
                                _dyld_objc_notify_init      init,
                                _dyld_objc_notify_unmapped  unmapped);

_dyld_objc_notify_register中的三个参数含义如下

  • &map_imagesdyldimage加载到内存中会调用该函数
  • load_imagesdyld初始化一切的image文件会调用
  • unmap_image:将image移除时会调用

咱们要点看的便是将image加载到内存中调用的函数map_image

image.png
map_image中调用map_images_nolock

image.png
map_images_nolock中的代码比较多,咱们这儿直接看要点_read_images

_read_images解读

_read_images办法中有360行代码,有点长,把里边的大括号折叠,苹果的代码流程和注释是很好的,能够先整体掌握一下,里边的ts.log很明晰的告知了咱们整个流程。

void _read_images(header_info hList, uint32_t hCount, int
totalClasses, int 
unoptimizedTotalClasses)
{
   ... //表明省略部分代码
#define EACH_HEADER \
    hIndex = 0;         \
    hIndex < hCount && (hi = hList[hIndex]); \
    hIndex++
    // 条件控制进行一次的加载
    if (!doneOnce) { ... }
    // 修正预编译阶段的`@selector`的紊乱的问题
    // 便是不同类中有相同的办法 但是相同的办法地址是不一样的
    // Fix up @selector references
    static size_t UnfixedSelectors;
    { ... }
    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();
    for (EACH_HEADER) { ... }
    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.
    if (!noClassesRemapped()) { ... }
    ts.log("IMAGE TIMES: remap classes");
#if SUPPORT_FIXUP
    // 修正一些音讯
    // Fix up old objc_msgSend_fixup call sites
    for (EACH_HEADER) { ... }
    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif
    // 当类中有协议时:`readProtocol`
    // Discover protocols. Fix up protocol refs.
    for (EACH_HEADER) { ... }
    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.
    for (EACH_HEADER) { ... }
    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.  
    if (didInitialAttachCategories) { ... }
    ts.log("IMAGE TIMES: discover categories");
    // 类的加载处理
    // Category discovery MUST BE Late to avoid potential races
    // when other threads call the new category code befor
    // this thread finishes its fixups.
    // +load handled by prepare_load_methods()
    // Realize non-lazy classes (for +load methods and static instances)
    for (EACH_HEADER) { ... }
    ts.log("IMAGE TIMES: realize non-lazy classes");
    // 没有被处理的类,优化那些被侵犯的类
    // Realize newly-resolved future classes, in case CF manipulates them
    if (resolvedFutureClasses) { ... }
    ts.log("IMAGE TIMES: realize future classes");
   ...
#undef EACH_HEADER
}
  • 条件控制,进行一次加载;
  • 修正预编译阶段的@selecter紊乱问题;
  • 过错紊乱的类处理;
  • 修正从头映射一些没有被镜像文件加载进来的类;
  • 修正一些音讯
  • 当类里边有协议的时分:readProtocol
  • 修正没有被加载进来的协议;
  • 分类处理;
  • 类的加载处理;
  • 没有被处理的类

doneOnce加载一次

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
#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
        // 容量:总数 * 4 / 3
        int namedClassesSize = 
            (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
        // 创立哈希表,用于存放一切的类
        gdb_objc_realized_classes =
            NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
        ts.log("IMAGE TIMES: first time tasks");
    }

经过对doneOnce的判别,只会进来一次条件句子,这儿首要处理对类表的拓荒创立处理gdb_objc_realized_classes

修正@selecter紊乱问题

static size_t UnfixedSelectors;
    {
        mutex_locker_t lock(selLock);
        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) continue;
            bool isBundle = hi->isBundle();
            // 从macho文件中获取办法名列表
            SEL *sels = _getObjc2SelectorRefs(hi, &count);
            UnfixedSelectors += count;
            for (i = 0; i < count; i++) {
                const char *name = sel_cname(sels[i]);
                // sel经过name从dyld中查找获取
                SEL sel = sel_registerNameNoLock(name, isBundle);
                if (sels[i] != sel) { // 修正地址,以dyld为准
                    sels[i] = sel;
                }
            }
        }
    }
    ts.log("IMAGE TIMES: fix up selector references");

sel进行修正,由于从编译后的macho读取的sel地址不一定是真实的sel地址,在这儿做修正。

过错紊乱的类处理

// 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;
        }
        // 从macho中读取的类列表
        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];
            // 经过readClass,将cls的类名和地址做相关
            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");
  • 经过_getObjc2ClassList从macho中读取的一切的类;
  • 遍历一切的类,经过readClass讲类的地址和类名相关;

image.png

  • popFutureNamedClass回来已完结的类,咱们增加的类未完结,这儿if句子不成立;
  • mangledName是有值的,调用addNamedClassname=>cls增加到命名的非元类映射中。
  • addClassTableEntry:将类增加到一切类的表中。假如addMeta为true,则自动增加类的元类。
  • 回来已处理的类

能够看出readClass函数是把传进来的cls从头映射并增加cls和其元类到一切的类中。

修正从头映射的类

类列表和非懒加载类列表依然未被增加。
类引证和父类引证被从头映射以用于音讯调度。

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

修正一些音讯

// Fix up old objc_msgSend_fixup call sites | 修正旧的objc_msgSend_fixup调用站点
    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++) {
            // 内部将常用的alloc、objc_msgSend等函数指针进行注册,并fix为新的函数指针
            fixupMessageRef(refs+i);
        }
    }
    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");

image.png

增加协议

当类里边有协议的时分,调用readProtocol绑定协议

// Discover protocols. Fix up protocol refs.
    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");

image.png

修正协议列表引证

上面做了协议和类的相关,这儿是对协议进行从头映射

image.png

分类的处理

if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }
    ts.log("IMAGE TIMES: discover categories");

分类的流程是比较重要的,将开展新的文章专讲一下。

类的加载处理

// Realize non-lazy classes (for +load methods and static instances)
// 完结非懒加载类(完结了+load或静态实例办法)
    for (EACH_HEADER) {
        // 经过_getObjc2NonlazyClassList获取一切非懒加载类
        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
            }
            // 对类cls履行初次初始化,包含分配其读写数据。不履行任何Swift端初始化。
            realizeClassWithoutSwift(cls, **nil**);
        }
    }
    ts.log("IMAGE TIMES: realize non-lazy classes");

本文要点

  • 调用nlclslist(里边是调用_getObjc2NonlazyClassList)获取一切非懒加载(non-lazy)的类;
  • 循环完结,再次增加到一切的类表中,假如已增加就不会增加进去,保证整个结构都被增加;
  • 调用realizeClassWithoutSwift对类cls履行初次初始化,包含分配其读写数据;

经过realizeClassWithoutSwift完结一切非懒加载类的第一次初始化,那咱们就看realizeClassWithoutSwift怎么完结的

static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();
    class_rw_t *rw;
    Class supercls;
    Class metacls;
    if (!cls) return nil;
    if (cls->isRealized()) {
        // 验证已完结的类
        validateAlreadyRealizedClass(cls);
        return cls;
    }
    ASSERT(cls == remapClass(cls));
    // fixme verify class is not in an un-dlopened part of the shared cache?
    auto ro = cls->safe_ro();
    auto isMeta = ro->flags & RO_META; // 是否元类
    if (ro->flags & RO_FUTURE) { // future类,rw的data现已初始化
        // 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->set_ro(ro);
        rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
        cls->setData(rw);
    }
    cls->cache.initializeToEmptyOrPreoptimizedInDisguise();
#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.
//     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->getSuperclass()), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
    // 纯isa还是nonpointer isa
#if SUPPORT_NONPOINTER_ISA
    if (isMeta) {
        // Metaclasses do not need any features from non pointer ISA
        // This allows for a faspath for classes in objc_retain/objc_release.
        cls->setInstancesRequireRawIsa(); // 纯指针isa
    } else {
        // 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->getName(), "OS_object"))
        {
            // hack for libdispatch et al - isa also acts as vtable pointer
            hackedDispatch = true;
            instancesRequireRawIsa = true;
        }
        else if (supercls  &&  supercls->getSuperclass()  &&
                 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) {  // 纯指针isa
            cls->setInstancesRequireRawIsaRecursively(rawIsaIsInherited);
        }
    }
// SUPPORT_NONPOINTER_ISA
#endif
    // Update superclass and metaclass in case of remapping
    cls->setSuperclass(supercls); // 设置superclass指向父类
    cls->initClassIsa(metacls);   // 设置isa指向元类
    // 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, previously);
    return cls;
}

initClassIsa时会依据nonpointer区别设置

  • 先类判别是否现已完结,假如已完结经过validateAlreadyRealizedClass验证;
  • 未完结,cls->setData(rw)处理类的data也便是rwro,初始化rw并复制ro数据到rw中;
  • 将事件往上层传递,来完结父类以及元类
  • 判别isa指针类型,是纯指针还是nonpointer指针,在设置isa时有不同;
  • cls->setSuperclass(supercls):设置superclass指向父类;
  • cls->initClassIsa(metacls):设置isa指向元类;
  • methodizeClass:在这儿进行办法、特点、协议、分类的完结;

image.png

看一下methodizeClass的完结

static void methodizeClass(Class cls, Class previously)
{
    runtimeLock.assertLocked();
    bool isMeta = cls->isMetaClass();
    auto rw = cls->data();
    auto ro = rw->ro();
    auto rwe = rw->ext();
    // 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.
    // rwe:办法、特点、协议
    method_list_t *list = ro->baseMethods;
    if (list) {
    // 写入办法,并对办法进行排序
        prepareMethodLists(cls, &list, 1, **YES**, isBundleClass(cls), **nullptr**);
        if (rwe) rwe->methods.attachLists(&list, 1);
    }
    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
}
  • methodizeClass中首要便是对methodpropertyprotocol存放在rwe的处理,其实这儿的rwe并没有值,由于还没有完结初始化,
  • 为根元类增加initialize初始化办法,
  • 对分类处理。

上面是非懒加载类的处理,那么懒加载类是在什么时分完结初始化的呢?依据懒加载原则,应该便是在用的时分再去调用吧,那就验证一下

源码环境中,咱们在methodizeClass经过类姓名加断点

先在LGTeacher里边完结+load办法,运转
image.png

这儿是从_objc_init_read_images进入的

LGTeacher里边去掉+load办法,运转

image.png
这儿能够看到,整个流程是在main函数里调用LGTeacheralloc办法来的,经过objc_msgSend音讯查找流程的lookUpImpOrForward走到了这儿。

总结

类的加载经过类是否完结+load静态实例办法,区分为懒加载类非懒加载类

  • 非懒加载类:是在发动时map_images时加载进内存的,经过_getObjc2NonlazyClassList得到一切非懒加载类,循环调用realizeClassWithoutSwiftmethodizeClass完结初始化。

  • 懒加载类:是在第一次音讯发送的时分,检查类是否初始化,为完结初始化再去完结初始化流程。

关于音讯发送文章:
iOS底层之Runtime探究(一)
iOS底层之Runtime探究(二)
iOS底层之Runtime探究(三)

iOS 全网最新objc4 可调式/编译源码
编译好的源码的下载地址

以上是对iOS中类的加载经过源码的探究进程,如有疑问或过错之处请留言或私信我