手撕iOS底层19 -- 类的加载【上卷】
在上篇手撕iOS底层18 -- dyld与libObjc那些事中,主要分析了
dyld与libobjc的如何关联调用,本篇目的理解类的相关信息,比如方法,属性,分类等信息是如何加载到内存的,重点是map_images和load_images函数。
map_images:主要是管理文件中和动态库中的所有符号,即class、protocol、selector、category等
load_images:加载执行load方法
代码是通过编译成Mach-O可执行文件,读取到Mach-O可执行文件后,再从Mach-O把类信息读取到内存中。
0x00 - map_images加载image到内存
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
在查看源码之前,首先需要说明为什么map_images有&,而load_images没有
map_images是引用类型,外界变了,跟着变。load_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
**********************************************************************/
// 处理由 dyld 映射的给定镜像
// 取得特定于 ABI 的锁后,调用与 ABI 无关的代码。
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);
}
- 关键代码是
map_images_nolock
void
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
const struct mach_header * const mhdrs[])
{
//...省略
// 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;
//代码块:作用域,进行局部处理,即局部处理一些事件
{
//...省略
}
//...省略
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]);
}
}
}
map_images_nolock 内部代码十分冗长,我们经过分析之后,前面的工作基本上都是进行镜像文件信息的提取与统计,所以可以定位到最后的 _read_images :
这里进入 _read_images 的条件是 hCount 大于 0, hCount 表示的是 Mach-O 中 header 的数量
我们的主角登场了, _read_images 和 lookupImpOrForward 可以说是我们学习 Runtime 和 iOS 底层里面非常重要的两个概念了, lookUpImpOrForward之前的篇章 已经探索过了,剩下的 _read_images 我们也不能落下。
0x01 -- _read_images源码实现
在_read_iamges方法中,主要做了如下这几件事情
- 1、条件控制进行的一次加载
- 2、修复预编译阶段的@selector的混乱问题
- 3、错误混乱的类处理
- 4、修复重映射一些没有被镜像文件加载进来的类
- 5、修复一些消息
- 6、当类里面有协议时:readProtocol 读取协议
- 7、修复没有被加载的协议
- 8、分类处理
- 9、类的加载处理
- 10、没有被处理的类,优化那些被侵犯的类
1. 条件控制进行的一次加载
if (!doneOnce) {
//...省略
initializeTaggedPointerObfuscator(); // 小对象
// namedClasses
// Preoptimized classes don't go in this table.
// 4/3 is NXMapTable's load factor
int namedClassesSize =
(isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
//创建表(哈希表key-value),目的是查找快
gdb_objc_realized_classes =
NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
ts.log("IMAGE TIMES: first time tasks");
}
// 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.
NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h
uintptr_t objc_debug_realized_class_generation_count;
查看gdb_objc_realized_classes是NXMapTalbe类型,通过注释说明,这个哈希表用于存储不在共享缓存且已命名类,无论类是否实现,其容量是类数量的4/3
2、修复预编译阶段的@selector的混乱问题
// Fix up @selector references 修复@selector引用
//sel 不是简单的字符串,而是带地址的字符串
static size_t UnfixedSelectors;
{
mutex_locker_t lock(selLock);
for (EACH_HEADER) {
if (hi->hasPreoptimizedSelectors()) continue;
bool isBundle = hi->isBundle();
//通过_getObjc2SelectorRefs拿到Mach-O中的静态段__objc_selrefs
SEL *sels = _getObjc2SelectorRefs(hi, &count);
UnfixedSelectors += count;
for (i = 0; i < count; i++) { //列表遍历
const char *name = sel_cname(sels[i]);
//注册sel操作,即将sel添加到
SEL sel = sel_registerNameNoLock(name, isBundle);
if (sels[i] != sel) {//当sel与sels[i]地址不一致时,需要调整为一致的
sels[i] = sel;
}
}
}
}
通过_getObjc2SelectorRefs来获取Mach-O中静态段数据__objc_selrefs数据,之后通过_getObjc2开头的获取Mach-O数据,都对应不同的section name
// function name content type section name
GETSECT(_getObjc2SelectorRefs, SEL, "__objc_selrefs");
GETSECT(_getObjc2MessageRefs, message_ref_t, "__objc_msgrefs");
GETSECT(_getObjc2ClassRefs, Class, "__objc_classrefs");
GETSECT(_getObjc2SuperRefs, Class, "__objc_superrefs");
GETSECT(_getObjc2ClassList, classref_t const, "__objc_classlist");
GETSECT(_getObjc2NonlazyClassList, classref_t const, "__objc_nlclslist");
GETSECT(_getObjc2CategoryList, category_t * const, "__objc_catlist");
GETSECT(_getObjc2CategoryList2, category_t * const, "__objc_catlist2");
GETSECT(_getObjc2NonlazyCategoryList, category_t * const, "__objc_nlcatlist");
GETSECT(_getObjc2ProtocolList, protocol_t * const, "__objc_protolist");
GETSECT(_getObjc2ProtocolRefs, protocol_t *, "__objc_protorefs");
GETSECT(getLibobjcInitializers, UnsignedInitializer, "__objc_init_func");
从Mach-O可以看到对应的各种数据段。
sel_registerNameNoLock ---> __sel_registerName 如下
SEL sel_registerNameNoLock(const char *name, bool copy) {
return __sel_registerName(name, 0, copy); // NO lock, maybe copy
}
static SEL __sel_registerName(const char *name, bool shouldLock, bool copy)
{
SEL result = 0;
if (shouldLock) selLock.assertUnlocked();
else selLock.assertLocked();
if (!name) return (SEL)0;
result = search_builtins(name);
if (result) return result;
conditional_mutex_locker_t lock(selLock, shouldLock);
auto it = namedSelectors.get().insert(name);
if (it.second) {
// No match. Insert.
*it.first = (const char *)sel_alloc(name, copy);
}
return (SEL)*it.first;
}
其关键代码是auto it = namedSelectors.get().insert(name);,即将sel插入namedSelectors哈希表
SEL并不是一个简简单单的字符串,而是一个带地址的字符串,sels[i]与sel字符串名字相同,但是地址并不一样,所以需要fix up
3、错误混乱的类处理
//3、错误混乱的类处理
// Discover classes. Fix up unresolved future classes. Mark bundle classes.
bool hasDyldRoots = dyld_shared_cache_some_image_overridden();
//读取类:readClass
for (EACH_HEADER) {
if (! mustReadClasses(hi, hasDyldRoots)) {
// Image is sufficiently optimized that we need not call readClass()
continue;
}
//从编译后的类列表中取出所有类,即从Mach-O中获取静态段__objc_classlist,是一个classref_t类型的指针
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];//此时获取的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");
主要从Mach-O获取类列表,遍历处理,通过调试,在readClass前,cls只是获取的一个地址,在readClass之后,就有了对应的名字
执行前
执行后
所以readClass是一个需要去重点研究的方法,之后去重点探索。所以到这步为止,类的信息目前仅存储了地址+名称
4、修复重映射一些没有被镜像文件加载进来的类
//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]);
}
}
}
ts.log("IMAGE TIMES: remap classes");
主要是将未映射的Class 和Super Class进行重映射,其中
_getObjc2ClassRefs是获取Mach-O中的静态段__objc_classrefs即类的引用_getObjc2SuperRefs是获取Mach-O中的静态段__objc_superrefs即父类的引用- 通过注释可以得知,被
remapClassRef的类都是懒加载的类,所以最初经过调试时,这部分代码是没有执行的
5、修复一些消息
#if SUPPORT_FIXUP
//5、修复一些消息
// Fix up old objc_msgSend_fixup call sites
for (EACH_HEADER) {
// _getObjc2MessageRefs 获取Mach-O的静态段 __objc_msgrefs
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里面的流程
//遍历将函数指针进行注册,并fix为新的函数指针
for (i = 0; i < count; i++) {
fixupMessageRef(refs+i);
}
}
ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif
主要是通过_getObjc2MessageRefs 获取Mach-O的静态段 __objc_msgrefs,并遍历通过fixupMessageRef将函数指针进行注册,并fix为新的函数指针
6、当类里面有协议时:readProtocol 读取协议
//6、当类里面有协议时:readProtocol 读取协议
// Discover protocols. Fix up protocol refs. 发现协议。修正协议参考
//遍历所有协议列表,并且将协议列表加载到Protocol的哈希表中
for (EACH_HEADER) {
extern objc_class OBJC_CLASS_$_Protocol;
//cls = Protocol类,所有协议和对象的结构体都类似,isa都对应Protocol类
Class cls = (Class)&OBJC_CLASS_$_Protocol;
ASSERT(cls);
//获取protocol哈希表 -- protocol_map
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 && cacheSupportsProtocolRoots) {
if (PrintProtocols) {
_objc_inform("PROTOCOLS: Skipping reading protocols in image: %s",
hi->fname());
}
continue;
}
bool isBundle = hi->isBundle();
//通过_getObjc2ProtocolList 获取到Mach-O中的静态段__objc_protolist协议列表,
//即从编译器中读取并初始化protocol
protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
for (i = 0; i < count; i++) {
//通过添加protocol到protocol_map哈希表中
readProtocol(protolist[i], cls, protocol_map,
isPreoptimized, isBundle);
}
}
ts.log("IMAGE TIMES: discover protocols");
通过NXMapTable *protocol_map = protocols();获取协议protocol_map的哈希表,
/***********************************************************************
* 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();
INIT_ONCE_PTR(protocol_map,
NXCreateMapTable(NXStrValueMapPrototype, 16),
NXFreeMapTable(v) );
return protocol_map;
}
通过_getObjc2ProtocolList读取到Mach-O里到协议列表,
protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
遍历加到protocol_map中
readProtocol(protolist[i], cls, protocol_map, isPreoptimized, isBundle);
7、修复没有被加载的协议
//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");
主要是通过 _getObjc2ProtocolRefs 获取到Mach-O的静态段 __objc_protorefs(与6中的__objc_protolist并不是同一个东西),然后遍历需要修复的协议,通过remapProtocolRef比较当前协议和协议列表中的同一个内存地址的协议是否相同,如果不同则替换
remapProtocolRef:
/***********************************************************************
* 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、分类处理
//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);
}
}
ts.log("IMAGE TIMES: discover categories");
主要是处理分类,需要在分类初始化并将数据加载到类后才执行,对于运行时出现的分类,将分类的发现推迟推迟到对_dyld_objc_notify_register的调用完成后的第一个load_images调用为止
9、类的加载处理
// 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);
}
}
ts.log("IMAGE TIMES: realize non-lazy classes");
实现类的加载处理,实现非懒加载类 non-lazy classes
- 通过
_getObjc2NonlazyClassList获取Mach-O非懒加载类列表 - 通过
addClassTableEntry将非懒加载类插入hash表,存到内存,如果已经添加就不会载添加,需要确保整个结构都被添加 - 通过
realizeClassWithoutSwift实现当前的类,因为前面3中的readClass读取到内存的仅仅只有地址+名称,类的data数据并没有加载出来
10、没有被处理的类,优化那些被侵犯的类
// 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();
}
主要是实现没有被处理的类,优化被侵犯的类
**总结:**通过以上简单的分析_read_images,得出的重点就是分析readClass和realizeClassWithoutSwift这俩个类。
0x02 -- readClass分析
/***********************************************************************
* 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();//名字
// **LG写的** ----如果想进入自定义,自己加一个判断
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;
}
- 首先通过
cls->mangleName()获取类的名字
const char *mangledName() {
// fixme can't assert locks here
ASSERT(this);
if (isRealized() || isFuture()) { //这个初始化判断在lookupImp也有类似的
return data()->ro()->name;//如果已经实例化,则从ro中获取name
} else {
return ((const class_ro_t *)data())->name;//反之,从mach-O的数据data中获取name
}
}
- 当前
cls的父类如果有丢失weak-linked类,返回nil - 接着判断是不是未来要处理的类,正常不会走到
if里面,因为专门针对未来待处理的类的操作,并通过调试,也没有走到ifli ,因此不会对里面的ro,rw操作。data()是machO数据,还未在内存中。ro的赋值是从`machO中的data强转类型赋值的。rw的数据是从ro复制过去的。
- 通过
addNameClass将cls和name以键值对的方式放到gdb_objc_realized_classes这个表里。该表用于存放所有的类,name为key,cls为value。
/***********************************************************************
* 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,将初始化的类添加到allocatedClasses表,此表allocatedClasses在_objc_init中的runtime_init中初始化的。
/***********************************************************************
* 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);
}
精确定位到自己想调试的类,也就是自己创建的类,可以在源码中加入自己的调试代码:
总结:
综上所述,readClass主要将Mach-O各个段的数据读取到内存,即插入表中,但是值有类名和类地址,其它的类数据并没有读出来,也就是这个类还没有实现,待下篇详细分析ro, rw, rxt是如何初始化。😊