iOS中类的加载(上)

913 阅读8分钟

引入

从前面的分析中我们可以知道,我们的代码经过编译之后,生成可执行文件(mach0),将代码加入到内存中,程序才可以执行,❓那么这些类是怎么加载的呢

源码分析

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    //1.读取影响运行时的环境变量。
    environ_init();
    //2.关于线程key的绑定
    tls_init();
    //3.运行c++静态构造函数。
    static_init();
    //4.初始化unattachedCategories、allocatedClasses表
    runtime_init();
    //5.初始化libobjc的异常处理系统
    exception_init();
#if __OBJC2__
    cache_t::init();
#endif
    _imp_implementationWithBlock_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);
    // map_images()
    // load_images()
#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}
exception_init() 捕获异常信息

我们看一下5,可以利用给NSSetUncaughtExceptionHandler赋值获取到异常信息,然后进行一些日志的上传或者堆栈的数据分析。

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

看一下_objc_terminate

static void (*old_terminate)(void) = nil;
static void _objc_terminate(void)
{
    if (PrintExceptions) {
        _objc_inform("EXCEPTIONS: terminating");
    }

    if (! __cxa_current_exception_type()) {
        // No current exception.
        (*old_terminate)();
    }
    else {
        // There is a current exception. Check if it's an objc exception.
        @try {
            __cxa_rethrow();
        } @catch (id e) {
            // It's an objc object. Call Foundation's handler, if any.
            (*uncaught_handler)((id)e);
            (*old_terminate)();
        } @catch (...) {
            // It's not an objc object. Continue to C++ terminate.
            (*old_terminate)();
        }
    }
}

根据try...catch..得知(*uncaught_handler)((id)e);这个是对异常的回调,搜索下uncaught_handler赋值。

/***********************************************************************
* _objc_default_uncaught_exception_handler
* Default uncaught exception handler. Expected to be overridden by Foundation.
**********************************************************************/
static void _objc_default_uncaught_exception_handler(id exception)
{
}
static objc_uncaught_exception_handler uncaught_handler = _objc_default_uncaught_exception_handler;

objc_uncaught_exception_handler进行重写,则可以获取到异常信息 部分实例代码

+ (void)installUncaughtSignalExceptionHandler{
    // uncaught_handler() = fn = LGExceptionHandlers
   //  objc_setUncaughtExceptionHandler() 对应的OC函数则为NSSetUncaughtExceptionHandler
    NSSetUncaughtExceptionHandler(&LGExceptionHandlers);
}
// Exception
void LGExceptionHandlers(NSException *exception) {
    NSLog(@"%s",__func__);
    
    int32_t exceptionCount = atomic_fetch_add_explicit(&LGUncaughtExceptionCount,1,memory_order_relaxed);
    if (exceptionCount > LGUncaughtExceptionMaximum) {
        return;
    }
    // 获取堆栈信息 - model 编程思想
    NSArray *callStack = [LGUncaughtExceptionHandle lg_backtrace];
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];
    [userInfo setObject:exception.name forKey:LGUncaughtExceptionHandlerSignalExceptionName];
    [userInfo setObject:exception.reason forKey:LGUncaughtExceptionHandlerSignalExceptionReason];
    [userInfo setObject:callStack forKey:LGUncaughtExceptionHandlerAddressesKey];
    [userInfo setObject:exception.callStackSymbols forKey:LGUncaughtExceptionHandlerCallStackSymbolsKey];
    [userInfo setObject:@"LGException" forKey:LGUncaughtExceptionHandlerFileKey];
    
    [[[LGUncaughtExceptionHandle alloc] init]
     performSelectorOnMainThread:@selector(lg_handleException:)
     withObject:
     [NSException
      exceptionWithName:[exception name]
      reason:[exception reason]
      userInfo:userInfo]
     waitUntilDone:YES]; 
}
- (void)lg_handleException:(NSException *)exception{
    // 保存上传服务器
    
    NSDictionary *userinfo = [exception userInfo];
    [self saveCrash:exception file:[userinfo objectForKey:LGUncaughtExceptionHandlerFileKey]];
    
    SCLAlertView *alert = [[SCLAlertView alloc] initWithNewWindowWidth:300.f];
    [alert addButton:@"奔溃" actionBlock:^{
        self.dismissed = YES;
    }];
    [alert showSuccess:exception.name subTitle:exception.reason closeButtonTitle:nil duration:0.0f];
}

// 保存奔溃信息或者上传
- (void)saveCrash:(NSException *)exception file:(NSString *)file{
    
}
_dyld_objc_notify_register(&map_images, load_images, unmap_image);

