FLEXObjectListViewController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //
  2. // FLEXObjectListViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 5/28/14.
  6. // Copyright (c) 2020 FLEX Team. All rights reserved.
  7. //
  8. #import "FLEXObjectListViewController.h"
  9. #import "FLEXObjectExplorerFactory.h"
  10. #import "FLEXObjectExplorerViewController.h"
  11. #import "FLEXMutableListSection.h"
  12. #import "FLEXRuntimeUtility.h"
  13. #import "FLEXUtility.h"
  14. #import "FLEXHeapEnumerator.h"
  15. #import "FLEXObjectRef.h"
  16. #import "NSString+FLEX.h"
  17. #import "NSObject+FLEX_Reflection.h"
  18. #import "FLEXTableViewCell.h"
  19. #import <malloc/malloc.h>
  20. typedef NS_ENUM(NSUInteger, FLEXObjectReferenceSection) {
  21. FLEXObjectReferenceSectionMain,
  22. FLEXObjectReferenceSectionAutoLayout,
  23. FLEXObjectReferenceSectionKVO,
  24. FLEXObjectReferenceSectionFLEX,
  25. FLEXObjectReferenceSectionCount
  26. };
  27. NSArray<NSString *> * FLEXObjectReferenceSectionTitles() {
  28. return @[
  29. @"", @"AutoLayout", @"Key-Value Observing", @"FLEX"
  30. ];
  31. }
  32. NSString const * FLEXTitleForObjectReferenceSection(FLEXObjectReferenceSection section) {
  33. switch (section) {
  34. case FLEXObjectReferenceSectionCount: @throw NSInternalInconsistencyException;
  35. default: return FLEXObjectReferenceSectionTitles()[section];
  36. }
  37. }
  38. @interface FLEXObjectListViewController ()
  39. @property (nonatomic, copy) NSArray<FLEXMutableListSection *> *sections;
  40. @property (nonatomic, copy) NSArray<FLEXMutableListSection *> *allSections;
  41. @property (nonatomic, readonly) NSArray<FLEXObjectRef *> *references;
  42. @property (nonatomic, readonly) NSArray<NSPredicate *> *predicates;
  43. @property (nonatomic, readonly) NSArray<NSString *> *sectionTitles;
  44. @end
  45. @implementation FLEXObjectListViewController
  46. @dynamic sections, allSections;
  47. #pragma mark - Reference Grouping
  48. + (NSPredicate *)defaultPredicateForSection:(NSInteger)section {
  49. // These are the types of references that we typically don't care about.
  50. // We want this list of "object-ivar pairs" split into two sections.
  51. BOOL(^isKVORelated)(FLEXObjectRef *, NSDictionary *) = ^BOOL(FLEXObjectRef *ref, NSDictionary *bindings) {
  52. NSString *row = ref.reference;
  53. return [row isEqualToString:@"__NSObserver object"] ||
  54. [row isEqualToString:@"_CFXNotificationObjcObserverRegistration _object"];
  55. };
  56. /// These are common AutoLayout related references we also rarely care about.
  57. BOOL(^isConstraintRelated)(FLEXObjectRef *, NSDictionary *) = ^BOOL(FLEXObjectRef *ref, NSDictionary *bindings) {
  58. static NSSet *ignored = nil;
  59. static dispatch_once_t onceToken;
  60. dispatch_once(&onceToken, ^{
  61. ignored = [NSSet setWithArray:@[
  62. @"NSLayoutConstraint _container",
  63. @"NSContentSizeLayoutConstraint _container",
  64. @"NSAutoresizingMaskLayoutConstraint _container",
  65. @"MASViewConstraint _installedView",
  66. @"MASLayoutConstraint _container",
  67. @"MASViewAttribute _view"
  68. ]];
  69. });
  70. NSString *row = ref.reference;
  71. return ([row hasPrefix:@"NSLayout"] && [row hasSuffix:@" _referenceItem"]) ||
  72. ([row hasPrefix:@"NSIS"] && [row hasSuffix:@" _delegate"]) ||
  73. ([row hasPrefix:@"_NSAutoresizingMask"] && [row hasSuffix:@" _referenceItem"]) ||
  74. [ignored containsObject:row];
  75. };
  76. /// These are FLEX classes and usually you aren't looking for FLEX references inside FLEX itself
  77. BOOL(^isFLEXClass)(FLEXObjectRef *, NSDictionary *) = ^BOOL(FLEXObjectRef *ref, NSDictionary *bindings) {
  78. return [ref.reference hasPrefix:@"FLEX"];
  79. };
  80. BOOL(^isEssential)(FLEXObjectRef *, NSDictionary *) = ^BOOL(FLEXObjectRef *ref, NSDictionary *bindings) {
  81. return !(
  82. isKVORelated(ref, bindings) ||
  83. isConstraintRelated(ref, bindings) ||
  84. isFLEXClass(ref, bindings)
  85. );
  86. };
  87. switch (section) {
  88. case FLEXObjectReferenceSectionMain:
  89. return [NSPredicate predicateWithBlock:isEssential];
  90. case FLEXObjectReferenceSectionAutoLayout:
  91. return [NSPredicate predicateWithBlock:isConstraintRelated];
  92. case FLEXObjectReferenceSectionKVO:
  93. return [NSPredicate predicateWithBlock:isKVORelated];
  94. case FLEXObjectReferenceSectionFLEX:
  95. return [NSPredicate predicateWithBlock:isFLEXClass];
  96. default: return nil;
  97. }
  98. }
  99. + (NSArray<NSPredicate *> *)defaultPredicates {
  100. return [NSArray flex_forEachUpTo:FLEXObjectReferenceSectionCount map:^id(NSUInteger i) {
  101. return [self defaultPredicateForSection:i];
  102. }];
  103. }
  104. #pragma mark - Initialization
  105. - (id)initWithReferences:(NSArray<FLEXObjectRef *> *)references {
  106. return [self initWithReferences:references predicates:nil sectionTitles:nil];
  107. }
  108. - (id)initWithReferences:(NSArray<FLEXObjectRef *> *)references
  109. predicates:(NSArray<NSPredicate *> *)predicates
  110. sectionTitles:(NSArray<NSString *> *)sectionTitles {
  111. NSParameterAssert(predicates.count == sectionTitles.count);
  112. self = [super initWithStyle:UITableViewStylePlain];
  113. if (self) {
  114. _references = references;
  115. _predicates = predicates;
  116. _sectionTitles = sectionTitles;
  117. }
  118. return self;
  119. }
  120. + (UIViewController *)instancesOfClassWithName:(NSString *)className {
  121. const char *classNameCString = className.UTF8String;
  122. NSMutableArray *instances = [NSMutableArray new];
  123. [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id object, __unsafe_unretained Class actualClass) {
  124. if (strcmp(classNameCString, class_getName(actualClass)) == 0) {
  125. // Note: objects of certain classes crash when retain is called.
  126. // It is up to the user to avoid tapping into instance lists for these classes.
  127. // Ex. OS_dispatch_queue_specific_queue
  128. // In the future, we could provide some kind of warning for classes that are known to be problematic.
  129. if (malloc_size((__bridge const void *)(object)) > 0) {
  130. [instances addObject:object];
  131. }
  132. }
  133. }];
  134. NSArray<FLEXObjectRef *> *references = [FLEXObjectRef referencingAll:instances];
  135. if (references.count == 1) {
  136. return [FLEXObjectExplorerFactory
  137. explorerViewControllerForObject:references.firstObject.object
  138. ];
  139. }
  140. FLEXObjectListViewController *controller = [[self alloc] initWithReferences:references];
  141. controller.title = [NSString stringWithFormat:@"%@ (%lu)", className, (unsigned long)instances.count];
  142. return controller;
  143. }
  144. + (instancetype)subclassesOfClassWithName:(NSString *)className {
  145. NSArray<Class> *classes = FLEXGetAllSubclasses(NSClassFromString(className), NO);
  146. NSArray<FLEXObjectRef *> *references = [FLEXObjectRef referencingClasses:classes];
  147. FLEXObjectListViewController *controller = [[self alloc] initWithReferences:references];
  148. controller.title = [NSString stringWithFormat:@"Subclasses of %@ (%lu)",
  149. className, (unsigned long)classes.count
  150. ];
  151. return controller;
  152. }
  153. + (instancetype)objectsWithReferencesToObject:(id)object {
  154. static Class SwiftObjectClass = nil;
  155. static dispatch_once_t onceToken;
  156. dispatch_once(&onceToken, ^{
  157. SwiftObjectClass = NSClassFromString(@"SwiftObject");
  158. if (!SwiftObjectClass) {
  159. SwiftObjectClass = NSClassFromString(@"Swift._SwiftObject");
  160. }
  161. });
  162. NSMutableArray<FLEXObjectRef *> *instances = [NSMutableArray new];
  163. [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id tryObject, __unsafe_unretained Class actualClass) {
  164. // Get all the ivars on the object. Start with the class and and travel up the inheritance chain.
  165. // Once we find a match, record it and move on to the next object. There's no reason to find multiple matches within the same object.
  166. Class tryClass = actualClass;
  167. while (tryClass) {
  168. unsigned int ivarCount = 0;
  169. Ivar *ivars = class_copyIvarList(tryClass, &ivarCount);
  170. for (unsigned int ivarIndex = 0; ivarIndex < ivarCount; ivarIndex++) {
  171. Ivar ivar = ivars[ivarIndex];
  172. NSString *typeEncoding = @(ivar_getTypeEncoding(ivar) ?: "");
  173. if (typeEncoding.flex_typeIsObjectOrClass) {
  174. ptrdiff_t offset = ivar_getOffset(ivar);
  175. uintptr_t *fieldPointer = (__bridge void *)tryObject + offset;
  176. if (*fieldPointer == (uintptr_t)(__bridge void *)object) {
  177. NSString *ivarName = @(ivar_getName(ivar) ?: "???");
  178. [instances addObject:[FLEXObjectRef referencing:tryObject ivar:ivarName]];
  179. return;
  180. }
  181. }
  182. }
  183. tryClass = class_getSuperclass(tryClass);
  184. }
  185. }];
  186. NSArray<NSPredicate *> *predicates = [self defaultPredicates];
  187. NSArray<NSString *> *sectionTitles = FLEXObjectReferenceSectionTitles();
  188. FLEXObjectListViewController *viewController = [[self alloc]
  189. initWithReferences:instances
  190. predicates:predicates
  191. sectionTitles:sectionTitles
  192. ];
  193. viewController.title = [NSString stringWithFormat:@"Referencing %@ %p",
  194. [FLEXRuntimeUtility safeClassNameForObject:object], object
  195. ];
  196. return viewController;
  197. }
  198. #pragma mark - Overrides
  199. - (void)viewDidLoad {
  200. [super viewDidLoad];
  201. self.showsSearchBar = YES;
  202. }
  203. - (NSArray<FLEXMutableListSection *> *)makeSections {
  204. if (self.predicates.count) {
  205. return [self buildSections:self.sectionTitles predicates:self.predicates];
  206. } else {
  207. return @[[self makeSection:self.references title:nil]];
  208. }
  209. }
  210. #pragma mark - Private
  211. - (NSArray *)buildSections:(NSArray<NSString *> *)titles predicates:(NSArray<NSPredicate *> *)predicates {
  212. NSParameterAssert(titles.count == predicates.count);
  213. NSParameterAssert(titles); NSParameterAssert(predicates);
  214. return [NSArray flex_forEachUpTo:titles.count map:^id(NSUInteger i) {
  215. NSArray *rows = [self.references filteredArrayUsingPredicate:predicates[i]];
  216. return [self makeSection:rows title:titles[i]];
  217. }];
  218. }
  219. - (FLEXMutableListSection *)makeSection:(NSArray *)rows title:(NSString *)title {
  220. FLEXMutableListSection *section = [FLEXMutableListSection list:rows
  221. cellConfiguration:^(FLEXTableViewCell *cell, FLEXObjectRef *ref, NSInteger row) {
  222. cell.textLabel.text = ref.reference;
  223. cell.detailTextLabel.text = ref.summary;
  224. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  225. } filterMatcher:^BOOL(NSString *filterText, FLEXObjectRef *ref) {
  226. if (ref.summary && [ref.summary localizedCaseInsensitiveContainsString:filterText]) {
  227. return YES;
  228. }
  229. return [ref.reference localizedCaseInsensitiveContainsString:filterText];
  230. }
  231. ];
  232. __weak __typeof(self) weakSelf = self;
  233. section.selectionHandler = ^(__kindof UIViewController *host, FLEXObjectRef *ref) {
  234. __strong __typeof(self) strongSelf = weakSelf;
  235. if (strongSelf) {
  236. [strongSelf.navigationController pushViewController:[
  237. FLEXObjectExplorerFactory explorerViewControllerForObject:ref.object
  238. ] animated:YES];
  239. }
  240. };
  241. section.customTitle = title;
  242. return section;
  243. }
  244. @end