TBRuntime.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. //
  2. // TBRuntime.m
  3. // TBTweakViewController
  4. //
  5. // Created by Tanner on 3/22/17.
  6. // Copyright © 2017 Tanner Bennett. All rights reserved.
  7. //
  8. #import "TBRuntime.h"
  9. #import "NSObject+Reflection.h"
  10. #import "FLEXMethod.h"
  11. #import "NSArray+Functional.h"
  12. //#import "MKRuntimeSafety.h"
  13. #define TBEquals(a, b) ([a compare:b options:NSCaseInsensitiveSearch] == NSOrderedSame)
  14. #define TBContains(a, b) ([a rangeOfString:b options:NSCaseInsensitiveSearch].location != NSNotFound)
  15. #define TBHasPrefix(a, b) ([a rangeOfString:b options:NSCaseInsensitiveSearch].location == 0)
  16. #define TBHasSuffix(a, b) ([a rangeOfString:b options:NSCaseInsensitiveSearch].location == (a.length - b.length))
  17. @interface TBRuntime () {
  18. NSMutableArray<NSString*> *_imageDisplayNames;
  19. }
  20. @property (nonatomic) NSMutableDictionary *bundles_pathToShort;
  21. @property (nonatomic) NSCache *bundles_pathToClassNames;
  22. @property (nonatomic) NSMutableArray<NSString*> *imagePaths;
  23. @end
  24. /// @return success if the map passes.
  25. static inline NSString * TBWildcardMap_(NSString *token, NSString *candidate, NSString *success, TBWildcardOptions options) {
  26. switch (options) {
  27. case TBWildcardOptionsNone:
  28. // Only "if equals"
  29. if (TBEquals(candidate, token)) {
  30. return success;
  31. }
  32. default: {
  33. // Only "if contains"
  34. if (options & TBWildcardOptionsPrefix &&
  35. options & TBWildcardOptionsSuffix) {
  36. if (TBContains(candidate, token)) {
  37. return success;
  38. }
  39. }
  40. // Only "if candidate ends with with token"
  41. else if (options & TBWildcardOptionsPrefix) {
  42. if (TBHasSuffix(candidate, token)) {
  43. return success;
  44. }
  45. }
  46. // Only "if candidate starts with with token"
  47. else if (options & TBWildcardOptionsSuffix) {
  48. // Case like "Bundle." where we want "" to match anything
  49. if (!token.length) {
  50. return success;
  51. }
  52. if (TBHasPrefix(candidate, token)) {
  53. return success;
  54. }
  55. }
  56. }
  57. }
  58. return nil;
  59. }
  60. /// @return candidate if the map passes.
  61. static inline NSString * TBWildcardMap(NSString *token, NSString *candidate, TBWildcardOptions options) {
  62. return TBWildcardMap_(token, candidate, candidate, options);
  63. }
  64. @implementation TBRuntime
  65. #pragma mark - Initialization
  66. + (instancetype)runtime {
  67. static TBRuntime *runtime;
  68. static dispatch_once_t onceToken;
  69. dispatch_once(&onceToken, ^{
  70. runtime = [self new];
  71. [runtime reloadLibrariesList];
  72. });
  73. return runtime;
  74. }
  75. - (id)init {
  76. self = [super init];
  77. if (self) {
  78. _imagePaths = [NSMutableArray array];
  79. _bundles_pathToShort = [NSMutableDictionary dictionary];
  80. _bundles_pathToClassNames = [NSCache new];
  81. }
  82. return self;
  83. }
  84. #pragma mark - Private
  85. - (void)reloadLibrariesList {
  86. unsigned int imageCount = 0;
  87. const char **imageNames = objc_copyImageNames(&imageCount);
  88. if (imageNames) {
  89. NSMutableArray *imageNameStrings = [NSMutableArray flex_forEachUpTo:imageCount map:^NSString *(NSUInteger i) {
  90. return @(imageNames[i]);
  91. }];
  92. self.imagePaths = imageNameStrings;
  93. free(imageNames);
  94. // Sort alphabetically
  95. [imageNameStrings sortUsingComparator:^NSComparisonResult(NSString *name1, NSString *name2) {
  96. NSString *shortName1 = [self shortNameForImageName:name1];
  97. NSString *shortName2 = [self shortNameForImageName:name2];
  98. return [shortName1 caseInsensitiveCompare:shortName2];
  99. }];
  100. // Cache image display names
  101. _imageDisplayNames = [imageNameStrings flex_mapped:^id(NSString *path, NSUInteger idx) {
  102. return [self shortNameForImageName:path];
  103. }];
  104. }
  105. }
  106. - (NSString *)shortNameForImageName:(NSString *)imageName {
  107. // Cache
  108. NSString *shortName = _bundles_pathToShort[imageName];
  109. if (shortName) {
  110. return shortName;
  111. }
  112. NSArray *components = [imageName componentsSeparatedByString:@"/"];
  113. if (components.count >= 2) {
  114. NSString *parentDir = components[components.count - 2];
  115. if ([parentDir hasSuffix:@".framework"] || [parentDir hasSuffix:@".axbundle"]) {
  116. shortName = parentDir;
  117. }
  118. }
  119. if (!shortName) {
  120. shortName = imageName.lastPathComponent;
  121. }
  122. _bundles_pathToShort[imageName] = shortName;
  123. return shortName;
  124. }
  125. - (NSMutableArray<NSString*> *)classNamesInImageAtPath:(NSString *)path {
  126. // Check cache
  127. NSMutableArray *classNameStrings = [_bundles_pathToClassNames objectForKey:path];
  128. if (classNameStrings) {
  129. return classNameStrings.mutableCopy;
  130. }
  131. unsigned int classCount = 0;
  132. const char **classNames = objc_copyClassNamesForImage(path.UTF8String, &classCount);
  133. if (classNames) {
  134. classNameStrings = [NSMutableArray flex_forEachUpTo:classCount map:^id(NSUInteger i) {
  135. return @(classNames[i]);
  136. }];
  137. free(classNames);
  138. [classNameStrings sortUsingSelector:@selector(caseInsensitiveCompare:)];
  139. [_bundles_pathToClassNames setObject:classNameStrings forKey:path];
  140. return classNameStrings.mutableCopy;
  141. }
  142. return [NSMutableArray array];
  143. }
  144. #pragma mark - Public
  145. - (NSMutableArray<NSString*> *)bundleNamesForToken:(TBToken *)token {
  146. if (self.imagePaths.count) {
  147. TBWildcardOptions options = token.options;
  148. NSString *query = token.string;
  149. // Optimization, avoid a loop
  150. if (options == TBWildcardOptionsAny) {
  151. return _imageDisplayNames;
  152. }
  153. // No dot syntax because imageDisplayNames is only mutable internally
  154. return [_imageDisplayNames flex_mapped:^id(NSString *binary, NSUInteger idx) {
  155. NSString *UIName = [self shortNameForImageName:binary];
  156. return TBWildcardMap(query, UIName, options);
  157. }];
  158. }
  159. return [NSMutableArray array];
  160. }
  161. - (NSMutableArray<NSString*> *)bundlePathsForToken:(TBToken *)token {
  162. if (self.imagePaths.count) {
  163. TBWildcardOptions options = token.options;
  164. NSString *query = token.string;
  165. // Optimization, avoid a loop
  166. if (options == TBWildcardOptionsAny) {
  167. return self.imagePaths;
  168. }
  169. return [self.imagePaths flex_mapped:^id(NSString *binary, NSUInteger idx) {
  170. NSString *UIName = [self shortNameForImageName:binary];
  171. // If query == UIName, -> binary
  172. return TBWildcardMap_(query, UIName, binary, options);
  173. }];
  174. }
  175. return [NSMutableArray array];
  176. }
  177. - (NSMutableArray<NSString*> *)classesForToken:(TBToken *)token inBundles:(NSMutableArray<NSString*> *)bundles {
  178. // Edge case where token is the class we want already
  179. if (token.isAbsolute) {
  180. if (MKClassIsSafe(NSClassFromString(token.string))) {
  181. return [NSMutableArray arrayWithObject:token.string];
  182. }
  183. return [NSMutableArray array];
  184. }
  185. if (bundles.count) {
  186. // Get class names, remove unsafe classes
  187. NSMutableArray<NSString*> *names = [self _classesForToken:token inBundles:bundles];
  188. return [names flex_mapped:^NSString *(NSString *cls, NSUInteger idx) {
  189. NSSet *ignored = MKKnownUnsafeClassNames();
  190. BOOL safe = ![ignored containsObject:cls];
  191. return safe ? cls : nil;
  192. }];
  193. }
  194. return [NSMutableArray array];
  195. }
  196. - (NSMutableArray<NSString*> *)_classesForToken:(TBToken *)token inBundles:(NSMutableArray<NSString*> *)bundles {
  197. TBWildcardOptions options = token.options;
  198. NSString *query = token.string;
  199. // Optimization, avoid unnecessary sorting
  200. if (bundles.count == 1) {
  201. // Optimization, avoid a loop
  202. if (options == TBWildcardOptionsAny) {
  203. return [self classNamesInImageAtPath:bundles.firstObject];
  204. }
  205. return [[self classNamesInImageAtPath:bundles.firstObject] flex_mapped:^id(NSString *className, NSUInteger idx) {
  206. return TBWildcardMap(query, className, options);
  207. }];
  208. }
  209. else {
  210. // Optimization, avoid a loop
  211. if (options == TBWildcardOptionsAny) {
  212. return [[bundles flex_mapped:^NSArray *(NSString *bundlePath, NSUInteger idx) {
  213. return [self classNamesInImageAtPath:bundlePath];
  214. }] sortedUsingSelector:@selector(caseInsensitiveCompare:)];
  215. }
  216. return [[bundles flex_mapped:^NSArray *(NSString *bundlePath, NSUInteger idx) {
  217. return [[self classNamesInImageAtPath:bundlePath] flex_mapped:^id(NSString *className, NSUInteger idx) {
  218. return TBWildcardMap(query, className, options);
  219. }];
  220. }] sortedUsingSelector:@selector(caseInsensitiveCompare:)];
  221. }
  222. }
  223. - (NSMutableArray<FLEXMethod*> *)methodsForToken:(TBToken *)token
  224. instance:(NSNumber *)checkInstance
  225. inClasses:(NSMutableArray *)classes {
  226. if (classes.count) {
  227. TBWildcardOptions options = token.options;
  228. BOOL instance = checkInstance.boolValue;
  229. NSString *selector = token.string;
  230. switch (options) {
  231. /// In practice, I don't think this case is ever used with methods
  232. case TBWildcardOptionsNone: {
  233. SEL sel = (SEL)selector.UTF8String;
  234. return [classes flex_mapped:^id(NSString *name, NSUInteger idx) {
  235. Class cls = NSClassFromString(name);
  236. // Method is absolute
  237. return [MKLazyMethod methodForSelector:sel class:cls instance:instance];
  238. }];
  239. }
  240. case TBWildcardOptionsAny: {
  241. return [classes flex_mapped:^NSArray *(NSString *name, NSUInteger idx) {
  242. // Any means `instance` was not specified
  243. Class cls = NSClassFromString(name);
  244. return [cls flex_allMethods];
  245. }];
  246. }
  247. default: {
  248. // Only "if contains"
  249. if (options & TBWildcardOptionsPrefix &&
  250. options & TBWildcardOptionsSuffix) {
  251. return [classes flex_mapped:^NSArray *(NSString *name, NSUInteger idx) {
  252. Class cls = NSClassFromString(name);
  253. return [[cls flex_allMethods] flex_mapped:^id(FLEXMethod *method, NSUInteger idx) {
  254. // Method is a prefix-suffix wildcard
  255. if (TBContains(method.selectorString, selector)) {
  256. return method;
  257. }
  258. return nil;
  259. }];
  260. }];
  261. }
  262. // Only "if method ends with with selector"
  263. else if (options & TBWildcardOptionsPrefix) {
  264. return [classes flex_mapped:^NSArray *(NSString *name, NSUInteger idx) {
  265. Class cls = NSClassFromString(name);
  266. return [[cls flex_allMethods] flex_mapped:^id(FLEXMethod *method, NSUInteger idx) {
  267. // Method is a prefix wildcard
  268. if (TBHasSuffix(method.selectorString, selector)) {
  269. return method;
  270. }
  271. return nil;
  272. }];
  273. }];
  274. }
  275. // Only "if method starts with with selector"
  276. else if (options & TBWildcardOptionsSuffix) {
  277. assert(checkInstance);
  278. return [classes flex_mapped:^NSArray *(NSString *name, NSUInteger idx) {
  279. Class cls = NSClassFromString(name);
  280. // Case like "Bundle.class.-" where we want "-" to match anything
  281. if (!selector.length) {
  282. if (instance) {
  283. return [cls flex_allInstanceMethods];
  284. } else {
  285. return [cls flex_allClassMethods];
  286. }
  287. }
  288. id mapping = ^id(FLEXMethod *method) {
  289. // Method is a suffix wildcard
  290. if (TBHasPrefix(method.selectorString, selector)) {
  291. return method;
  292. }
  293. return nil;
  294. };
  295. if (instance) {
  296. return [[cls flex_allInstanceMethods] flex_mapped:mapping];
  297. } else {
  298. return [[cls flex_allClassMethods] flex_mapped:mapping];
  299. }
  300. }];
  301. }
  302. }
  303. }
  304. }
  305. return [NSMutableArray array];
  306. }
  307. @end