认识_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();
static_init();
runtime_init();
exception_init();
cache_init();
_imp_implementationWithBlock_init();
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
#if __OBJC2__
didCallDyldNotifyRegister = true;
#endif
}
environ_init()
环境变量初始化
读取影响运行时的环境变量。如果需要,还可以打印环境变量帮助。
将核心代码提出出来,去除设定条件,直接打印
for (size_t i = 0; i < sizeof(Settings)/sizeof(Settings[0]); i++) {
const option_t *opt = &Settings[i];
if (PrintHelp) _objc_inform("%s: %s", opt->env, opt->help);
if (PrintOptions && *opt->var) _objc_inform("%s is set", opt->env);
}
打印结果
objc[1877]: OBJC_PRINT_IMAGES: log image and library names as they are loaded
objc[1877]: OBJC_PRINT_IMAGES is set
objc[1877]: OBJC_PRINT_IMAGE_TIMES: measure duration of image loading steps
objc[1877]: OBJC_PRINT_IMAGE_TIMES is set
objc[1877]: OBJC_PRINT_LOAD_METHODS: log calls to class and category +load methods
objc[1877]: OBJC_PRINT_LOAD_METHODS is set
objc[1877]: OBJC_PRINT_INITIALIZE_METHODS: log calls to class +initialize methods
objc[1877]: OBJC_PRINT_INITIALIZE_METHODS is set
objc[1877]: OBJC_PRINT_RESOLVED_METHODS: log methods created by +resolveClassMethod: and +resolveInstanceMethod:
objc[1877]: OBJC_PRINT_RESOLVED_METHODS is set
objc[1877]: OBJC_PRINT_CLASS_SETUP: log progress of class and category setup
objc[1877]: OBJC_PRINT_CLASS_SETUP is set
objc[1877]: OBJC_PRINT_PROTOCOL_SETUP: log progress of protocol setup
objc[1877]: OBJC_PRINT_PROTOCOL_SETUP is set
objc[1877]: OBJC_PRINT_IVAR_SETUP: log processing of non-fragile ivars
objc[1877]: OBJC_PRINT_IVAR_SETUP is set
objc[1877]: OBJC_PRINT_VTABLE_SETUP: log processing of class vtables
objc[1877]: OBJC_PRINT_VTABLE_SETUP is set
objc[1877]: OBJC_PRINT_VTABLE_IMAGES: print vtable images showing overridden methods
objc[1877]: OBJC_PRINT_VTABLE_IMAGES is set
objc[1877]: OBJC_PRINT_CACHE_SETUP: log processing of method caches
objc[1877]: OBJC_PRINT_CACHE_SETUP is set
objc[1877]: OBJC_PRINT_FUTURE_CLASSES: log use of future classes for toll-free bridging
objc[1877]: OBJC_PRINT_FUTURE_CLASSES is set
objc[1877]: OBJC_PRINT_PREOPTIMIZATION: log preoptimization courtesy of dyld shared cache
objc[1877]: OBJC_PRINT_PREOPTIMIZATION is set
objc[1877]: OBJC_PRINT_CXX_CTORS: log calls to C++ ctors and dtors for instance variables
objc[1877]: OBJC_PRINT_CXX_CTORS is set
objc[1877]: OBJC_PRINT_EXCEPTIONS: log exception handling
objc[1877]: OBJC_PRINT_EXCEPTIONS is set
objc[1877]: OBJC_PRINT_EXCEPTION_THROW: log backtrace of every objc_exception_throw()
objc[1877]: OBJC_PRINT_EXCEPTION_THROW is set
objc[1877]: OBJC_PRINT_ALT_HANDLERS: log processing of exception alt handlers
objc[1877]: OBJC_PRINT_ALT_HANDLERS is set
objc[1877]: OBJC_PRINT_REPLACED_METHODS: log methods replaced by category implementations
objc[1877]: OBJC_PRINT_REPLACED_METHODS is set
objc[1877]: OBJC_PRINT_DEPRECATION_WARNINGS: warn about calls to deprecated runtime functions
objc[1877]: OBJC_PRINT_DEPRECATION_WARNINGS is set
objc[1877]: OBJC_PRINT_POOL_HIGHWATER: log high-water marks for autorelease pools
objc[1877]: OBJC_PRINT_POOL_HIGHWATER is set
objc[1877]: OBJC_PRINT_CUSTOM_CORE: log classes with custom core methods
objc[1877]: OBJC_PRINT_CUSTOM_CORE is set
objc[1877]: OBJC_PRINT_CUSTOM_RR: log classes with custom retain/release methods
objc[1877]: OBJC_PRINT_CUSTOM_RR is set
objc[1877]: OBJC_PRINT_CUSTOM_AWZ: log classes with custom allocWithZone methods
objc[1877]: OBJC_PRINT_CUSTOM_AWZ is set
objc[1877]: OBJC_PRINT_RAW_ISA: log classes that require raw pointer isa fields
objc[1877]: OBJC_PRINT_RAW_ISA is set
objc[1877]: OBJC_DEBUG_UNLOAD: warn about poorly-behaving bundles when unloaded
objc[1877]: OBJC_DEBUG_UNLOAD is set
objc[1877]: OBJC_DEBUG_FRAGILE_SUPERCLASSES: warn about subclasses that may have been broken by subsequent changes to superclasses
objc[1877]: OBJC_DEBUG_FRAGILE_SUPERCLASSES is set
objc[1877]: OBJC_DEBUG_NIL_SYNC: warn about @synchronized(nil), which does no synchronization
objc[1877]: OBJC_DEBUG_NIL_SYNC is set
objc[1877]: OBJC_DEBUG_NONFRAGILE_IVARS: capriciously rearrange non-fragile ivars
objc[1877]: OBJC_DEBUG_NONFRAGILE_IVARS is set
objc[1877]: OBJC_DEBUG_ALT_HANDLERS: record more info about bad alt handler use
objc[1877]: OBJC_DEBUG_ALT_HANDLERS is set
objc[1877]: OBJC_DEBUG_MISSING_POOLS: warn about autorelease with no pool in place, which may be a leak
objc[1877]: OBJC_DEBUG_MISSING_POOLS is set
objc[1877]: OBJC_DEBUG_POOL_ALLOCATION: halt when autorelease pools are popped out of order, and allow heap debuggers to track autorelease pools
objc[1877]: OBJC_DEBUG_POOL_ALLOCATION is set
objc[1877]: OBJC_DEBUG_DUPLICATE_CLASSES: halt when multiple classes with the same name are present
objc[1877]: OBJC_DEBUG_DUPLICATE_CLASSES is set
objc[1877]: OBJC_DEBUG_DONT_CRASH: halt the process by exiting instead of crashing
objc[1877]: OBJC_DEBUG_DONT_CRASH is set
objc[1877]: OBJC_DISABLE_VTABLES: disable vtable dispatch
objc[1877]: OBJC_DISABLE_VTABLES is set
objc[1877]: OBJC_DISABLE_PREOPTIMIZATION: disable preoptimization courtesy of dyld shared cache
objc[1877]: OBJC_DISABLE_PREOPTIMIZATION is set
objc[1877]: OBJC_DISABLE_TAGGED_POINTERS: disable tagged pointer optimization of NSNumber et al.
objc[1877]: OBJC_DISABLE_TAGGED_POINTERS is set
objc[1877]: OBJC_DISABLE_TAG_OBFUSCATION: disable obfuscation of tagged pointers
objc[1877]: OBJC_DISABLE_TAG_OBFUSCATION is set
objc[1877]: OBJC_DISABLE_NONPOINTER_ISA: disable non-pointer isa fields
objc[1877]: OBJC_DISABLE_NONPOINTER_ISA is set
objc[1877]: OBJC_DISABLE_INITIALIZE_FORK_SAFETY: disable safety checks for +initialize after fork
objc[1877]: OBJC_DISABLE_INITIALIZE_FORK_SAFETY is set
OBJC_DISABLE_NONPOINTER_ISA
:
首先进行lldb调试
我们设置OBJC_DISABLE_NONPOINTER_ISA
在lldb打印对象
0x101b32520: 0x0000000100002260 0x0000000000000000
0x101b32530: 0x0000000000000000 0x0000000000000000
(lldb) p/t 0x0000000100002260
(long) $1 = 0b0000000000000000000000000000000100000000000000000010001001100000
去除环境变量后:
(lldb) x/4gx person
0x101908400: 0x001d800100002265 0x0000000000000000
0x101908410: 0x0000000000000000 0x0000000000000000
(lldb) p/t 0x001d800100002265
(long) $2 = 0b0000000000011101100000000000000100000000000000000010001001100101
我们可以看到最后一位由0变成1,最后一位就是 nonpointer 位,表示是否对 isa 指针开启指针优化。 0:纯 isa 指针;1:不止是类对象地址。isa 中包含了类信息、对象的引用计数等。
接下来我们设置OBJC_PRINT_LOAD_METHODS = YES
,就饿会在控制台打印所有调用+load
的地方
...
objc[2228]: LOAD: +[NSApplication load]
objc[2228]: LOAD: +[NSBinder load]
objc[2228]: LOAD: +[NSColorSpaceColor load]
objc[2228]: LOAD: +[NSNextStepFrame load]
objc[2228]: LOAD: +[NSColor(NSUIKitSupport) load]
objc[2228]: LOAD: category 'NSError(FPAdditions)' scheduled for +load
objc[2228]: LOAD: +[NSError(FPAdditions) load]
objc[2228]: LOAD: class '_DKEventQuery' scheduled for +load
objc[2228]: LOAD: +[_DKEventQuery load]
objc[2228]: LOAD: class 'LGPerson' scheduled for +load
objc[2228]: LOAD: +[LGPerson load]
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 ++静态构造函数。在dyld调⽤我们的静态构造函数之前,libc
会调⽤ _objc_init(),因此我们必须⾃⼰做
/***********************************************************************
* static_init
* Run C++ static constructor functions.
* libc calls _objc_init() before dyld would call our static constructors,
* so we have to do it ourselves.
**********************************************************************/
static void static_init()
{
size_t count;
auto inits = getLibobjcInitializers(&_mh_dylib_header, &count);
for (size_t i = 0; i < count; i++) {
inits[i]();
}
}
runtime_init()
运行时初始化
初始化一些分类,和class表
void runtime_init(void)
{
objc::unattachedCategories.init(32);
objc::allocatedClasses.init();
}
exception_init ()
初始化libobjc的异常处理系统
void exception_init(void)
{
old_terminate = std::set_terminate(&_objc_terminate);
}
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)();
}
}
}
static objc_uncaught_exception_handler uncaught_handler = _objc_default_uncaught_exception_handler;
/***********************************************************************
* objc_setUncaughtExceptionHandler
* Set a handler for uncaught Objective-C exceptions.
* Returns the previous handler.
**********************************************************************/
objc_uncaught_exception_handler
objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
{
objc_uncaught_exception_handler result = uncaught_handler;
uncaught_handler = fn;
return result;
}
我们在程序崩溃前就会调用我们保存的函数
我们测试一下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSSetUncaughtExceptionHandler(&printException);
return YES;
}
void printException(){
printf("%s",__func__);
}
@interface ViewController ()
@property(nonatomic,strong)NSArray *arr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.arr = @[@"1",@"2"];
}
- (IBAction)action:(id)sender {
self.arr[100];
}
@end
点击按钮之后就会调用我们设置printException()
方法
cache_init()
缓存条件初始化
_imp_implementationWithBlock_init
:启动回调机制。通常这不会做什么,因为所有的初始化都是惰性的,但是对于某些进程,我们会迫不及待地加载trampolines dylib
。
_dyld_objc_notify_register
:这个方法是跨库执行的,在苹果开源的 dyld 源码里面可以找到,然后看到上文中我们所说道的 dyld::registerObjCNotifiers 这个方法
void registerObjCNotifiers(_dyld_objc_notify_mapped mapped, _dyld_objc_notify_init init, _dyld_objc_notify_unmapped unmapped)
{
// record functions to call
sNotifyObjCMapped = mapped;
sNotifyObjCInit = init;
sNotifyObjCUnmapped = unmapped;
// call 'mapped' function with all images mapped so far
try {
notifyBatchPartial(dyld_image_state_bound, true, NULL, false, true);
}
catch (const char* msg) {
// ignore request to abort during registration
}
// <rdar://problem/32209809> call 'init' function on all images already init'ed (below libSystem)
for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
ImageLoader* image = *it;
if ( (image->getState() == dyld_image_state_initialized) && image->notifyObjC() ) {
dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_INIT, (uint64_t)image->machHeader(), 0, 0);
(*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
}
}
}
在特定地时候我们可以回调在_dyld_objc_notify_register
中设置的方法。
我们先看map_images
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);
}
void
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
/***********************************************************************
* _read_images
* Perform initial processing of the headers in the linked
* list beginning with headerList.
*
* Called by: map_images_nolock
*
* Locking: runtimeLock acquired by map_images
*对链接的标题进行初始化处理
以headerList开头的list。
*
*调用:map_images_nolock
*
*锁定:通过map_images获取runtimeLock
**********************************************************************/
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++
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_get_program_sdk_version() < DYLD_MACOSX_VERSION_10_11) {
DisableNonpointerIsa = true;
if (PrintRawIsa) {
_objc_inform("RAW ISA: disabling non-pointer isa because "
"the app is too old (SDK version " SDK_FORMAT ")",
FORMAT_SDK(dyld_get_program_sdk_version()));
}
}
// 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
//把class放入表中,更加快速的查找
int namedClassesSize =
(isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
gdb_objc_realized_classes =
NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
ts.log("IMAGE TIMES: first time tasks");
}
// Fix up @selector references
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();
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];
//打印cls还是地址
Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);
//打印cls显示的是名字
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.
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
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
bool cacheSupportsProtocolRoots = sharedCacheSupportsProtocolRoots();
// 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 && cacheSupportsProtocolRoots) {
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.
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;
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
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)
//实现非延迟类(用于+加载方法和静态实例)
for (EACH_HEADER) {
classref_t const *classlist =
_getObjc2NonlazyClassList(hi, &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
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
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 = ((class_ro_t *)cls->data())->baseMethods())) {
PreoptTotalMethodLists++;
if (mlist->isFixedUp()) {
PreoptOptimizedMethodLists++;
}
}
if ((mlist=((class_ro_t *)cls->ISA()->data())->baseMethods())) {
PreoptTotalMethodLists++;
if (mlist->isFixedUp()) {
PreoptOptimizedMethodLists++;
}
}
}
}
...
}
#undef EACH_HEADER
}
- 条件控制进⾏⼀次的加载
- 修复预编译阶段的
@selector
的混乱问题 - 错误混乱的类处理
- 修复重映射⼀些没有被镜像⽂件加载进来的 类
- 修复⼀些消息!
- 当我们类⾥⾯有协议的时候 :
readProtocol
- 修复没有被加载的协议
- 分类处理
- 类的加载处理
- 没有被处理的类 优化那些被侵犯的类
我们来研究readClass()
,因为在调试代码时候加载的class太多,所以我们加个条件好进行调试
Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
const char *mangledName = cls->mangledName();
//自己添加的
const char *LGPersonName = "LGPerson";
if (strcmp(mangledName, LGPersonName) == 0) {
printf("%s - xxxx - %s \n",__func__,mangledName);
}
//自己添加的
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();
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.
//这个名称以前被分配为一个将来的类。
//将objc_class复制到未来类的结构体。
//保存future的rw数据块。
//本次不作处理
if (newCls->isAnySwift()) {
_objc_fatal("Can't complete future class request for '%s' "
"because the real class is too big.",
cls->nameForLogging());
}
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);
//添加到之前的class表中,从表中读取
addClassTableEntry(cls);
}
// 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;
}
网友评论