-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathXCDUndocumentedChecker.m
282 lines (255 loc) · 10.6 KB
/
XCDUndocumentedChecker.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//
// XCDUndocumentedChecker.m
// xcproj
//
// Created by Cédric Luthi on 2011-02-09.
// Copyright 2011 Cédric Luthi. All rights reserved.
//
#import "XCDUndocumentedChecker.h"
#import <dlfcn.h>
#import <objc/message.h>
#import <objc/runtime.h>
extern const char *_protocol_getMethodTypeEncoding(Protocol *p, SEL sel, BOOL isRequiredMethod, BOOL isInstanceMethod);
NSString *const XCDUndocumentedCheckerErrorDomain = @"XCDUndocumentedChecker";
NSString *const XCDUndocumentedCheckerMismatchingHierarchyKey = @"MismatchingHierarchy";
NSString *const XCDUndocumentedCheckerMissingMethodsKey = @"MissingMethods";
NSString *const XCDUndocumentedCheckerMismatchingMethodsKey = @"MismatchingMethods";
NSString *const XCDUndocumentedCheckerClassNameKey = @"ClassName";
NSString *const XCDUndocumentedCheckerClassBundleKey = @"ClassBundle";
NSString *const XCDUndocumentedCheckerMethodNameKey = @"MethodName";
NSString *const XCDUndocumentedCheckerProtocolSignatureKey = @"ProtocolSignature";
NSString *const XCDUndocumentedCheckerClassSignatureKey = @"ClassSignature";
/*
{ className -> { methodSignature -> returnInfo } }
E.g.
{
"PBXBuildPhase" ->
{
"+buildPhase" -> "PBXBuildPhase";
"-buildFiles" -> "NSArray.PBXBuildFile";
}
}
*/
static NSMutableDictionary *classInfo = nil;
static void XCDUndocumentedChecker_forwardInvocation(id self, SEL _cmd, NSInvocation *invocation)
{
NSString *returnClassName = nil;
NSString *collectionElementsClassName = nil;
Class class = object_getClass([invocation target]);
while (!returnClassName && class)
{
NSDictionary *methodInfo = classInfo[NSStringFromClass(class)];
NSString *methodName = [class_isMetaClass(class) ? @"+" : @"-" stringByAppendingString:NSStringFromSelector([invocation selector])];
NSString *returnInfo = methodInfo[methodName];
NSArray *returnComponents = [returnInfo componentsSeparatedByString:@"."];
returnClassName = [returnComponents objectAtIndex:0];
if ([returnComponents count] == 2)
collectionElementsClassName = [returnComponents objectAtIndex:1];
class = class_getSuperclass(class);
}
NSMethodSignature *methodSignature = [invocation methodSignature];
NSUInteger methodReturnLength = [methodSignature methodReturnLength];
@try
{
__unsafe_unretained id result = nil;
SEL selector = NSSelectorFromString([@"XCDUndocumentedChecker_" stringByAppendingString:NSStringFromSelector([invocation selector])]);
BOOL returnsObject = [methodSignature methodReturnType][0] == _C_ID;
[invocation setSelector:selector];
[invocation invoke];
if (returnsObject && methodReturnLength == sizeof(id))
{
[invocation getReturnValue:&result];
if (result && ![returnClassName isEqualToString:@"id"])
{
if (![result isKindOfClass:NSClassFromString(returnClassName)])
{
[invocation setReturnValue:&(id){nil}];
return;
}
if (collectionElementsClassName && [result isKindOfClass:[NSArray class]])
{
Class collectionElementsClass = NSClassFromString(collectionElementsClassName);
for (id item in result)
{
if (![item isKindOfClass:collectionElementsClass])
{
[invocation setReturnValue:&(id){nil}];
return;
}
}
}
}
}
}
@catch (NSException *exception)
{
uint8_t result[methodReturnLength];
bzero(result, sizeof(result));
[invocation setReturnValue:result];
}
}
Class XCDClassFromProtocol(Protocol *protocol, NSError **error)
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classInfo = [NSMutableDictionary new];
});
BOOL hasError = NO;
if (error)
*error = nil;
NSString *className = protocol ? @(protocol_getName(protocol)) : @"nil";
Class class = NSClassFromString(className);
if (!class)
{
if (error)
{
NSDictionary *errorInfo = @{
NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Class %@ not found", className],
XCDUndocumentedCheckerClassNameKey: className
};
*error = [NSError errorWithDomain:XCDUndocumentedCheckerErrorDomain code:XCDUndocumentedCheckerClassNotFound userInfo:errorInfo];
}
return Nil;
}
NSMutableArray *superClasses = [NSMutableArray array];
Class superClass = class;
while ((superClass = [superClass superclass]))
[superClasses addObject:superClass];
NSMutableArray *hierarchyMismatch = [NSMutableArray array];
unsigned int protocolCount = 0;
__unsafe_unretained Protocol **adoptedProtocols = protocol_copyProtocolList(protocol, &protocolCount);
for (unsigned int i = 0; i < protocolCount; i++)
{
Protocol *adoptedProtocol = adoptedProtocols[i];
NSString *superClassName = NSStringFromProtocol(adoptedProtocol);
superClass = NSClassFromString(superClassName);
if (![superClasses containsObject:superClass])
{
hasError = YES;
[hierarchyMismatch addObject:superClassName];
}
}
free(adoptedProtocols);
NSMutableDictionary *methodSignatures = [NSMutableDictionary dictionary];
Method *methods = NULL;
unsigned int methodCount = 0;
for (unsigned methodKind = 0; methodKind <= 1; methodKind++)
{
BOOL isInstanceMethod = (methodKind == 1);
methods = class_copyMethodList(isInstanceMethod ? class : object_getClass(class), &methodCount);
for (unsigned int i = 0; i < methodCount; i++)
{
NSString *methodName = [NSString stringWithFormat:@"%c%s", isInstanceMethod ? '-':'+', sel_getName(method_getName(methods[i]))];
methodSignatures[methodName] = @(method_getTypeEncoding(methods[i]));
}
free(methods);
}
struct objc_method_description *protocolMethods = NULL;
unsigned int protocolMethodCount = 0;
NSMutableArray *methodsNotFound = [NSMutableArray array];
NSMutableArray *methodsMismatch = [NSMutableArray array];
classInfo[className] = [NSMutableDictionary dictionary];
for (unsigned methodKind = 0; methodKind <= 1; methodKind++)
{
BOOL isInstanceMethod = (methodKind == 1);
protocolMethods = protocol_copyMethodDescriptionList(protocol, YES, isInstanceMethod, &protocolMethodCount);
Method (*class_getMethod)(Class cls, SEL name) = isInstanceMethod ? class_getInstanceMethod : class_getClassMethod;
Method forwardInvocation = class_getInstanceMethod([NSObject class], @selector(forwardInvocation:));
BOOL added = class_addMethod(isInstanceMethod ? class : object_getClass(class), @selector(forwardInvocation:), (IMP)XCDUndocumentedChecker_forwardInvocation, method_getTypeEncoding(forwardInvocation));
if (!added && protocolMethodCount > 0)
{
if (error)
{
NSDictionary *errorInfo = @{
NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@ already implements the forwardInvocation: method.", className],
XCDUndocumentedCheckerClassNameKey: className,
XCDUndocumentedCheckerClassBundleKey: [NSBundle bundleForClass:class]
};
*error = [NSError errorWithDomain:XCDUndocumentedCheckerErrorDomain code:XCDUndocumentedCheckerUnsupportedClass userInfo:errorInfo];
}
free(protocolMethods);
return Nil;
}
for (unsigned int i = 0; i < protocolMethodCount; i++)
{
SEL selector = protocolMethods[i].name;
NSString *methodName = [isInstanceMethod ? @"-" : @"+" stringByAppendingFormat:@"%s", sel_getName(selector)];
NSString *methodSignature = methodSignatures[methodName];
NSString *expectedSignature = @(protocolMethods[i].types);
BOOL signatureMatch = [expectedSignature isEqualToString:methodSignature];
if (!signatureMatch)
{
hasError = YES;
NSDictionary *methodError = nil;
if (!methodSignature)
{
methodError = @{
XCDUndocumentedCheckerMethodNameKey: methodName,
XCDUndocumentedCheckerClassNameKey: className,
XCDUndocumentedCheckerClassBundleKey: [NSBundle bundleForClass:class]
};
[methodsNotFound addObject:methodError];
}
else
{
methodError = @{
XCDUndocumentedCheckerProtocolSignatureKey: expectedSignature,
XCDUndocumentedCheckerClassSignatureKey: methodSignature,
XCDUndocumentedCheckerMethodNameKey: methodName,
XCDUndocumentedCheckerClassNameKey: className,
XCDUndocumentedCheckerClassBundleKey: [NSBundle bundleForClass:class]
};
[methodsMismatch addObject:methodError];
}
}
NSString *typeEncoding = @(_protocol_getMethodTypeEncoding(protocol, selector, YES, isInstanceMethod) ?: "");
if ([typeEncoding hasPrefix:@"@\""])
{
// Parses extended type encoding, e.g. `@"NSString"16@0:8`, `@"<PBXProject>"24@0:8@"NSString"16`, `@"NSArray<PBXBuildFile>"16@0:8`
NSString *returnInfo = [typeEncoding componentsSeparatedByString:@"\""][1];
returnInfo = [returnInfo stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
returnInfo = [returnInfo stringByReplacingOccurrencesOfString:@"<" withString:@"."];
classInfo[className][methodName] = returnInfo;
}
methodName = [methodName substringFromIndex:1];
if (typeEncoding.length == 0)
{
fprintf(stderr, "WARNING: No return type information found for %c[%s %s]\n", isInstanceMethod ? '-' : '+', [className UTF8String], [methodName UTF8String]);
}
else
{
NSString *forwardMethodName = [@"XCDUndocumentedChecker_" stringByAppendingString:methodName];
Method method = class_getMethod(class, NSSelectorFromString(methodName));
if ([NSProcessInfo.processInfo.environment[@"DEBUG_METHOD_IMP"] boolValue])
{
Dl_info info;
if (dladdr(method_getImplementation(method), &info))
printf("%s: %c[%s %s]\n", info.dli_fname, isInstanceMethod ? '-' : '+', [className UTF8String], [methodName UTF8String]);
}
BOOL added = class_addMethod(isInstanceMethod ? class : object_getClass(class), NSSelectorFromString(forwardMethodName), _objc_msgForward, method_getTypeEncoding(method));
if (added)
{
Method forwardMethod = class_getMethod(class, NSSelectorFromString(forwardMethodName));
method_exchangeImplementations(method, forwardMethod);
}
}
}
free(protocolMethods);
}
if (error)
{
NSMutableDictionary *errorInfo = [NSMutableDictionary dictionary];
if ([methodsNotFound count] > 0)
errorInfo[XCDUndocumentedCheckerMissingMethodsKey] = methodsNotFound;
if ([methodsMismatch count] > 0)
errorInfo[XCDUndocumentedCheckerMismatchingMethodsKey] = methodsMismatch;
if ([hierarchyMismatch count] > 0)
errorInfo[XCDUndocumentedCheckerMismatchingHierarchyKey] = hierarchyMismatch;
if ([errorInfo count] > 0)
{
errorInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Methods of class %@ do not match %@ protocol", className, NSStringFromProtocol(protocol)];
*error = [NSError errorWithDomain:XCDUndocumentedCheckerErrorDomain code:XCDUndocumentedCheckerMethodMismatch userInfo:errorInfo];
}
}
return hasError ? Nil : class;
}