FLEXRuntimeClient.m 14 KB

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