_dyld_objc_notify_register函数中有两个传参,一个是&map_imagesload_images,❓为什么map_images前面有一个&,传过去的是个指针,为了后面调用的与赋值的一起改变。 我们看下这两个传入的参数,&map_imagesload_images

  • map_images管理文件中和动态库中所有的符号(class Protocol selector category )
  • load_image 加载执行load方法
map_images

map_images的实现

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

map_images_nolock实现

map_images_nolock(unsigned mhCount, const char * const mhPaths[],
                  const struct mach_header * const mhdrs[])
{
...
 if (hCount > 0) {
        _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
    }
  ...
}
_read_images

在map_images中我们主要是看类的一些加载,所以把重点转移到_read_images,摘要主要的代码

void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
  //1.条件控制进行一次的加载
  if (!doneOnce) {
  ...
   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();
        
        // x *3 / 4 = count * 4 / 3 * 3 / 4  count
        int namedClassesSize = 
            (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
        gdb_objc_realized_classes =
            NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
    ...
  }
   // Fix up @selector references
   //2.修复selector方法
    static size_t UnfixedSelectors;
    {
        mutex_locker_t lock(selLock);
        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) continue;

            bool isBundle = hi->isBundle();
            //从符号表中取出来sels
            SEL *sels = _getObjc2SelectorRefs(hi, &count);
            UnfixedSelectors += count;
            for (i = 0; i < count; i++) {
                const char *name = sel_cname(sels[i]);
                //从dyld取出来的sel
                SEL sel = sel_registerNameNoLock(name, isBundle);
                if (sels[i] != sel) {
                    sels[i] = sel;
                }
            }
        }
    }

    ts.log("IMAGE TIMES: fix up selector references");
    
     // 3.错误混乱的类处理
    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++) {
            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");
    //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");
    //5.修复一些消息
    #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
//6.当我们类里面有协议的时候:redProtocol
  // 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");
    //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");
    //8.分类处理
      if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }

    ts.log("IMAGE TIMES: discover categories");
    //9.类的加载处理
      // Realize non-lazy classes (for +load methods and static instances)
    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");
    //10.没有被处理的类,优化那些被侵犯的类
    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");
    ...

}
  • 1.条件控制进行一次的加载: 如果第一次进来,进行表的创建 int namedClassesSize = (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3; gdb_objc_realized_classes = NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize); gdb_objc_realized_classes是一个全量的表
// 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.
// This list excludes lazily named classes, which have to be looked up
// using a getClass hook.
NXMapTable *gdb_objc_realized_classes;
  • 2.UnfixedSelectors修复selector方法 SEL *sels = _getObjc2SelectorRefs(hi, &count);从macho符号表中获取sels SEL sel = sel_registerNameNoLock(name, isBundle);从dyld中获取到sel 如果不相等,把dyld获取到的赋值过去,dyld在动态链接过程中,做了一些rebase,rebind等操作,应该以它为准。macho中只是一个相对的地址。
  • 3.错误混乱的类处理 Class cls = (Class)classlist[i]; Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);处前后打两个断点,打印clsnewCls的值,
(lldb) po cls
objc[26761]: mutex incorrectly locked
objc[26761]: mutex incorrectly locked
0x0000000100008668

po newCls
objc[26761]: mutex incorrectly locked
objc[26761]: mutex incorrectly locked
LGPerson
readClass

我们看下readClass里面做了什么,

Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
            ...
            addNamedClass(cls, mangledName, replacing);
            ...
            addClassTableEntry(cls);
            ...
}

addNamedClass

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

NXMapInsert(gdb_objc_realized_classes, name, cls);将类的名字和cls插入到全量表中 所以后面在打印newCls的时候已经可以打印出来类的名字了。

把这个类添加到所有class表中

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

打断点发现是不会进到下面这个if中,看备注,resolvedFutureClasses是对一些被移除,但是没有被删干净的类,进行了一些处理

   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;
            }
  • 9.类的加载处理 我们重点看下类的加载处理 示例代码:
//Person.h

@interface Person : NSObject

@property (nonatomic, copy) NSString *lgName;
@property (nonatomic, strong) NSString *nickName;

- (void)say1;
- (void)say2;

+ (void)sayHappy;

@end
//person.m
#import "Person.h"

@implementation Person

- (void)saySomething{
    NSLog(@"Person say : %s",__func__);
}

- (void)say1{
    NSLog(@"Person say : %s",__func__);
}
- (void)say2{
    NSLog(@"Person say : %s",__func__);
}
- (void)say3{
    NSLog(@"Person say : %s",__func__);
}
- (void)say4{
    NSLog(@"Person say : %s",__func__);
}
- (void)say5{
    NSLog(@"Person say : %s",__func__);
}
- (void)say6{
    NSLog(@"Person say : %s",__func__);
}
- (void)say7{
    NSLog(@"Person say : %s",__func__);
}
//+ (void)load{
//    NSLog(@"load");
//}
+ (void)sayHappy{
    NSLog(@"LGPerson say : %s",__func__);
}
@end

