【MobileSubstrate】
Cydia Substrate (formerly called MobileSubstrate) is the de facto framework that allows 3rd-party developers to provide run-time patches (“Cydia Substrate extensions”) to system functions.
MobileSubstrate也叫CydiaSubstrate,是一个基础架构,允许第三方开发者为系统功能提供CydiaSubstrateExtension(也叫做tweaks)。
Cydia Substrate consists of 3 major components: MobileHooker, MobileLoader and safe mode.
CydiaSubstrate提供3个主要的组件:MobileHook,MobileLoader,safeMode。
【MobileHook】
MobileHooker is used to replace system functions. This process is known as hooking. There are 2 APIs that one would use:
MSHookMessage() will replace the implementation of the Objective-C message -[class selector] by replacement, and return the original implementation. To hook a class method, provide the meta class retrieved from objc_getMetaClass in the MSHookeMessage(Ex) call and see example note below. This dynamic replacement is in fact a feature of Objective-C, and can be done using method_setImplementation. MSHookMessage() is not thread-safe and has been deprecated in favor of MSHookMessageEx().
MSHookMessage()非纯种安全,已经被deprecated。
MSHookFunction() is like MSHookMessage() but is for C/C++ functions. The replacement must be done at assembly level. Conceptually, MSHookFunction() will write instructions that jumps to the replacement function, and allocate some bytes on a custom memory location, which has the original cut-out instructions and a jump to the rest of the hooked function. Since on iOS by default a memory page cannot be simultaneously writable and executable, a kernel patch must be applied for MSHookFunction() to work.
ios中黑夜一块内存不能同时具有写&执行的权限,需要打一个kernel patch才能使MSHookFunction()起作用。
【MSHook Example Code】
1、Using MSHookFunction:
2、Using MSHookMessageEx:
3、Note that if you are hooking a class method, you have to put a meta-class in the class argument, e.g.
【MobileLoader】
MobileLoader loads 3rd-party patching code into the running application.
MobileLoader will first load itself into the run application using DYLD_INSERT_LIBRARIES environment variable. Then it looks for all dynamic libraries in the directory /Library/MobileSubstrate/DynamicLibraries/, and dlopen them. An extension should use constructor code to perform any works, e.g.
【safe mode】
When a extension crashed the SpringBoard, MobileLoader will catch that and put the device into safe mode. In safe mode all 3rd-party extensions will be disabled.
The following signals will invoke safe mode:
- SIGTRAP
- SIGABRT
- SIGILL
- SIGBUS
- SIGSEGV
- SIGSYS