// Find all images with Objective-C metadata.查找所有带有Objective-C元数据的映像 hCount = 0;
// Count classes. Size various table based on the total.计算类的个数 int totalClasses = 0; int unoptimizedTotalClasses = 0; // 代码块:作用域,进行局部处理,即局部处理一些事件 { //...省略 } //...省略
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]); } } }
// 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. //gdb_objc_realized_classes实际上是不在dyld共享缓存中的已命名类的列表,无论是否实现 NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h
2、修复预编译阶段的@selector的混乱问题
主要是通过通过 _getObjc2SelectorRefs 拿到Mach_O中的静态段 __objc_selrefs,遍历列表调用 sel_registerNameNoLock 将 SEL 添加到 namedSelectors 哈希表中
sel_registerNameNoLock 源码路径如下:sel_registerNameNoLock -> __sel_registerName,如下所示,其关键代码是 auto it = namedSelectors.get().insert(name);,即将sel插入 namedSelectors 哈希表
for (i = 0; i < count; i++) { Class cls = (Class)classlist[i];//此时获取的cls只是一个地址 Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized); //读取类,经过这步后,cls获取的值才是一个名字 // 经过调试,并未执行if里面的流程 // 初始化所有懒加载的类需要的内存空间,但是懒加载类的数据现在是没有加载到的,连类都没有初始化 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、修复重映射一些没有被镜像文件加载进来的类 // Fix up remapped classes 修正重新映射的类 // Class list and nonlazy class list remain unremapped.类列表和非惰性类列表保持未映射 // Class refs and super refs are remapped for message dispatching.类引用和超级引用将重新映射以进行消息分发 //经过调试,并未执行if里面的流程 //将未映射的Class 和 Super Class重映射,被remap的类都是懒加载的类 if (!noClassesRemapped()) { for (EACH_HEADER) { Class *classrefs = _getObjc2ClassRefs(hi, &count);//Mach-O的静态段 __objc_classrefs for (i = 0; i < count; i++) { remapClassRef(&classrefs[i]); } // fixme why doesn't test future1 catch the absence of this? classrefs = _getObjc2SuperRefs(hi, &count);//Mach_O中的静态段 __objc_superrefs for (i = 0; i < count; i++) { remapClassRef(&classrefs[i]); } } }
// 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 && cacheSupportsProtocolRoots) { if (PrintProtocols) { _objc_inform("PROTOCOLS: Skipping reading protocols in image: %s", hi->fname()); } continue; }
/*********************************************************************** * protocols * Returns the protocol name => protocol map for protocols. * Locking: runtimeLock must read- or write-locked by the caller **********************************************************************/ static NXMapTable *protocols(void) { static NXMapTable *protocol_map = nil; runtimeLock.assertLocked();
//7、修复没有被加载的协议 // Fix up @protocol references // Preoptimized images may have the right // answer already but we don't know for sure. 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 && cacheSupportsProtocolRoots && hi->isPreoptimized()) continue; //_getObjc2ProtocolRefs 获取到Mach-O的静态段 __objc_protorefs protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count); for (i = 0; i < count; i++) {//遍历 //比较当前协议和协议列表中的同一个内存地址的协议是否相同,如果不同则替换 remapProtocolRef(&protolist[i]);//经过代码调试,并未执行 } }
ts.log("IMAGE TIMES: fix up @protocol references");
其中 remapProtocolRef 的源码实现如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*********************************************************************** * remapProtocolRef * Fix up a protocol ref, in case the protocol referenced has been reallocated. * Locking: runtimeLock must be read- or write-locked by the caller **********************************************************************/ static size_t UnfixedProtocolReferences; static void remapProtocolRef(protocol_t **protoref) { runtimeLock.assertLocked(); //获取协议列表中统一内存地址的协议 protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref); if (*protoref != newproto) {//如果当前协议 与 同一内存地址协议不同,则替换 *protoref = newproto; UnfixedProtocolReferences++; } }
// 8、分类处理 // 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 if (didInitialAttachCategories) { for (EACH_HEADER) { load_categories_nolock(hi); } }
// Realize non-lazy classes (for +load methods and static instances) 初始化非懒加载类,进行rw、ro等操作:realizeClassWithoutSwift //懒加载类 -- 别人不动我,我就不动 //实现非懒加载的类,对于load方法和静态实例变量 for (EACH_HEADER) { //通过_getObjc2NonlazyClassList获取Mach-O的静态段__objc_nlclslist非懒加载类表 classref_t const *classlist = _getObjc2NonlazyClassList(hi, &count); for (i = 0; i < count; i++) { Class cls = remapClass(classlist[i]); const char *mangledName = cls->mangledName(); const char *LGPersonName = "LGPerson"; if (strcmp(mangledName, LGPersonName) == 0) { auto kc_ro = (const class_ro_t *)cls->data(); printf("_getObjc2NonlazyClassList: 这个是我要研究的 %s \n",LGPersonName); } 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 } //实现当前的类,因为前面readClass读取到内存的仅仅只有地址+名称,类的data数据并没有加载出来 //实现所有非懒加载的类(实例化类对象的一些信息,例如rw) realizeClassWithoutSwift(cls, nil); } }
// Realize newly-resolved future classes, in case CF manipulates them if (resolvedFutureClasses) { for (i = 0; i < resolvedFutureClassCount; i++) { Class cls = resolvedFutureClasses[i]; if (cls->isSwiftStable()) { _objc_fatal("Swift class is not allowed to be future"); } //实现类 realizeClassWithoutSwift(cls, nil); cls->setInstancesRequireRawIsaRecursively(false/*inherited*/); } free(resolvedFutureClasses); }
ts.log("IMAGE TIMES: realize future classes");
if (DebugNonFragileIvars) { //实现所有类 realizeAllClasses(); }
/*********************************************************************** * readClass * Read a class and metaclass as written by a compiler. 读取编译器编写的类和元类 * Returns the new class pointer. This could be: 返回新的类指针,可能是: * - cls * - nil (cls has a missing weak-linked superclass) * - something else (space for this class was reserved by a future class) * * Note that all work performed by this function is preflighted by * mustReadClasses(). Do not change this function without updating that one. * * Locking: runtimeLock acquired by map_images or objc_readClassPair **********************************************************************/ Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized) { const char *mangledName = cls->mangledName();//名字 // **CJL写的** ----如果想进入自定义,自己加一个判断 const char *LGPersonName = "LGPerson"; if (strcmp(mangledName, LGPersonName) == 0) { auto kc_ro = (const class_ro_t *)cls->data(); printf("%s -- 研究重点--%s\n", __func__,mangledName); } // 当前类的父类中若有丢失的weak-linked类,则返回nil if (missingWeakSuperclass(cls)) { // No superclass (probably weak-linked). // Disavow any knowledge of this subclass. if (PrintConnecting) { _objc_inform("CLASS: IGNORING class '%s' with " "missing weak-linked superclass", cls->nameForLogging()); } addRemappedClass(cls, nil); cls->superclass = nil; return nil; } cls->fixupBackwardDeployingStableSwift(); // 判断是不是后期要处理的类 // 正常情况下,不会走到popFutureNamedClass,因为这是专门针对未来待处理的类的操作 // 通过断点调试,不会走到if流程里面,因此也不会对ro、rw进行操作 Class replacing = nil; if (Class newCls = popFutureNamedClass(mangledName)) { // This name was previously allocated as a future class. // Copy objc_class to future class's struct. // Preserve future's rw data block. if (newCls->isAnySwift()) { _objc_fatal("Can't complete future class request for '%s' " "because the real class is too big.", cls->nameForLogging()); } // 读取class的data,设置ro、rw // 经过调试,并不会走到这里 class_rw_t *rw = newCls->data(); const class_ro_t *old_ro = rw->ro(); memcpy(newCls, cls, sizeof(objc_class)); rw->set_ro((class_ro_t *)newCls->data()); newCls->setData(rw); freeIfMutable((char *)old_ro->name); free((void *)old_ro); addRemappedClass(cls, newCls); replacing = cls; cls = newCls; } // 判断是否类是否已经加载到内存 if (headerIsPreoptimized && !replacing) { // class list built in shared cache // fixme strict assert doesn't work because of duplicates // ASSERT(cls == getClass(name)); ASSERT(getClassExceptSomeSwift(mangledName)); } else { addNamedClass(cls, mangledName, replacing);//加载共享缓存中的类 addClassTableEntry(cls);//插入表,即相当于从mach-O文件 读取到 内存 中 }
// 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; }
/*********************************************************************** * addNamedClass 加载共享缓存中的类 插入表 * Adds name => cls to the named non-meta class map. 将name=> cls添加到命名的非元类映射 * Warns about duplicate class names and keeps the old mapping. * Locking: runtimeLock must be held by the caller **********************************************************************/ 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 { //添加到gdb_objc_realized_classes哈希表 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()); }
/*********************************************************************** * addClassTableEntry 将一个类添加到所有类的表中 * Add a class to the table of all classes. If addMeta is true, * automatically adds the metaclass of the class as well. * Locking: runtimeLock must be held by the caller. **********************************************************************/ 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();//开辟的类的表,在objc_init中的runtime_init就创建了表
ASSERT(set.find(cls) == set.end());
if (!isKnownClass(cls)) set.insert(cls); if (addMeta) //添加到allocatedClasses哈希表 addClassTableEntry(cls->ISA(), false); }
// fixme verify class is not in an un-dlopened part of the shared cache? //读取class的data(),以及ro/rw创建 auto ro = (const class_ro_t *)cls->data(); //读取类结构的bits属性、//ro -- clean memory,在编译时就已经确定了内存 auto isMeta = ro->flags & RO_META; //判断元类 if (ro->flags & RO_FUTURE) { // This was a future class. rw data is already allocated. rw = cls->data(); //dirty memory 进行赋值 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>(); //申请开辟zalloc -- rw rw->set_ro(ro);//rw中的ro设置为临时变量ro rw->flags = RW_REALIZED|RW_REALIZING|isMeta; cls->setData(rw);//将cls的data赋值为rw形式 }
// 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. -- //递归调用realizeClassWithoutSwift完善继承链,并处理当前类的父类、元类 //递归实现 设置当前类、父类、元类的 rw,主要目的是确定继承链 (类继承链、元类继承链) //实现元类、父类 //当isa找到根元类之后,根元类的isa是指向自己的,不会返回nil从而导致死循环——remapClass中对类在表中进行查找的操作,如果表中已有该类,则返回一个空值;如果没有则返回当前类,这样保证了类只加载一次并结束递归 supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil); metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil); ...
// Update superclass and metaclass in case of remapping -- class 是 双向链表结构 即父子关系都确认了 // 将父类和元类给我们的类 分别是isa和父类的对应值 cls->superclass = supercls; cls->initClassIsa(metacls);
...
// Connect this class to its superclass's subclass lists //双向链表指向关系 父类中可以找到子类 子类中也可以找到父类 //通过addSubclass把当前类放到父类的子类列表中去 if (supercls) { addSubclass(supercls, cls); } else { addRootClass(cls); }
这里有一个问题,realizeClassWithoutSwift 递归调用时,isa 找到 根元类 之后,根元类的 isa 是 指向自己,并不会返回 nil,所以有以下递归终止条件,其目的是保证类只加载一次
在 realizeClassWithoutSwift 中
如果类 不存在,则返回 nil
如果类 已经实现,则直接返回 cls
1 2 3 4 5 6 7 8 9 10 11 12
static Class realizeClassWithoutSwift(Class cls, Class previously) { runtimeLock.assertLocked(); //如果类不存在,则返回nil if (!cls) return nil; 如果类已经实现,则直接返回cls if (cls->isRealized()) return cls; ASSERT(cls == remapClass(cls)); ... }
/*********************************************************************** * remapClass * Returns the live class pointer for cls, which may be pointing to * a class struct that has been reallocated. * Returns nil if cls is ignored because of weak linking. * Locking: runtimeLock must be read- or write-locked by the caller **********************************************************************/ static Class remapClass(Class cls) { runtimeLock.assertLocked();
if (!cls) return nil;//如果cls不存在,则返回nil
auto *map = remappedClasses(NO); if (!map) return cls; auto iterator = map->find(cls); if (iterator == map->end()) return cls; return std::get<1>(*iterator); }
static void methodizeClass(Class cls, Class previously) { runtimeLock.assertLocked();
bool isMeta = cls->isMetaClass(); auto rw = cls->data(); // 初始化一个rw auto ro = rw->ro(); auto rwe = rw->ext(); ...
// Install methods and properties that the class implements itself. //将属性列表、方法列表、协议列表等贴到rw中 // 将ro中的方法列表加入到rw中 method_list_t *list = ro->baseMethods();//获取ro的baseMethods if (list) { prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));//methods进行排序 if (rwe) rwe->methods.attachLists(&list, 1);//对rwe进行处理 } // 加入属性 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 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);
// 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); meth.name = sel_registerNameNoLock(name, bundleCopy); } }
// Sort by selector address.根据sel地址排序 if (sort) { method_t::SortBySELAddress sorter; std::stable_sort(mlist->begin(), mlist->end(), sorter); } // Mark method list as uniqued and sorted mlist->setFixedUp(); }
验证方法排序
下面我们可以通过 调试来验证 方法的排序
在 methodizeClass 方法中添加自定义逻辑,并断住
读取 ro 中的 methodlist
p kc_ro
p $0->baseMethodList(通过 auto kc_ro = kc_rw->ro(); – ro() – class_ro_t类型查看属性)
/* * Only a few classes have more than 64 categories during launch. * This uses a little stack, and avoids malloc. * * Categories must be added in the proper order, which is back * to front. To do that with the chunking, we iterate cats_list * from front to back, build up the local buffers backwards, * and call attachLists on the chunks. attachLists prepends the * lists, so the final result is in the expected order. */ constexpr uint32_t ATTACH_BUFSIZ = 64; method_list_t *mlists[ATTACH_BUFSIZ]; property_list_t *proplists[ATTACH_BUFSIZ]; protocol_list_t *protolists[ATTACH_BUFSIZ];
method_list_t *list = ro->baseMethods(); if (list) { if (deepCopy) list = list->duplicate(); rwe->methods.attachLists(&list, 1); }
// See comments in objc_duplicateClass // property lists and protocol lists historically // have not been deep-copied // // This is probably wrong and ought to be fixed some day property_list_t *proplist = ro->baseProperties; if (proplist) { rwe->properties.attachLists(&proplist, 1); }
protocol_list_t *protolist = ro->baseProtocols; if (protolist) { rwe->protocols.attachLists(&protolist, 1); }