//main.m
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        [Person sayHappy];
        Person *p = [Person alloc];
         }
    return 0;
}      
realizeClassWithoutSwift

在9里面打断点,发现跳过了,❓,为什么,我们看下备注 // Realize non-lazy classes (for +load methods and static instances)实现非懒加载类需要添加+load方法,我们在person.m中添加+load方法。 这个时候就进到了

            ...
            realizeClassWithoutSwift(cls, nil);
            ...

这个方法中,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 = (const class_ro_t *)cls->data();
    auto isMeta = ro->flags & RO_META;
     if (ro->flags & RO_FUTURE) {
        // 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 {//赋值ro, rw
        // Normal class. Allocate writeable class data. ro -> rw
        rw = objc::zalloc<class_rw_t>();
        rw->set_ro(ro);
        rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
        cls->setData(rw);
    }
    ...
    //superClass指向以及isa指向的构建
     supercls = realizeClassWithoutSwift(remapClass(cls->getSuperclass()), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
    ...
      // Update superclass and metaclass in case of remapping
    cls->setSuperclass(supercls);
    cls->initClassIsa(metacls);
    ...
    
       methodizeClass(cls, previously);

methodizeClass

看下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();
    ...
     method_list_t *list = ro->baseMethods();
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls), nullptr);
        if (rwe) rwe->methods.attachLists(&list, 1);
    }
    ...

如果list有值,会走一个prepareMethodLists的过程,我们的Person类中有很多方法,也会走这里,记得在前面的方法查找中有说过,对于已排序的查找,是二分查找,排序是什么时候排的呢,就是在这个方法中处理的。下面摘取主要代码

prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount,
                   bool baseMethods, bool methodsFromBundle, const char *why)
{
...
for (int i = 0; i < addedCount; i++) {
        method_list_t *mlist = addedLists[i];
        ASSERT(mlist);

        // Fixup selectors if necessary
        if (!mlist->isFixedUp()) {
            fixupMethodList(mlist, methodsFromBundle, true/*sort*/);
        }
    }

...
    
    }

fixupMethodList源码

fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
{
    runtimeLock.assertLocked();
    ASSERT(!mlist->isFixedUp());

    // fixme lock less in attachMethodLists ?
    // dyld3 may have already uniqued, but not sorted, the list
    if (!mlist->isUniqued()) {
        mutex_locker_t lock(selLock);
    
        // Unique selectors in list.
        for (auto& meth : *mlist) {
            const char *name = sel_cname(meth.name());
            
            // printf("上面 : %s - %p\n",name,meth.name());
            
            meth.setName(sel_registerNameNoLock(name, bundleCopy));
        }
    }

    // Sort by selector address.
    // Don't try to sort small lists, as they're immutable.
    // Don't try to sort big lists of nonstandard size, as stable_sort
    // won't copy the entries properly.
    if (sort && !mlist->isSmallList() && mlist->entsize() == method_t::bigSize) {
        method_t::SortBySELAddress sorter;
        std::stable_sort(&mlist->begin()->big(), &mlist->end()->big(), sorter);
    }
    
//    printf("****************");
//    for (auto& meth : *mlist) {
//        const char *name = sel_cname(meth.name());
//        printf("下面 : %s - %p\n",name,meth.name());
//    }
    
    // Mark method list as uniqued and sorted.
    // Can't mark small lists, since they're immutable.
    if (!mlist->isSmallList()) {
        mlist->setFixedUp();
    }
}

把排序前后的注释打开,可以看到方法按照了selecotr的地址,从小到大进行了排序

下面 : saySomething - 0x100003e06
下面 : say1 - 0x100003e13
下面 : say2 - 0x100003e18
下面 : say3 - 0x100003e1d
下面 : say4 - 0x100003e22
下面 : say5 - 0x100003e27
下面 : say6 - 0x100003e2c
下面 : say7 - 0x100003e31
下面 : lgName - 0x100003e36
下面 : setLgName: - 0x100003e3d
下面 : nickName - 0x7fff7bfbaf71
下面 : setNickName: - 0x7fff7bfbaf7a
懒加载类与非懒加载类

前面我们提到非懒加载类,非懒加载类的加载流程是在map_images的时候加载所有类

  • _read_images

  • readClass

  • realizeClassWithoutSwift

  • methodizeClass 那么什么是懒加载类,它又是怎么加载的呢。在person调用方法的时候,打一个断点,打印堆栈信息如下 截屏2021-07-16 上午7.22.23.png 懒加载类是将数据加载推迟到第一次消息的时候,

  • lookUpImpOrForward

  • realizeClassMaybeSwiftMaybeRelock

  • realizeClassWithoutSwift

  • methodizeClass