JSPatch是一個很是棒的熱修復框架,10000+star!!!!!雖然說2017年被蘋果封殺了,可是據我獲取到的有限的信息,你們仍是偷偷摸摸混淆一下、改改類名繼續在使用。畢竟bug仍是不可避免的,有了JSPatch萬一出了問題咱們仍是可以搶救一下的。一些實現細節bang哥其實已經作了一些介紹了,可是看了以後仍是不能對完整的流程有個大體的印象,而且其中確定仍是有不少東西值得咱們去深挖學習的。html
JSPatch 是一個 iOS 動態更新框架,只需在項目中引入極小的引擎,就可使用 JavaScript
調用任何 Objective-C
原生接口,得到腳本語言的優點:爲項目動態添加模塊,或替換項目原生代碼動態修復 bug。git
JavaScript
- 仍是要稍微會一點點js的,我就是那種菜的摳腳的水平,因此js部分看的有點吃力。不懂的地方都是靠調試js代碼打斷點,根據結果反向推來搞懂的。JavaScript
的寫法。仍是那句話,用過以後會有一些問題,帶着問題去讀源碼更有針對性,效果更好。JavaScriptCore
- js和oc內部交互用的是JavaScriptCore
,推薦閱讀JavaScriptCore 總體介紹。Runtime
- JSPatch內部是經過Runtime來動態修改添加方法的,涉及到了不少不少的runtime的知識。因此你仍是須要了解一些runtime的知識。推薦閱讀Objective-C Runtime。國際慣例,拋磚引玉提倆問題。github
class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp,
const char * _Nullable types)
複製代碼
我知道runtime裏添加一個方法裏會須要咱們傳遞一個方法的編碼。蘋果的運行時庫內部利用類型編碼幫助加快消息分發。方法的編碼主要描述了方法的返回值和參數。好比這樣一個方法-(void)test:(id)arg;
最後拿到的編碼是v@:@
,具體各個字符對應關係Type Encodings。可是你可能會有個問題這裏算上返回值一共就倆個參數,可是這裏一共有四個字符。緣由是[receiver test:arg]
會被編譯器轉化成objc_msgSend(receiver, selector, arg1)
咱們拿到的簽名裏的參數部分被加上了一個self
和一個SEL
。objective-c
JS裏的方法顯然是沒有這樣的編碼的,那麼從JS到OC方法的編碼是如何處理的呢。bash
若是某個JS對象不存在某個方法那麼調用是要出錯的。例如
UIView.alloc()
若是UIView
對象沒有alloc
這個方法調用是會出問題的。數據結構
簡化了不少細節,demo裏的代碼的大體的流程以下。用兩種顏色區分了js端和native端。 app
從這個流程圖當中咱們大體能夠了解到,JSPatch最後的方法調用和Aspects
庫相似都是走的消息轉發。並且native方法不存在的時候JSPatch並不會去動態生成一個方法。因此當Aspects
和JSPatch
混用的時候須要特別當心。框架
關於第一個方法編碼的問題,JSPatch分了幾種狀況去處理ide
對應的大體的代碼邏輯,能夠看到若是是添加了一個以前徹底不存在的方法,是須要知道有多少個參數來本身建立一個方法編碼的。因此以前的js裏有一步是要生成一個[方法參數個數,方法實現]
這樣的數據結構。函數
// 若是已經實現了這個方法
if (class_respondsToSelector(currCls, NSSelectorFromString(selectorName))) {
// overrideMethod方法內部經過下面的邏輯來獲取編碼
// Method method = class_getInstanceMethod(cls, selector);
// typeDescription = (char *)method_getTypeEncoding(method);
overrideMethod(currCls, selectorName, jsMethod, !isInstance, NULL);
} else {
// 協議方法
BOOL overrided = NO;
for (NSString *protocolName in protocols) {
char *types = methodTypesInProtocol(protocolName, selectorName, isInstance, YES);
if (!types) types = methodTypesInProtocol(protocolName, selectorName, isInstance, NO);
if (types) {
overrideMethod(currCls, selectorName, jsMethod, !isInstance, types);
free(types);
overrided = YES;
break;
}
}
// 默認的狀況
if (!overrided) {
if (![[jsMethodName substringToIndex:1] isEqualToString:@"_"]) {
NSMutableString *typeDescStr = [@"@@:" mutableCopy];
for (int i = 0; i < numberOfArg; i ++) {
[typeDescStr appendString:@"@"];
}
overrideMethod(currCls, selectorName, jsMethod, !isInstance, [typeDescStr cStringUsingEncoding:NSUTF8StringEncoding]);
}
}
}
複製代碼
關於這個問題bang哥已經有一些介紹,經過正則,相似UIView.alloc().init()
的調用被替換成UIView.__c('alloc')().__c('init')()
形式。走統一的__c()
元函數,傳遞進方法名拿到一個方法,再傳遞進參數調用方法。
JSPatch細節有點多。我這邊只挑一些主要的看,默認你已經大體看過源碼。
從demo的執行入口開始
[JPEngine startEngine];
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];
NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
[JPEngine evaluateScript:script];
複製代碼
startEngine
至關於初始化運行環境,它的內部經過JavaScriptCore
定義了不少JS的方法,給外部的js來和native交互。
+ (void)startEngine
{
.
.
.
context[@"_OC_defineClass"] = ^(NSString *classDeclaration, JSValue *instanceMethods, JSValue *classMethods) {
return defineClass(classDeclaration, instanceMethods, classMethods);
};
context[@"_OC_defineProtocol"] = ^(NSString *protocolDeclaration, JSValue *instProtocol, JSValue *clsProtocol) {
return defineProtocol(protocolDeclaration, instProtocol,clsProtocol);
};
context[@"_OC_callI"] = ^id(JSValue *obj, NSString *selectorName, JSValue *arguments, BOOL isSuper) {
return callSelector(nil, selectorName, arguments, obj, isSuper);
};
context[@"_OC_callC"] = ^id(NSString *className, NSString *selectorName, JSValue *arguments) {
return callSelector(className, selectorName, arguments, nil, NO);
};
context[@"_OC_formatJSToOC"] = ^id(JSValue *obj) {
return formatJSToOC(obj);
};
context[@"_OC_formatOCToJS"] = ^id(JSValue *obj) {
return formatOCToJS([obj toObject]);
};
.
.
.
複製代碼
js能夠直接調用這些方法而且傳遞參數,傳遞的參數在這裏會自動轉換。具體的轉換對應關係。
Objective-C type | JavaScript type
--------------------+---------------------
nil | undefined
NSNull | null
NSString | string
NSNumber | number, boolean
NSDictionary | Object object
NSArray | Array object
NSDate | Date object
NSBlock (1) | Function object (1)
id (2) | Wrapper object (2)
Class (3) | Constructor object (3)
複製代碼
上面是環境的初始化,初始化完就是js腳本的調用。[JPEngine evaluateScript:script];
evaluateScript
方法的主要做用就是把原始的js方法裏方法調用正則修改爲__c
函數調用。也就是上面問題2的描述。
+ (JSValue *)_evaluateScript:(NSString *)script withSourceURL:(NSURL *)resourceURL
{
if (!script || ![JSContext class]) {
_exceptionBlock(@"script is nil");
return nil;
}
[self startEngine];
if (!_regex) {
_regex = [NSRegularExpression regularExpressionWithPattern:_regexStr options:0 error:nil];
}
NSString *formatedScript = [NSString stringWithFormat:@";(function(){try{\n%@\n}catch(e){_OC_catch(e.message, e.stack)}})();", [_regex stringByReplacingMatchesInString:script options:0 range:NSMakeRange(0, script.length) withTemplate:_replaceStr]];
@try {
if ([_context respondsToSelector:@selector(evaluateScript:withSourceURL:)]) {
return [_context evaluateScript:formatedScript withSourceURL:resourceURL];
} else {
return [_context evaluateScript:formatedScript];
}
}
@catch (NSException *exception) {
_exceptionBlock([NSString stringWithFormat:@"%@", exception]);
}
return nil;
}
複製代碼
接下來就是JavaScriptCore
執行js腳本了。
defineClass('JPViewController', {
viewDidAppear:function(animate) {
console.log('lol');
},
handleBtn: function(sender) {
var tableViewCtrl = JPTableViewController.alloc().init()
self.navigationController().pushViewController_animated(tableViewCtrl, YES)
}
})
複製代碼
global.defineClass = function(declaration, properties, instMethods, clsMethods) {
var newInstMethods = {}, newClsMethods = {}
if (!(properties instanceof Array)) {
clsMethods = instMethods
instMethods = properties
properties = null
}
// 若是有屬性的狀況下,須要去判斷有沒有實現set get方法,若是實現了就要加到實例方法列表裏面去
if (properties) {
properties.forEach(function(name){
if (!instMethods[name]) {
instMethods[name] = _propertiesGetFun(name);
}
var nameOfSet = "set"+ name.substr(0,1).toUpperCase() + name.substr(1);
if (!instMethods[nameOfSet]) {
instMethods[nameOfSet] = _propertiesSetFun(name);
}
});
}
// 解析出類名
var realClsName = declaration.split(':')[0].trim()
_formatDefineMethods(instMethods, newInstMethods, realClsName)
_formatDefineMethods(clsMethods, newClsMethods, realClsName)
var ret = _OC_defineClass(declaration, newInstMethods, newClsMethods)
var className = ret['cls']
var superCls = ret['superCls']
_ocCls[className] = {
instMethods: {},
clsMethods: {},
}
if (superCls.length && _ocCls[superCls]) {
for (var funcName in _ocCls[superCls]['instMethods']) {
_ocCls[className]['instMethods'][funcName] = _ocCls[superCls]['instMethods'][funcName]
}
for (var funcName in _ocCls[superCls]['clsMethods']) {
_ocCls[className]['clsMethods'][funcName] = _ocCls[superCls]['clsMethods'][funcName]
}
}
_setupJSMethod(className, instMethods, 1, realClsName)
_setupJSMethod(className, clsMethods, 0, realClsName)
return require(className)
}
複製代碼
咱們看到defineClass
方法內部作了一些解析處理,而且調用了咱們以前註冊的_OC_defineClass
方法,傳遞進去了類名、實例方法、類方法。OC部分的defineClass
方法以下
static NSDictionary *defineClass(NSString *classDeclaration, JSValue *instanceMethods, JSValue *classMethods)
{
NSScanner *scanner = [NSScanner scannerWithString:classDeclaration];
NSString *className;
NSString *superClassName;
NSString *protocolNames;
// xxObject : xxSuperObject <xxProtocol>
// 解析類
[scanner scanUpToString:@":" intoString:&className];
if (!scanner.isAtEnd) {
// 解析父類
scanner.scanLocation = scanner.scanLocation + 1;
[scanner scanUpToString:@"<" intoString:&superClassName];
// 解析協議
if (!scanner.isAtEnd) {
scanner.scanLocation = scanner.scanLocation + 1;
[scanner scanUpToString:@">" intoString:&protocolNames];
}
}
// 沒有父類信息的狀況就繼承自NSObject
if (!superClassName) superClassName = @"NSObject";
// 刪除先後空格
className = trim(className);
superClassName = trim(superClassName);
// 解析出協議
NSArray *protocols = [protocolNames length] ? [protocolNames componentsSeparatedByString:@","] : nil;
Class cls = NSClassFromString(className);
if (!cls) {// 若是當前的類不存在
Class superCls = NSClassFromString(superClassName);
if (!superCls) {// 若是父類不存在直接奔潰
_exceptionBlock([NSString stringWithFormat:@"can't find the super class %@", superClassName]);
return @{@"cls": className};
}
// 建立這個類
cls = objc_allocateClassPair(superCls, className.UTF8String, 0);
objc_registerClassPair(cls);
}
// 給這個類添加協議
if (protocols.count > 0) {
for (NSString* protocolName in protocols) {
Protocol *protocol = objc_getProtocol([trim(protocolName) cStringUsingEncoding:NSUTF8StringEncoding]);
class_addProtocol (cls, protocol);
}
}
// 實例方法和類方法處理 1是實例方法 2是類方法
for (int i = 0; i < 2; i ++) {
BOOL isInstance = i == 0;
// 傳遞過來的方法都是 `方法名` : `[方法參數個數,方法實現]` 這樣的形式
JSValue *jsMethods = isInstance ? instanceMethods: classMethods;
Class currCls = isInstance ? cls: objc_getMetaClass(className.UTF8String);
NSDictionary *methodDict = [jsMethods toDictionary];
for (NSString *jsMethodName in methodDict.allKeys) {
JSValue *jsMethodArr = [jsMethods valueForProperty:jsMethodName];
// 參數的個數
int numberOfArg = [jsMethodArr[0] toInt32];
// JS的方法名字轉換成OC的方法名字
NSString *selectorName = convertJPSelectorString(jsMethodName);
// 爲了js端的寫法好看點,末尾的參數能夠不用寫 `_`
if ([selectorName componentsSeparatedByString:@":"].count - 1 < numberOfArg) {
selectorName = [selectorName stringByAppendingString:@":"];
}
JSValue *jsMethod = jsMethodArr[1];
// 若是已經實現了這個方法
if (class_respondsToSelector(currCls, NSSelectorFromString(selectorName))) {
// overrideMethod方法內部經過下面的邏輯來獲取編碼
// Method method = class_getInstanceMethod(cls, selector);
// typeDescription = (char *)method_getTypeEncoding(method);
overrideMethod(currCls, selectorName, jsMethod, !isInstance, NULL);
} else {
// 協議方法
BOOL overrided = NO;
for (NSString *protocolName in protocols) {
char *types = methodTypesInProtocol(protocolName, selectorName, isInstance, YES);
if (!types) types = methodTypesInProtocol(protocolName, selectorName, isInstance, NO);
if (types) {
overrideMethod(currCls, selectorName, jsMethod, !isInstance, types);
free(types);
overrided = YES;
break;
}
}
// 默認的狀況
if (!overrided) {
if (![[jsMethodName substringToIndex:1] isEqualToString:@"_"]) {
NSMutableString *typeDescStr = [@"@@:" mutableCopy];
for (int i = 0; i < numberOfArg; i ++) {
[typeDescStr appendString:@"@"];
}
overrideMethod(currCls, selectorName, jsMethod, !isInstance, [typeDescStr cStringUsingEncoding:NSUTF8StringEncoding]);
}
}
}
}
}
class_addMethod(cls, @selector(getProp:), (IMP)getPropIMP, "@@:@");
class_addMethod(cls, @selector(setProp:forKey:), (IMP)setPropIMP, "v@:@@");
return @{@"cls": className, @"superCls": superClassName};
}
複製代碼
咱們主要來看一下針對方法部分的操做,能夠看到區分不一樣的狀況拿到方法的編碼以後走的都是overrideMethod
方法。再來看看這個方法的主要邏輯。
static void overrideMethod(Class cls, NSString *selectorName, JSValue *function, BOOL isClassMethod, const char *typeDescription)
{
SEL selector = NSSelectorFromString(selectorName);
// 拿到方法簽名
if (!typeDescription) {
Method method = class_getInstanceMethod(cls, selector);
typeDescription = (char *)method_getTypeEncoding(method);
}
// 拿到原始方法的IMP若是方法實現了的話
IMP originalImp = class_respondsToSelector(cls, selector) ? class_getMethodImplementation(cls, selector) : NULL;
// 拿到消息轉發指針
IMP msgForwardIMP = _objc_msgForward;
#if !defined(__arm64__)
if (typeDescription[0] == '{') {
//In some cases that returns struct, we should use the '_stret' API:
//http://sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html
//NSMethodSignature knows the detail but has no API to return, we can only get the info from debugDescription.
NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:typeDescription];
if ([methodSignature.debugDescription rangeOfString:@"is special struct return? YES"].location != NSNotFound) {
msgForwardIMP = (IMP)_objc_msgForward_stret;
}
}
#endif
// 替換消息轉發 `forwardInvocation:`的實現
if (class_getMethodImplementation(cls, @selector(forwardInvocation:)) != (IMP)JPForwardInvocation) {
IMP originalForwardImp = class_replaceMethod(cls, @selector(forwardInvocation:), (IMP)JPForwardInvocation, "v@:@");
if (originalForwardImp) {
class_addMethod(cls, @selector(ORIGforwardInvocation:), originalForwardImp, "v@:@");// 存一下原始的IMP
}
}
// invocation return 0 when the return type is double/float.
[cls jp_fixMethodSignature];
// 若是實現了這個方法,作一下區分生成一個新的 ORIGSelector -> 原始方法的IMP。 爲了JS能調用到以前的方法
if (class_respondsToSelector(cls, selector)) {
NSString *originalSelectorName = [NSString stringWithFormat:@"ORIG%@", selectorName];
SEL originalSelector = NSSelectorFromString(originalSelectorName);
if(!class_respondsToSelector(cls, originalSelector)) {
class_addMethod(cls, originalSelector, originalImp, typeDescription);
}
}
NSString *JPSelectorName = [NSString stringWithFormat:@"_JP%@", selectorName];
_initJPOverideMethods(cls);
_JSOverideMethods[cls][JPSelectorName] = function;
// Replace the original selector at last, preventing threading issus when
// the selector get called during the execution of `overrideMethod`
// 調用方法的時候直接走消息轉發
class_replaceMethod(cls, selector, msgForwardIMP, typeDescription);
}
複製代碼
這個方法和Aspects
裏的核心方法很像。主要的操做就是替換forwardInvocation
的實現,替換要調用的方法的SEL指向_objc_msgForward
。也就是方法調用的時候直接走消息轉發,執行JPForwardInvocation
方法。而且也把傳遞過來的JS方法存了一下,以便在JPForwardInvocation
方法裏調用。JPForwardInvocation
的方法實在是有點長,它主要的流程以下圖
代碼以下,有刪除一些內容。
static void JPForwardInvocation(__unsafe_unretained id assignSlf, SEL selector, NSInvocation *invocation)
{
// 調用棧
#ifdef DEBUG
_JSLastCallStack = [NSThread callStackSymbols];
#endif
BOOL deallocFlag = NO;
id slf = assignSlf;
// 方法簽名
NSMethodSignature *methodSignature = [invocation methodSignature];
// 方法參數
NSInteger numberOfArguments = [methodSignature numberOfArguments];
// 方法名字
NSString *selectorName = NSStringFromSelector(invocation.selector);
// JS方法名字
NSString *JPSelectorName = [NSString stringWithFormat:@"_JP%@", selectorName];
// 拿到js的function
JSValue *jsFunc = getJSFunctionInObjectHierachy(slf, JPSelectorName);
if (!jsFunc) {
// 若是沒有實現JS的方法就調用原始的消息轉發
JPExecuteORIGForwardInvocation(slf, selector, invocation);
return;
}
// JPBoxing的做用是防止強制轉換
NSMutableArray *argList = [[NSMutableArray alloc] init];
if ([slf class] == slf) {
// 類方法
[argList addObject:[JSValue valueWithObject:@{@"__clsName": NSStringFromClass([slf class])} inContext:_context]];
} else if ([selectorName isEqualToString:@"dealloc"]) {
// dealloc方法添加一個assign的self對象
[argList addObject:[JPBoxing boxAssignObj:slf]];
deallocFlag = YES;
} else {
// 默認的狀況添加一個weak的self對象
[argList addObject:[JPBoxing boxWeakObj:slf]];
}
// 方法簽名的 0是self 1是_cmd
// 遍歷獲取方法的參數,
for (NSUInteger i = 2; i < numberOfArguments; i++) {
const char *argumentType = [methodSignature getArgumentTypeAtIndex:i];
switch(argumentType[0] == 'r' ? argumentType[1] : argumentType[0]) {
// 基礎數據類型
#define JP_FWD_ARG_CASE(_typeChar, _type) \
case _typeChar: { \
_type arg; \
[invocation getArgument:&arg atIndex:i]; \
[argList addObject:@(arg)]; \
break; \
}
JP_FWD_ARG_CASE('c', char)
JP_FWD_ARG_CASE('C', unsigned char)
JP_FWD_ARG_CASE('s', short)
JP_FWD_ARG_CASE('S', unsigned short)
JP_FWD_ARG_CASE('i', int)
JP_FWD_ARG_CASE('I', unsigned int)
JP_FWD_ARG_CASE('l', long)
JP_FWD_ARG_CASE('L', unsigned long)
JP_FWD_ARG_CASE('q', long long)
JP_FWD_ARG_CASE('Q', unsigned long long)
JP_FWD_ARG_CASE('f', float)
JP_FWD_ARG_CASE('d', double)
JP_FWD_ARG_CASE('B', BOOL)
// 對象
case '@': {
__unsafe_unretained id arg;
[invocation getArgument:&arg atIndex:i];
if ([arg isKindOfClass:NSClassFromString(@"NSBlock")]) {
[argList addObject:(arg ? [arg copy]: _nilObj)];
} else {
[argList addObject:(arg ? arg: _nilObj)];
}
break;
}
// struct
case '{': {
NSString *typeString = extractStructName([NSString stringWithUTF8String:argumentType]);
#define JP_FWD_ARG_STRUCT(_type, _transFunc) \
if ([typeString rangeOfString:@#_type].location != NSNotFound) { \
_type arg; \
[invocation getArgument:&arg atIndex:i]; \
[argList addObject:[JSValue _transFunc:arg inContext:_context]]; \
break; \
}
JP_FWD_ARG_STRUCT(CGRect, valueWithRect)
JP_FWD_ARG_STRUCT(CGPoint, valueWithPoint)
JP_FWD_ARG_STRUCT(CGSize, valueWithSize)
JP_FWD_ARG_STRUCT(NSRange, valueWithRange)
@synchronized (_context) {
NSDictionary *structDefine = _registeredStruct[typeString];
if (structDefine) {
size_t size = sizeOfStructTypes(structDefine[@"types"]);
if (size) {
void *ret = malloc(size);
[invocation getArgument:ret atIndex:i];
NSDictionary *dict = getDictOfStruct(ret, structDefine);
[argList addObject:[JSValue valueWithObject:dict inContext:_context]];
free(ret);
break;
}
}
}
break;
}
case ':': {
SEL selector;
[invocation getArgument:&selector atIndex:i];
NSString *selectorName = NSStringFromSelector(selector);
[argList addObject:(selectorName ? selectorName: _nilObj)];
break;
}
// 指針
case '^':
case '*': {
void *arg;
[invocation getArgument:&arg atIndex:i];
[argList addObject:[JPBoxing boxPointer:arg]];
break;
}
// 類
case '#': {
Class arg;
[invocation getArgument:&arg atIndex:i];
[argList addObject:[JPBoxing boxClass:arg]];
break;
}
default: {
NSLog(@"error type %s", argumentType);
break;
}
}
}
// 調用父類方法
if (_currInvokeSuperClsName[selectorName]) {
Class cls = NSClassFromString(_currInvokeSuperClsName[selectorName]);
NSString *tmpSelectorName = [[selectorName stringByReplacingOccurrencesOfString:@"_JPSUPER_" withString:@"_JP"] stringByReplacingOccurrencesOfString:@"SUPER_" withString:@"_JP"];
if (!_JSOverideMethods[cls][tmpSelectorName]) {
NSString *ORIGSelectorName = [selectorName stringByReplacingOccurrencesOfString:@"SUPER_" withString:@"ORIG"];
[argList removeObjectAtIndex:0];
id retObj = callSelector(_currInvokeSuperClsName[selectorName], ORIGSelectorName, [JSValue valueWithObject:argList inContext:_context], [JSValue valueWithObject:@{@"__obj": slf, @"__realClsName": @""} inContext:_context], NO);
id __autoreleasing ret = formatJSToOC([JSValue valueWithObject:retObj inContext:_context]);
[invocation setReturnValue:&ret];
return;
}
}
// 把oc的參數轉成js的參數
NSArray *params = _formatOCToJSList(argList);
// 返回數據的encode
char returnType[255];
strcpy(returnType, [methodSignature methodReturnType]);
// 處理7.1系統下返回double float 0的問題
// Restore the return type
if (strcmp(returnType, @encode(JPDouble)) == 0) {
strcpy(returnType, @encode(double));
}
if (strcmp(returnType, @encode(JPFloat)) == 0) {
strcpy(returnType, @encode(float));
}
// 拿到jsFunc 直接調用 `[jsFunc callWithArguments:params]` 而後根據returnType轉成對應的OC數據
switch (returnType[0] == 'r' ? returnType[1] : returnType[0]) {
#define JP_FWD_RET_CALL_JS \
JSValue *jsval; \
[_JSMethodForwardCallLock lock]; \
jsval = [jsFunc callWithArguments:params]; \
[_JSMethodForwardCallLock unlock]; \
while (![jsval isNull] && ![jsval isUndefined] && [jsval hasProperty:@"__isPerformInOC"]) { \
NSArray *args = nil; \
JSValue *cb = jsval[@"cb"]; \
if ([jsval hasProperty:@"sel"]) { \
id callRet = callSelector(![jsval[@"clsName"] isUndefined] ? [jsval[@"clsName"] toString] : nil, [jsval[@"sel"] toString], jsval[@"args"], ![jsval[@"obj"] isUndefined] ? jsval[@"obj"] : nil, NO); \
args = @[[_context[@"_formatOCToJS"] callWithArguments:callRet ? @[callRet] : _formatOCToJSList(@[_nilObj])]]; \
} \
[_JSMethodForwardCallLock lock]; \
jsval = [cb callWithArguments:args]; \
[_JSMethodForwardCallLock unlock]; \
}
#define JP_FWD_RET_CASE_RET(_typeChar, _type, _retCode) \
case _typeChar : { \
JP_FWD_RET_CALL_JS \
_retCode \
[invocation setReturnValue:&ret];\
break; \
}
#define JP_FWD_RET_CASE(_typeChar, _type, _typeSelector) \
JP_FWD_RET_CASE_RET(_typeChar, _type, _type ret = [[jsval toObject] _typeSelector];) \
#define JP_FWD_RET_CODE_ID \
id __autoreleasing ret = formatJSToOC(jsval); \
if (ret == _nilObj || \
([ret isKindOfClass:[NSNumber class]] && strcmp([ret objCType], "c") == 0 && ![ret boolValue])) ret = nil; \
#define JP_FWD_RET_CODE_POINTER \
void *ret; \
id obj = formatJSToOC(jsval); \
if ([obj isKindOfClass:[JPBoxing class]]) { \
ret = [((JPBoxing *)obj) unboxPointer]; \
}
#define JP_FWD_RET_CODE_CLASS \
Class ret; \
ret = formatJSToOC(jsval);
#define JP_FWD_RET_CODE_SEL \
SEL ret; \
id obj = formatJSToOC(jsval); \
if ([obj isKindOfClass:[NSString class]]) { \
ret = NSSelectorFromString(obj); \
}
JP_FWD_RET_CASE_RET('@', id, JP_FWD_RET_CODE_ID)
JP_FWD_RET_CASE_RET('^', void*, JP_FWD_RET_CODE_POINTER)
JP_FWD_RET_CASE_RET('*', void*, JP_FWD_RET_CODE_POINTER)
JP_FWD_RET_CASE_RET('#', Class, JP_FWD_RET_CODE_CLASS)
JP_FWD_RET_CASE_RET(':', SEL, JP_FWD_RET_CODE_SEL)
JP_FWD_RET_CASE('c', char, charValue)
JP_FWD_RET_CASE('C', unsigned char, unsignedCharValue)
JP_FWD_RET_CASE('s', short, shortValue)
JP_FWD_RET_CASE('S', unsigned short, unsignedShortValue)
JP_FWD_RET_CASE('i', int, intValue)
JP_FWD_RET_CASE('I', unsigned int, unsignedIntValue)
JP_FWD_RET_CASE('l', long, longValue)
JP_FWD_RET_CASE('L', unsigned long, unsignedLongValue)
JP_FWD_RET_CASE('q', long long, longLongValue)
JP_FWD_RET_CASE('Q', unsigned long long, unsignedLongLongValue)
JP_FWD_RET_CASE('f', float, floatValue)
JP_FWD_RET_CASE('d', double, doubleValue)
JP_FWD_RET_CASE('B', BOOL, boolValue)
case 'v': {
JP_FWD_RET_CALL_JS
break;
}
case '{': {
NSString *typeString = extractStructName([NSString stringWithUTF8String:returnType]);
#define JP_FWD_RET_STRUCT(_type, _funcSuffix) \
if ([typeString rangeOfString:@#_type].location != NSNotFound) { \
JP_FWD_RET_CALL_JS \
_type ret = [jsval _funcSuffix]; \
[invocation setReturnValue:&ret];\
break; \
}
JP_FWD_RET_STRUCT(CGRect, toRect)
JP_FWD_RET_STRUCT(CGPoint, toPoint)
JP_FWD_RET_STRUCT(CGSize, toSize)
JP_FWD_RET_STRUCT(NSRange, toRange)
@synchronized (_context) {
NSDictionary *structDefine = _registeredStruct[typeString];
if (structDefine) {
size_t size = sizeOfStructTypes(structDefine[@"types"]);
JP_FWD_RET_CALL_JS
void *ret = malloc(size);
NSDictionary *dict = formatJSToOC(jsval);
getStructDataWithDict(ret, dict, structDefine);
[invocation setReturnValue:ret];
free(ret);
}
}
break;
}
default: {
break;
}
}
...
}
複製代碼
上面的流程主要是定義一個js的方法而後進行的一些操做。
下面再來看一下js方法內部是如何調用原生的方法的。JS部分的代碼就不貼全了,主要的操做邏輯是給JS 對象基類對象加加上__c
成員,這樣全部對象均可以調用到__c
, __c
內部還有一些判斷是不是對象、是否調用的是父類的方法等等的操做,最後調用的是_methodFunc方法。
var _methodFunc = function(instance, clsName, methodName, args, isSuper, isPerformSelector) {
var selectorName = methodName
if (!isPerformSelector) {
methodName = methodName.replace(/__/g, "-")
selectorName = methodName.replace(/_/g, ":").replace(/-/g, "_")
var marchArr = selectorName.match(/:/g)
var numOfArgs = marchArr ? marchArr.length : 0
if (args.length > numOfArgs) {
selectorName += ":"
}
}
var ret = instance ? _OC_callI(instance, selectorName, args, isSuper):
_OC_callC(clsName, selectorName, args)
return _formatOCToJS(ret)
}
複製代碼
而後咱們看到,方法內部作了一些判斷和解析。最後對象方法調用的是在native裏註冊了的_OC_callI
類方法調用的是在native裏註冊了的_OC_callC
方法。這兩個方法都走的是callSelector
方法。這個方法也是老長。它的主要流程圖以下。
代碼以下
static id callSelector(NSString *className, NSString *selectorName, JSValue *arguments, JSValue *instance, BOOL isSuper)
{
NSString *realClsName = [[instance valueForProperty:@"__realClsName"] toString];
if (instance) {
// JSValue -> OC對象
instance = formatJSToOC(instance);
if (class_isMetaClass(object_getClass(instance))) {// 是不是類對象
className = NSStringFromClass((Class)instance);
instance = nil;
} else if (!instance || instance == _nilObj || [instance isKindOfClass:[JPBoxing class]]) { // 空對象
return @{@"__isNil": @(YES)};
}
}
// 參數
id argumentsObj = formatJSToOC(arguments);
if (instance && [selectorName isEqualToString:@"toJS"]) {
if ([instance isKindOfClass:[NSString class]] || [instance isKindOfClass:[NSDictionary class]] || [instance isKindOfClass:[NSArray class]] || [instance isKindOfClass:[NSDate class]]) {
return _unboxOCObjectToJS(instance);
}
}
// 類
Class cls = instance ? [instance class] : NSClassFromString(className);
SEL selector = NSSelectorFromString(selectorName);
// 父類
NSString *superClassName = nil;
if (isSuper) {
NSString *superSelectorName = [NSString stringWithFormat:@"SUPER_%@", selectorName];
SEL superSelector = NSSelectorFromString(superSelectorName);
Class superCls;
if (realClsName.length) {
Class defineClass = NSClassFromString(realClsName);
superCls = defineClass ? [defineClass superclass] : [cls superclass];
} else {
superCls = [cls superclass];
}
Method superMethod = class_getInstanceMethod(superCls, selector);
IMP superIMP = method_getImplementation(superMethod);
class_addMethod(cls, superSelector, superIMP, method_getTypeEncoding(superMethod));
NSString *JPSelectorName = [NSString stringWithFormat:@"_JP%@", selectorName];
JSValue *overideFunction = _JSOverideMethods[superCls][JPSelectorName];
if (overideFunction) {
overrideMethod(cls, superSelectorName, overideFunction, NO, NULL);
}
selector = superSelector;
superClassName = NSStringFromClass(superCls);
}
NSMutableArray *_markArray;
// 方法編碼
NSInvocation *invocation;
NSMethodSignature *methodSignature;
if (!_JSMethodSignatureCache) {
_JSMethodSignatureCache = [[NSMutableDictionary alloc]init];
}
if (instance) {
[_JSMethodSignatureLock lock];
if (!_JSMethodSignatureCache[cls]) {
_JSMethodSignatureCache[(id<NSCopying>)cls] = [[NSMutableDictionary alloc]init];
}
methodSignature = _JSMethodSignatureCache[cls][selectorName];
if (!methodSignature) {
methodSignature = [cls instanceMethodSignatureForSelector:selector];
methodSignature = fixSignature(methodSignature);
_JSMethodSignatureCache[cls][selectorName] = methodSignature;
}
[_JSMethodSignatureLock unlock];
if (!methodSignature) {
_exceptionBlock([NSString stringWithFormat:@"unrecognized selector %@ for instance %@", selectorName, instance]);
return nil;
}
invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:instance];
} else {
methodSignature = [cls methodSignatureForSelector:selector];
methodSignature = fixSignature(methodSignature);
if (!methodSignature) {
_exceptionBlock([NSString stringWithFormat:@"unrecognized selector %@ for class %@", selectorName, className]);
return nil;
}
invocation= [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:cls];
}
[invocation setSelector:selector];
NSUInteger numberOfArguments = methodSignature.numberOfArguments;
NSInteger inputArguments = [(NSArray *)argumentsObj count];
if (inputArguments > numberOfArguments - 2) {
// calling variable argument method, only support parameter type `id` and return type `id`
id sender = instance != nil ? instance : cls;
id result = invokeVariableParameterMethod(argumentsObj, methodSignature, sender, selector);
return formatOCToJS(result);
}
// 設置方法參數
for (NSUInteger i = 2; i < numberOfArguments; i++) {
const char *argumentType = [methodSignature getArgumentTypeAtIndex:i];
id valObj = argumentsObj[i-2];
switch (argumentType[0] == 'r' ? argumentType[1] : argumentType[0]) {
#define JP_CALL_ARG_CASE(_typeString, _type, _selector) \
case _typeString: { \
_type value = [valObj _selector]; \
[invocation setArgument:&value atIndex:i];\
break; \
}
JP_CALL_ARG_CASE('c', char, charValue)
JP_CALL_ARG_CASE('C', unsigned char, unsignedCharValue)
JP_CALL_ARG_CASE('s', short, shortValue)
JP_CALL_ARG_CASE('S', unsigned short, unsignedShortValue)
JP_CALL_ARG_CASE('i', int, intValue)
JP_CALL_ARG_CASE('I', unsigned int, unsignedIntValue)
JP_CALL_ARG_CASE('l', long, longValue)
JP_CALL_ARG_CASE('L', unsigned long, unsignedLongValue)
JP_CALL_ARG_CASE('q', long long, longLongValue)
JP_CALL_ARG_CASE('Q', unsigned long long, unsignedLongLongValue)
JP_CALL_ARG_CASE('f', float, floatValue)
JP_CALL_ARG_CASE('d', double, doubleValue)
JP_CALL_ARG_CASE('B', BOOL, boolValue)
case ':': {
SEL value = nil;
if (valObj != _nilObj) {
value = NSSelectorFromString(valObj);
}
[invocation setArgument:&value atIndex:i];
break;
}
case '{': {
NSString *typeString = extractStructName([NSString stringWithUTF8String:argumentType]);
JSValue *val = arguments[i-2];
#define JP_CALL_ARG_STRUCT(_type, _methodName) \
if ([typeString rangeOfString:@#_type].location != NSNotFound) { \
_type value = [val _methodName]; \
[invocation setArgument:&value atIndex:i]; \
break; \
}
JP_CALL_ARG_STRUCT(CGRect, toRect)
JP_CALL_ARG_STRUCT(CGPoint, toPoint)
JP_CALL_ARG_STRUCT(CGSize, toSize)
JP_CALL_ARG_STRUCT(NSRange, toRange)
@synchronized (_context) {
NSDictionary *structDefine = _registeredStruct[typeString];
if (structDefine) {
size_t size = sizeOfStructTypes(structDefine[@"types"]);
void *ret = malloc(size);
getStructDataWithDict(ret, valObj, structDefine);
[invocation setArgument:ret atIndex:i];
free(ret);
break;
}
}
break;
}
case '*':
case '^': {
if ([valObj isKindOfClass:[JPBoxing class]]) {
void *value = [((JPBoxing *)valObj) unboxPointer];
if (argumentType[1] == '@') {
if (!_TMPMemoryPool) {
_TMPMemoryPool = [[NSMutableDictionary alloc] init];
}
if (!_markArray) {
_markArray = [[NSMutableArray alloc] init];
}
memset(value, 0, sizeof(id));
[_markArray addObject:valObj];
}
[invocation setArgument:&value atIndex:i];
break;
}
}
case '#': {
if ([valObj isKindOfClass:[JPBoxing class]]) {
Class value = [((JPBoxing *)valObj) unboxClass];
[invocation setArgument:&value atIndex:i];
break;
}
}
default: {
if (valObj == _nullObj) {
valObj = [NSNull null];
[invocation setArgument:&valObj atIndex:i];
break;
}
if (valObj == _nilObj ||
([valObj isKindOfClass:[NSNumber class]] && strcmp([valObj objCType], "c") == 0 && ![valObj boolValue])) {
valObj = nil;
[invocation setArgument:&valObj atIndex:i];
break;
}
if ([(JSValue *)arguments[i-2] hasProperty:@"__isBlock"]) {
JSValue *blkJSVal = arguments[i-2];
Class JPBlockClass = NSClassFromString(@"JPBlock");
if (JPBlockClass && ![blkJSVal[@"blockObj"] isUndefined]) {
__autoreleasing id cb = [JPBlockClass performSelector:@selector(blockWithBlockObj:) withObject:[blkJSVal[@"blockObj"] toObject]];
[invocation setArgument:&cb atIndex:i];
Block_release((__bridge void *)cb);
} else {
__autoreleasing id cb = genCallbackBlock(arguments[i-2]);
[invocation setArgument:&cb atIndex:i];
}
} else {
[invocation setArgument:&valObj atIndex:i];
}
}
}
}
if (superClassName) _currInvokeSuperClsName[selectorName] = superClassName;
[invocation invoke];
if (superClassName) [_currInvokeSuperClsName removeObjectForKey:selectorName];
if ([_markArray count] > 0) {
for (JPBoxing *box in _markArray) {
void *pointer = [box unboxPointer];
id obj = *((__unsafe_unretained id *)pointer);
if (obj) {
@synchronized(_TMPMemoryPool) {
[_TMPMemoryPool setObject:obj forKey:[NSNumber numberWithInteger:[(NSObject*)obj hash]]];
}
}
}
}
char returnType[255];
strcpy(returnType, [methodSignature methodReturnType]);
// Restore the return type
if (strcmp(returnType, @encode(JPDouble)) == 0) {
strcpy(returnType, @encode(double));
}
if (strcmp(returnType, @encode(JPFloat)) == 0) {
strcpy(returnType, @encode(float));
}
// 方法返回值處理
id returnValue;
if (strncmp(returnType, "v", 1) != 0) {
if (strncmp(returnType, "@", 1) == 0) {
void *result;
[invocation getReturnValue:&result];
//For performance, ignore the other methods prefix with alloc/new/copy/mutableCopy
if ([selectorName isEqualToString:@"alloc"] || [selectorName isEqualToString:@"new"] ||
[selectorName isEqualToString:@"copy"] || [selectorName isEqualToString:@"mutableCopy"]) {
returnValue = (__bridge_transfer id)result;
} else {
returnValue = (__bridge id)result;
}
return formatOCToJS(returnValue);
} else {
switch (returnType[0] == 'r' ? returnType[1] : returnType[0]) {
#define JP_CALL_RET_CASE(_typeString, _type) \
case _typeString: { \
_type tempResultSet; \
[invocation getReturnValue:&tempResultSet];\
returnValue = @(tempResultSet); \
break; \
}
JP_CALL_RET_CASE('c', char)
JP_CALL_RET_CASE('C', unsigned char)
JP_CALL_RET_CASE('s', short)
JP_CALL_RET_CASE('S', unsigned short)
JP_CALL_RET_CASE('i', int)
JP_CALL_RET_CASE('I', unsigned int)
JP_CALL_RET_CASE('l', long)
JP_CALL_RET_CASE('L', unsigned long)
JP_CALL_RET_CASE('q', long long)
JP_CALL_RET_CASE('Q', unsigned long long)
JP_CALL_RET_CASE('f', float)
JP_CALL_RET_CASE('d', double)
JP_CALL_RET_CASE('B', BOOL)
case '{': {
NSString *typeString = extractStructName([NSString stringWithUTF8String:returnType]);
#define JP_CALL_RET_STRUCT(_type, _methodName) \
if ([typeString rangeOfString:@#_type].location != NSNotFound) { \
_type result; \
[invocation getReturnValue:&result]; \
return [JSValue _methodName:result inContext:_context]; \
}
JP_CALL_RET_STRUCT(CGRect, valueWithRect)
JP_CALL_RET_STRUCT(CGPoint, valueWithPoint)
JP_CALL_RET_STRUCT(CGSize, valueWithSize)
JP_CALL_RET_STRUCT(NSRange, valueWithRange)
@synchronized (_context) {
NSDictionary *structDefine = _registeredStruct[typeString];
if (structDefine) {
size_t size = sizeOfStructTypes(structDefine[@"types"]);
void *ret = malloc(size);
[invocation getReturnValue:ret];
NSDictionary *dict = getDictOfStruct(ret, structDefine);
free(ret);
return dict;
}
}
break;
}
case '*':
case '^': {
void *result;
[invocation getReturnValue:&result];
returnValue = formatOCToJS([JPBoxing boxPointer:result]);
if (strncmp(returnType, "^{CG", 4) == 0) {
if (!_pointersToRelease) {
_pointersToRelease = [[NSMutableArray alloc] init];
}
[_pointersToRelease addObject:[NSValue valueWithPointer:result]];
CFRetain(result);
}
break;
}
case '#': {
Class result;
[invocation getReturnValue:&result];
returnValue = formatOCToJS([JPBoxing boxClass:result]);
break;
}
}
return returnValue;
}
}
return nil;
}
複製代碼
ok,到這裏一些基本的流程就已經走完了。你能夠大體感覺到,其中有很大的一部分代碼是在作類型轉換的工做。這轉換的過程當中還有不少的細節,好比可變對象的處理等等這裏沒有具體展開來說。有興趣能夠研究研究。
JavaScriptCore
。NSInvocation
。看完JSPatch
的源碼,加上最近一直在玩JSBox。有些想要本身實現一個簡單的JSBox的衝動,定個小目標,準備最近好好看看JS,而後嘗試嘗試。
水文一篇,但願能幫到你們一點點。