LKS_TraceManager.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #ifdef SHOULD_COMPILE_LOOKIN_SERVER
  2. //
  3. // LKS_TraceManager.m
  4. // LookinServer
  5. //
  6. // Created by Li Kai on 2019/5/5.
  7. // https://lookin.work
  8. //
  9. #import "LKS_TraceManager.h"
  10. #import <objc/runtime.h>
  11. #import "LookinIvarTrace.h"
  12. #import "LookinServerDefines.h"
  13. #import "LookinWeakContainer.h"
  14. #ifdef LOOKIN_SERVER_SWIFT_ENABLED
  15. #if __has_include(<LookinServer/LookinServer-Swift.h>)
  16. #import <LookinServer/LookinServer-Swift.h>
  17. #define LOOKIN_SERVER_SWIFT_ENABLED_SUCCESSFULLY
  18. #elif __has_include("LookinServer-Swift.h")
  19. #import "LookinServer-Swift.h"
  20. #define LOOKIN_SERVER_SWIFT_ENABLED_SUCCESSFULLY
  21. #endif
  22. #endif
  23. #ifdef SPM_LOOKIN_SERVER_ENABLED
  24. @import LookinServerSwift;
  25. #define LOOKIN_SERVER_SWIFT_ENABLED_SUCCESSFULLY
  26. #endif
  27. @interface LKS_TraceManager ()
  28. @property(nonatomic, strong) NSMutableArray<LookinWeakContainer *> *searchTargets;
  29. @end
  30. @implementation LKS_TraceManager
  31. + (instancetype)sharedInstance {
  32. static dispatch_once_t onceToken;
  33. static LKS_TraceManager *instance = nil;
  34. dispatch_once(&onceToken,^{
  35. instance = [[super allocWithZone:NULL] init];
  36. });
  37. return instance;
  38. }
  39. + (id)allocWithZone:(struct _NSZone *)zone {
  40. return [self sharedInstance];
  41. }
  42. - (void)addSearchTarger:(id)target {
  43. if (!target) {
  44. return;
  45. }
  46. if (!self.searchTargets) {
  47. self.searchTargets = [NSMutableArray array];
  48. }
  49. LookinWeakContainer *container = [LookinWeakContainer containerWithObject:target];
  50. [self.searchTargets addObject:container];
  51. }
  52. - (void)reload {
  53. // 把旧的先都清理掉
  54. [NSObject lks_clearAllObjectsTraces];
  55. [self.searchTargets enumerateObjectsUsingBlock:^(LookinWeakContainer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  56. if (!obj.object) {
  57. return;
  58. }
  59. [self _markIVarsInAllClassLevelsOfObject:obj.object];
  60. }];
  61. [[[UIApplication sharedApplication].windows copy] enumerateObjectsUsingBlock:^(__kindof UIWindow * _Nonnull window, NSUInteger idx, BOOL * _Nonnull stop) {
  62. [self _addTraceForLayersRootedByLayer:window.layer];
  63. }];
  64. }
  65. - (void)_addTraceForLayersRootedByLayer:(CALayer *)layer {
  66. UIView *view = layer.lks_hostView;
  67. if ([view.superview lks_isChildrenViewOfTabBar]) {
  68. view.lks_isChildrenViewOfTabBar = YES;
  69. } else if ([view isKindOfClass:[UITabBar class]]) {
  70. view.lks_isChildrenViewOfTabBar = YES;
  71. }
  72. if (view) {
  73. [self _markIVarsInAllClassLevelsOfObject:view];
  74. UIViewController* vc = [view lks_findHostViewController];
  75. if (vc) {
  76. [self _markIVarsInAllClassLevelsOfObject:vc];
  77. }
  78. [self _buildSpecialTraceForView:view];
  79. } else {
  80. [self _markIVarsInAllClassLevelsOfObject:layer];
  81. }
  82. [[layer.sublayers copy] enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull sublayer, NSUInteger idx, BOOL * _Nonnull stop) {
  83. [self _addTraceForLayersRootedByLayer:sublayer];
  84. }];
  85. }
  86. - (void)_buildSpecialTraceForView:(UIView *)view {
  87. UIViewController* vc = [view lks_findHostViewController];
  88. if (vc) {
  89. view.lks_specialTrace = [NSString stringWithFormat:@"%@.view", NSStringFromClass(vc.class)];
  90. } else if ([view isKindOfClass:[UIWindow class]]) {
  91. CGFloat currentWindowLevel = ((UIWindow *)view).windowLevel;
  92. if (((UIWindow *)view).isKeyWindow) {
  93. view.lks_specialTrace = [NSString stringWithFormat:@"KeyWindow ( Level: %@ )", @(currentWindowLevel)];
  94. } else {
  95. view.lks_specialTrace = [NSString stringWithFormat:@"WindowLevel: %@", @(currentWindowLevel)];
  96. }
  97. } else if ([view isKindOfClass:[UITableViewCell class]]) {
  98. ((UITableViewCell *)view).backgroundView.lks_specialTrace = @"cell.backgroundView";
  99. ((UITableViewCell *)view).accessoryView.lks_specialTrace = @"cell.accessoryView";
  100. } else if ([view isKindOfClass:[UITableView class]]) {
  101. UITableView *tableView = (UITableView *)view;
  102. NSMutableArray<NSNumber *> *relatedSectionIdx = [NSMutableArray array];
  103. [[tableView visibleCells] enumerateObjectsUsingBlock:^(__kindof UITableViewCell * _Nonnull cell, NSUInteger idx, BOOL * _Nonnull stop) {
  104. NSIndexPath *indexPath = [tableView indexPathForCell:cell];
  105. cell.lks_specialTrace = [NSString stringWithFormat:@"{ sec:%@, row:%@ }", @(indexPath.section), @(indexPath.row)];
  106. if (![relatedSectionIdx containsObject:@(indexPath.section)]) {
  107. [relatedSectionIdx addObject:@(indexPath.section)];
  108. }
  109. }];
  110. [relatedSectionIdx enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  111. NSUInteger secIdx = [obj unsignedIntegerValue];
  112. UIView *secHeaderView = [tableView headerViewForSection:secIdx];
  113. secHeaderView.lks_specialTrace = [NSString stringWithFormat:@"sectionHeader { sec: %@ }", @(secIdx)];
  114. UIView *secFooterView = [tableView footerViewForSection:secIdx];
  115. secFooterView.lks_specialTrace = [NSString stringWithFormat:@"sectionFooter { sec: %@ }", @(secIdx)];
  116. }];
  117. } else if ([view isKindOfClass:[UICollectionView class]]) {
  118. UICollectionView *collectionView = (UICollectionView *)view;
  119. collectionView.backgroundView.lks_specialTrace = @"collectionView.backgroundView";
  120. if (@available(iOS 9.0, *)) {
  121. [[collectionView indexPathsForVisibleSupplementaryElementsOfKind:UICollectionElementKindSectionHeader] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull indexPath, NSUInteger idx, BOOL * _Nonnull stop) {
  122. UIView *headerView = [collectionView supplementaryViewForElementKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
  123. headerView.lks_specialTrace = [NSString stringWithFormat:@"sectionHeader { sec:%@ }", @(indexPath.section)];
  124. }];
  125. [[collectionView indexPathsForVisibleSupplementaryElementsOfKind:UICollectionElementKindSectionFooter] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull indexPath, NSUInteger idx, BOOL * _Nonnull stop) {
  126. UIView *footerView = [collectionView supplementaryViewForElementKind:UICollectionElementKindSectionFooter atIndexPath:indexPath];
  127. footerView.lks_specialTrace = [NSString stringWithFormat:@"sectionFooter { sec:%@ }", @(indexPath.section)];
  128. }];
  129. }
  130. [[collectionView visibleCells] enumerateObjectsUsingBlock:^(__kindof UICollectionViewCell * _Nonnull cell, NSUInteger idx, BOOL * _Nonnull stop) {
  131. NSIndexPath *indexPath = [collectionView indexPathForCell:cell];
  132. cell.lks_specialTrace = [NSString stringWithFormat:@"{ item:%@, sec:%@ }", @(indexPath.item), @(indexPath.section)];
  133. }];
  134. } else if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  135. UITableViewHeaderFooterView *headerFooterView = (UITableViewHeaderFooterView *)view;
  136. headerFooterView.textLabel.lks_specialTrace = @"sectionHeaderFooter.textLabel";
  137. headerFooterView.detailTextLabel.lks_specialTrace = @"sectionHeaderFooter.detailTextLabel";
  138. }
  139. }
  140. - (void)_markIVarsInAllClassLevelsOfObject:(NSObject *)object {
  141. [self _markIVarsOfObject:object class:object.class];
  142. #ifdef LOOKIN_SERVER_SWIFT_ENABLED_SUCCESSFULLY
  143. [LKS_SwiftTraceManager swiftMarkIVarsOfObject:object];
  144. #endif
  145. }
  146. - (void)_markIVarsOfObject:(NSObject *)hostObject class:(Class)targetClass {
  147. if (!targetClass) {
  148. return;
  149. }
  150. NSArray<NSString *> *prefixesToTerminateRecursion = @[@"NSObject", @"UIResponder", @"UIButton", @"UIButtonLabel"];
  151. BOOL hasPrefix = [prefixesToTerminateRecursion lookin_any:^BOOL(NSString *prefix) {
  152. return [NSStringFromClass(targetClass) hasPrefix:prefix];
  153. }];
  154. if (hasPrefix) {
  155. return;
  156. }
  157. unsigned int outCount = 0;
  158. Ivar *ivars = class_copyIvarList(targetClass, &outCount);
  159. for (unsigned int i = 0; i < outCount; i ++) {
  160. Ivar ivar = ivars[i];
  161. NSString *ivarType = [[NSString alloc] lookin_safeInitWithUTF8String:ivar_getTypeEncoding(ivar)];
  162. if (![ivarType hasPrefix:@"@"] || ivarType.length <= 3) {
  163. continue;
  164. }
  165. NSString *ivarClassName = [ivarType substringWithRange:NSMakeRange(2, ivarType.length - 3)];
  166. Class ivarClass = NSClassFromString(ivarClassName);
  167. if (![ivarClass isSubclassOfClass:[UIView class]]
  168. && ![ivarClass isSubclassOfClass:[CALayer class]]
  169. && ![ivarClass isSubclassOfClass:[UIViewController class]]
  170. && ![ivarClass isSubclassOfClass:[UIGestureRecognizer class]]) {
  171. continue;
  172. }
  173. const char * ivarNameChar = ivar_getName(ivar);
  174. if (!ivarNameChar) {
  175. continue;
  176. }
  177. // 这个 ivarObject 可能的类型:UIView, CALayer, UIViewController, UIGestureRecognizer
  178. NSObject *ivarObject = object_getIvar(hostObject, ivar);
  179. if (!ivarObject || ![ivarObject isKindOfClass:[NSObject class]]) {
  180. continue;
  181. }
  182. LookinIvarTrace *ivarTrace = [LookinIvarTrace new];
  183. ivarTrace.hostObject = hostObject;
  184. ivarTrace.hostClassName = [self makeDisplayClassNameWithSuper:targetClass childClass:hostObject.class];
  185. ivarTrace.ivarName = [[NSString alloc] lookin_safeInitWithUTF8String:ivarNameChar];
  186. if (hostObject == ivarObject) {
  187. ivarTrace.relation = LookinIvarTraceRelationValue_Self;
  188. } else if ([hostObject isKindOfClass:[UIView class]]) {
  189. CALayer *ivarLayer = nil;
  190. if ([ivarObject isKindOfClass:[CALayer class]]) {
  191. ivarLayer = (CALayer *)ivarObject;
  192. } else if ([ivarObject isKindOfClass:[UIView class]]) {
  193. ivarLayer = ((UIView *)ivarObject).layer;
  194. }
  195. if (ivarLayer && (ivarLayer.superlayer == ((UIView *)hostObject).layer)) {
  196. ivarTrace.relation = @"superview";
  197. }
  198. }
  199. if ([LKS_InvalidIvarTraces() containsObject:ivarTrace]) {
  200. continue;
  201. }
  202. if (![ivarObject respondsToSelector:@selector(lks_ivarTraces)] || ![ivarObject respondsToSelector:@selector(setLks_ivarTraces:)]) {
  203. continue;
  204. }
  205. if (!ivarObject.lks_ivarTraces) {
  206. ivarObject.lks_ivarTraces = [NSArray array];
  207. }
  208. if (![ivarObject.lks_ivarTraces containsObject:ivarTrace]) {
  209. ivarObject.lks_ivarTraces = [ivarObject.lks_ivarTraces arrayByAddingObject:ivarTrace];
  210. }
  211. }
  212. free(ivars);
  213. Class superClass = [targetClass superclass];
  214. [self _markIVarsOfObject:hostObject class:superClass];
  215. }
  216. // 比如 superClass 可能是 UIView,而 childClass 可能是 UIButton
  217. - (NSString *)makeDisplayClassNameWithSuper:(Class)superClass childClass:(Class)childClass {
  218. NSString *superName = NSStringFromClass(superClass);
  219. if (!childClass) {
  220. return superName;
  221. }
  222. NSString *childName = NSStringFromClass(childClass);
  223. if ([childName isEqualToString:superName]) {
  224. return superName;
  225. }
  226. return [NSString stringWithFormat:@"%@ : %@", childName, superName];
  227. }
  228. static NSSet<LookinIvarTrace *> *LKS_InvalidIvarTraces(void) {
  229. static NSSet *list;
  230. static dispatch_once_t onceToken;
  231. dispatch_once(&onceToken, ^{
  232. NSMutableSet *set = [NSMutableSet set];
  233. [set addObject:({
  234. LookinIvarTrace *trace = [LookinIvarTrace new];
  235. trace.hostClassName = @"UIView";
  236. trace.ivarName = @"_window";
  237. trace;
  238. })];
  239. [set addObject:({
  240. LookinIvarTrace *trace = [LookinIvarTrace new];
  241. trace.hostClassName = @"UIViewController";
  242. trace.ivarName = @"_view";
  243. trace;
  244. })];
  245. [set addObject:({
  246. LookinIvarTrace *trace = [LookinIvarTrace new];
  247. trace.hostClassName = @"UIView";
  248. trace.ivarName = @"_viewDelegate";
  249. trace;
  250. })];
  251. [set addObject:({
  252. LookinIvarTrace *trace = [LookinIvarTrace new];
  253. trace.hostClassName = @"UIViewController";
  254. trace.ivarName = @"_parentViewController";
  255. trace;
  256. })];
  257. list = set.copy;
  258. });
  259. return list;
  260. }
  261. @end
  262. #endif /* SHOULD_COMPILE_LOOKIN_SERVER */