Repository navigation
Expand file tree
/
Copy pathDebugTools.m
More file actions
413 lines (387 loc) · 21.3 KB
/
Copy pathDebugTools.m
File metadata and controls
413 lines (387 loc) · 21.3 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Development-only helpers, compiled out of release builds (make package FINALPACKAGE=1).
//
// Over SSH, while the lock screen is visible:
// touch /var/mobile/Documents/lsr-dump-request
// -> LockScreenRestoreViews-now.log: every view in every window (class, frame in window
// coordinates, hidden/alpha/transform, label text/font/color)
// printf "Focus\nCSFocus\n" > /var/mobile/Documents/lsr-recon-request
// -> LockScreenRestoreRecon-now.log: methods/ivars/properties of matching classes
// printf "CSCombinedListViewController topContentInset\n" > /var/mobile/Documents/lsr-call-request
// -> LockScreenRestoreCalls-now.log: result of a zero-argument getter on the live instance
// ("Class +selector" calls a class method; "Class a.b.c" follows a getter chain;
// "Class setFoo: 3" calls a setter with a number, YES/NO or {struct})
// touch /var/mobile/Documents/lsr-snap-request
// -> LockScreenRestoreSnap-<n>.png: image of every visible window
//
// In MediaRemoteUI (the lock screen music player) the same files live in the app's sandboxed
// tmp folder instead: find it with find /var/mobile/Containers/Data -name lsr-debug-here
#ifdef DEBUG
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import "LSRSim.h"
static NSString *LSRDebugPath(NSString *name) {
static NSString *dir;
static dispatch_once_t once;
dispatch_once(&once, ^{
BOOL springBoard = [[NSProcessInfo processInfo].processName isEqualToString:@"SpringBoard"];
dir = springBoard ? LSRDevicePath(@"/var/mobile/Documents") : NSTemporaryDirectory();
});
return [dir stringByAppendingPathComponent:name];
}
@interface UIWindow (LSRPrivate)
+ (NSArray *)allWindowsIncludingInternalWindows:(BOOL)includeInternal onlyVisibleWindows:(BOOL)onlyVisible;
@end
static void LSRDumpClass(Class cls, NSMutableString *out) {
[out appendFormat:@"\n=== %@ (superclass: %@) ===\n", NSStringFromClass(cls), NSStringFromClass(class_getSuperclass(cls))];
unsigned int count = 0;
Method *methods = class_copyMethodList(cls, &count);
[out appendFormat:@"-- instance methods (%u) --\n", count];
for (unsigned int i = 0; i < count; i++) {
[out appendFormat:@" - %@ %s\n", NSStringFromSelector(method_getName(methods[i])),
method_getTypeEncoding(methods[i]) ?: ""];
}
free(methods);
methods = class_copyMethodList(object_getClass(cls), &count);
[out appendFormat:@"-- class methods (%u) --\n", count];
for (unsigned int i = 0; i < count; i++) {
[out appendFormat:@" + %@ %s\n", NSStringFromSelector(method_getName(methods[i])),
method_getTypeEncoding(methods[i]) ?: ""];
}
free(methods);
Ivar *ivars = class_copyIvarList(cls, &count);
[out appendFormat:@"-- ivars (%u) --\n", count];
for (unsigned int i = 0; i < count; i++) {
[out appendFormat:@" %s (%s)\n", ivar_getName(ivars[i]) ?: "?", ivar_getTypeEncoding(ivars[i]) ?: "?"];
}
free(ivars);
objc_property_t *props = class_copyPropertyList(cls, &count);
[out appendFormat:@"-- properties (%u) --\n", count];
for (unsigned int i = 0; i < count; i++) {
[out appendFormat:@" @property %s (%s)\n", property_getName(props[i]), property_getAttributes(props[i]) ?: ""];
}
free(props);
}
static void LSRRunRecon(NSArray<NSString *> *fragments) {
NSMutableString *out = [NSMutableString new];
[out appendFormat:@"LockScreenRestore recon %@ — %@\n", fragments, [NSDate date]];
int numClasses = objc_getClassList(NULL, 0);
Class *classes = (Class *)malloc(sizeof(Class) * (unsigned long)numClasses);
numClasses = objc_getClassList(classes, numClasses);
for (int i = 0; i < numClasses; i++) {
NSString *name = NSStringFromClass(classes[i]);
for (NSString *fragment in fragments) {
if ([name rangeOfString:fragment options:NSCaseInsensitiveSearch].location != NSNotFound) {
LSRDumpClass(classes[i], out);
break;
}
}
}
free(classes);
[out writeToFile:LSRDebugPath(@"LockScreenRestoreRecon-now.log") atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}
static void LSRDumpView(UIView *view, NSUInteger depth, NSMutableString *out) {
NSString *extra = @"";
if ([view isKindOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)view;
extra = [NSString stringWithFormat:@" text=\"%@\" font=%@ %.1f color=%@", label.text,
label.font.fontName, label.font.pointSize, label.textColor];
} else if ([view isKindOfClass:[UIImageView class]]) {
UIImageView *imageView = (UIImageView *)view;
extra = [NSString stringWithFormat:@" image=%@ tint=%@", imageView.image, imageView.tintColor];
}
if (view.backgroundColor) extra = [extra stringByAppendingFormat:@" bg=%@", view.backgroundColor];
if (view.layer.cornerRadius > 0) extra = [extra stringByAppendingFormat:@" radius=%.1f", view.layer.cornerRadius];
NSString *transform = CGAffineTransformIsIdentity(view.transform) ? @""
: [NSString stringWithFormat:@" transform=%@", NSStringFromCGAffineTransform(view.transform)];
[out appendFormat:@"%@%@ %p frame=%@ hidden=%d alpha=%.2f%@%@\n",
[@"" stringByPaddingToLength:depth * 2 withString:@" " startingAtIndex:0],
NSStringFromClass([view class]), view, NSStringFromCGRect([view convertRect:view.bounds toView:nil]),
view.hidden, view.alpha, transform, extra];
for (UIView *sub in view.subviews) LSRDumpView(sub, depth + 1, out);
}
static void LSRDumpAllWindows(void) {
NSMutableString *out = [NSMutableString new];
[out appendFormat:@"### view dump — %@\n", [NSDate date]];
for (UIWindow *window in [UIWindow allWindowsIncludingInternalWindows:YES onlyVisibleWindows:NO]) {
[out appendFormat:@"\n##### WINDOW %@ level=%.0f hidden=%d\n", NSStringFromClass([window class]),
window.windowLevel, window.hidden];
LSRDumpView(window, 0, out);
}
[out writeToFile:LSRDebugPath(@"LockScreenRestoreViews-now.log") atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}
// Live object lookup: first view of the class in any window, else first view controller of
// the class reachable from the windows' root view controllers.
static id LSRFindViewOfClass(UIView *root, Class cls) {
if ([root isKindOfClass:cls]) return root;
for (UIView *sub in root.subviews) {
id found = LSRFindViewOfClass(sub, cls);
if (found) return found;
}
return nil;
}
static id LSRFindViewControllerOfClass(UIViewController *vc, Class cls) {
if (!vc) return nil;
if ([vc isKindOfClass:cls]) return vc;
for (UIViewController *child in vc.childViewControllers) {
id found = LSRFindViewControllerOfClass(child, cls);
if (found) return found;
}
return LSRFindViewControllerOfClass(vc.presentedViewController, cls);
}
static id LSRFindLiveObject(Class cls) {
NSArray *windows = [UIWindow allWindowsIncludingInternalWindows:YES onlyVisibleWindows:NO];
for (UIWindow *window in windows) {
id found = LSRFindViewOfClass(window, cls);
if (found) return found;
}
for (UIWindow *window in windows) {
id found = LSRFindViewControllerOfClass(window.rootViewController, cls);
if (found) return found;
}
return nil;
}
// Calls a zero-argument getter and formats the common return types.
static NSString *LSRCallGetter(id target, SEL sel) {
if (![target respondsToSelector:sel]) return @"<does not respond>";
NSMethodSignature *sig = [target methodSignatureForSelector:sel];
if (sig.numberOfArguments != 2) return @"<not a zero-argument getter>";
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];
inv.target = target;
inv.selector = sel;
[inv invoke];
const char *type = sig.methodReturnType;
if (type[0] == '@') {
__unsafe_unretained id value = nil;
[inv getReturnValue:&value];
return [NSString stringWithFormat:@"%@", value];
}
if (type[0] == 'B' || type[0] == 'c') { BOOL v; [inv getReturnValue:&v]; return v ? @"YES" : @"NO"; }
if (type[0] == 'd') { double v; [inv getReturnValue:&v]; return [NSString stringWithFormat:@"%.2f", v]; }
if (type[0] == 'q' || type[0] == 'Q' || type[0] == 'i' || type[0] == 'I' || type[0] == 'l' || type[0] == 'L') {
long long v = 0; [inv getReturnValue:&v]; return [NSString stringWithFormat:@"%lld", v];
}
if (strncmp(type, "{CGRect", 7) == 0) { CGRect v; [inv getReturnValue:&v]; return NSStringFromCGRect(v); }
if (strncmp(type, "{CGPoint", 8) == 0) { CGPoint v; [inv getReturnValue:&v]; return NSStringFromCGPoint(v); }
if (strncmp(type, "{CGSize", 7) == 0) { CGSize v; [inv getReturnValue:&v]; return NSStringFromCGSize(v); }
if (strncmp(type, "{UIEdgeInsets", 13) == 0) { UIEdgeInsets v; [inv getReturnValue:&v]; return NSStringFromUIEdgeInsets(v); }
return [NSString stringWithFormat:@"<unsupported return type %s>", type];
}
// Calls a one-argument setter with a number, BOOL (YES/NO) or struct string ({1, 2} / {1, 2, 3, 4}).
static NSString *LSRCallSetter(id target, SEL sel, NSString *arg) {
if (![target respondsToSelector:sel]) return @"<does not respond>";
NSMethodSignature *sig = [target methodSignatureForSelector:sel];
if (sig.numberOfArguments != 3) return @"<not a one-argument setter>";
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];
inv.target = target;
inv.selector = sel;
const char *type = [sig getArgumentTypeAtIndex:2];
if (type[0] == 'B' || type[0] == 'c') { BOOL v = [arg boolValue]; [inv setArgument:&v atIndex:2]; }
else if (type[0] == 'd') { double v = [arg doubleValue]; [inv setArgument:&v atIndex:2]; }
else if (type[0] == 'f') { float v = [arg floatValue]; [inv setArgument:&v atIndex:2]; }
else if (strchr("qQlLiI", type[0])) { long long v = [arg longLongValue]; [inv setArgument:&v atIndex:2]; }
else if (strncmp(type, "{CGSize", 7) == 0) { CGSize v = CGSizeFromString(arg); [inv setArgument:&v atIndex:2]; }
else if (strncmp(type, "{UIEdgeInsets", 13) == 0) { UIEdgeInsets v = UIEdgeInsetsFromString(arg); [inv setArgument:&v atIndex:2]; }
else return [NSString stringWithFormat:@"<unsupported argument type %s>", type];
[inv invoke];
return @"done";
}
// Request lines: "ClassName selector" or "ClassName setter: value" -> LockScreenRestoreCalls-now.log
static void LSRRunCalls(NSString *body) {
NSMutableString *out = [NSMutableString new];
for (NSString *line in [body componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
NSArray *parts = [[line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsSeparatedByString:@" "];
if (parts.count >= 3 && [parts[1] hasSuffix:@":"]) {
Class cls = NSClassFromString(parts[0]);
id target = cls ? LSRFindLiveObject(cls) : nil;
NSString *arg = [[parts subarrayWithRange:NSMakeRange(2, parts.count - 2)] componentsJoinedByString:@" "];
NSString *result = @"<no live instance>";
if (target) {
@try {
result = LSRCallSetter(target, NSSelectorFromString(parts[1]), arg);
} @catch (NSException *e) {
result = [NSString stringWithFormat:@"<exception %@>", e.reason];
}
}
[out appendFormat:@"%@ %@ %@ -> %@\n", parts[0], parts[1], arg, result];
continue;
}
if (parts.count != 2) continue;
Class cls = NSClassFromString(parts[0]);
// "+selector" calls a class method instead of looking for a live instance.
BOOL classCall = [parts[1] hasPrefix:@"+"];
if (classCall) parts = @[parts[0], [parts[1] substringFromIndex:1]];
id target = cls ? (classCall ? (id)cls : LSRFindLiveObject(cls)) : nil;
NSString *result = @"<no live instance>";
if (target) {
@try {
// "a.b.c": every step but the last must return an object.
NSArray *path = [parts[1] componentsSeparatedByString:@"."];
for (NSUInteger i = 0; i + 1 < path.count && target; i++) {
target = [target valueForKey:path[i]];
}
result = target ? LSRCallGetter(target, NSSelectorFromString(path.lastObject)) : @"<nil in path>";
} @catch (NSException *e) {
result = [NSString stringWithFormat:@"<exception %@>", e.reason];
}
}
[out appendFormat:@"%@ %@ = %@\n", parts[0], parts[1], result];
}
[out writeToFile:LSRDebugPath(@"LockScreenRestoreCalls-now.log") atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}
// Burst: for 120s, every 0.2s, note every *visible* view that could be a wallpaper copy (PBUI*,
// portals, snapshots, big images) -> LockScreenRestoreBurst-now.log with first/last sighting.
static BOOL LSRLooksLikeWallpaper(UIView *view) {
NSString *name = NSStringFromClass([view class]);
for (NSString *fragment in @[@"PBUI", @"Portal", @"Snapshot", @"Wallpaper", @"Parallax", @"Poster", @"LSRLive"]) {
if ([name containsString:fragment]) return YES;
}
if ([view isKindOfClass:[UIImageView class]]) {
CGSize size = ((UIImageView *)view).image.size;
return size.width >= 1000 && size.height >= 2000;
}
return NO;
}
// Stops at hidden/transparent views, so everything reached has visible ancestors.
static void LSRCollectWallpaperViews(UIView *view, NSString *windowName, CFTimeInterval t, NSMutableDictionary *seen) {
if (view.hidden || view.alpha < 0.01) return;
if (LSRLooksLikeWallpaper(view)) {
NSString *key = [NSString stringWithFormat:@"%@ | %@ %p", windowName, NSStringFromClass([view class]), view];
NSMutableDictionary *entry = seen[key];
CGRect frame = [view convertRect:view.bounds toView:nil];
if (!entry) {
entry = [@{ @"first": @(t), @"count": @0, @"frames": [NSMutableSet new],
@"window": @(view.window.windowLevel) } mutableCopy];
seen[key] = entry;
}
entry[@"last"] = @(t);
entry[@"count"] = @([entry[@"count"] integerValue] + 1);
[entry[@"frames"] addObject:NSStringFromCGRect(frame)];
}
for (UIView *sub in view.subviews) LSRCollectWallpaperViews(sub, windowName, t, seen);
}
static void LSRRunBurst(void) {
NSMutableDictionary *seen = [NSMutableDictionary new];
CFTimeInterval start = CACurrentMediaTime();
__block NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 repeats:YES block:^(NSTimer *t) {
CFTimeInterval now = CACurrentMediaTime() - start;
for (UIWindow *window in [UIWindow allWindowsIncludingInternalWindows:YES onlyVisibleWindows:NO]) {
if (window.hidden) continue;
LSRCollectWallpaperViews(window, NSStringFromClass([window class]), now, seen);
}
if (now < 120.0) return;
[t invalidate];
NSMutableString *out = [NSMutableString new];
for (NSString *key in [seen.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
NSDictionary *e = seen[key];
[out appendFormat:@"%@\n seen %@x, %.1fs..%.1fs, windowLevel %@, frames: %@\n", key, e[@"count"],
[e[@"first"] doubleValue], [e[@"last"] doubleValue], e[@"window"],
[[e[@"frames"] allObjects] componentsJoinedByString:@" "]];
}
[out writeToFile:LSRDebugPath(@"LockScreenRestoreBurst-now.log") atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}];
(void)timer;
}
// Snapshot of every visible window -> LockScreenRestoreSnap-<n>.png (on a dark gray backdrop,
// since the player's window itself is transparent).
static void LSRSnapWindows(void) {
NSUInteger index = 0;
for (UIWindow *window in [UIWindow allWindowsIncludingInternalWindows:YES onlyVisibleWindows:NO]) {
if (window.hidden || window.bounds.size.width < 1) continue;
UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:window.bounds format:format];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {
[[UIColor colorWithWhite:0.25 alpha:1] setFill];
UIRectFill(window.bounds);
[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
}];
NSString *name = [NSString stringWithFormat:@"LockScreenRestoreSnap-%lu.png", (unsigned long)index++];
[UIImagePNGRepresentation(image) writeToFile:LSRDebugPath(name) atomically:YES];
}
}
// Backdrop layers: the wallpaper window's whole layer tree, and every backdrop layer elsewhere
// with its group name -> LockScreenRestoreBackdrops-now.log
static void LSRDumpLayerTree(CALayer *layer, NSUInteger depth, BOOL everything, NSMutableString *out) {
BOOL backdrop = [layer isKindOfClass:NSClassFromString(@"CABackdropLayer")];
if (everything || backdrop) {
NSMutableString *line = [NSMutableString string];
for (NSUInteger i = 0; i < (everything ? depth : 1); i++) [line appendString:@" "];
[line appendFormat:@"%@ view=%@ frame=%@ hidden=%d opacity=%.2f", NSStringFromClass([layer class]),
layer.delegate ? NSStringFromClass([(id)layer.delegate class]) : @"-", NSStringFromCGRect(layer.frame),
layer.hidden, layer.opacity];
if (backdrop) {
[line appendFormat:@" GROUP=%@ namespace=%@ captureOnly=%@ scale=%@ enabled=%@", [layer valueForKey:@"groupName"],
[layer valueForKey:@"groupNamespace"], [layer valueForKey:@"captureOnly"], [layer valueForKey:@"scale"],
[layer valueForKey:@"enabled"]];
if (!everything) {
NSMutableArray *path = [NSMutableArray new];
for (CALayer *up = layer.superlayer; up; up = up.superlayer) {
if (up.delegate) [path addObject:NSStringFromClass([(id)up.delegate class])];
}
[line appendFormat:@" < %@", [path componentsJoinedByString:@" < "]];
}
}
[out appendFormat:@"%@\n", line];
}
for (CALayer *sub in layer.sublayers) LSRDumpLayerTree(sub, depth + 1, everything, out);
}
static void LSRDumpBackdrops(void) {
NSMutableString *out = [NSMutableString string];
for (UIWindow *window in [UIWindow allWindowsIncludingInternalWindows:YES onlyVisibleWindows:NO]) {
BOOL wallpaper = [NSStringFromClass([window class]) containsString:@"Wallpaper"];
[out appendFormat:@"##### WINDOW %@ level=%.0f hidden=%d bounds=%@\n", NSStringFromClass([window class]),
window.windowLevel, window.hidden, NSStringFromCGRect(window.bounds)];
LSRDumpLayerTree(window.layer, 0, wallpaper, out);
}
[out writeToFile:LSRDebugPath(@"LockScreenRestoreBackdrops-now.log") atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
__attribute__((constructor)) static void LSRInstallDebugTools(void) {
[@"" writeToFile:LSRDebugPath(@"lsr-debug-here") atomically:YES encoding:NSUTF8StringEncoding error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
[NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer *timer) {
NSFileManager *fm = [NSFileManager defaultManager];
NSString *dumpRequest = LSRDebugPath(@"lsr-dump-request");
if ([fm fileExistsAtPath:dumpRequest]) {
[fm removeItemAtPath:dumpRequest error:nil];
LSRDumpAllWindows();
}
NSString *reconRequest = LSRDebugPath(@"lsr-recon-request");
if ([fm fileExistsAtPath:reconRequest]) {
NSString *body = [NSString stringWithContentsOfFile:reconRequest encoding:NSUTF8StringEncoding error:nil];
[fm removeItemAtPath:reconRequest error:nil];
NSMutableArray *fragments = [NSMutableArray new];
for (NSString *line in [body componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
NSString *trimmed = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (trimmed.length) [fragments addObject:trimmed];
}
if (fragments.count) LSRRunRecon(fragments);
}
NSString *backdropsRequest = LSRDebugPath(@"lsr-backdrops-request");
if ([fm fileExistsAtPath:backdropsRequest]) {
[fm removeItemAtPath:backdropsRequest error:nil];
LSRDumpBackdrops();
}
NSString *snapRequest = LSRDebugPath(@"lsr-snap-request");
if ([fm fileExistsAtPath:snapRequest]) {
[fm removeItemAtPath:snapRequest error:nil];
LSRSnapWindows();
}
NSString *burstRequest = LSRDebugPath(@"lsr-burst-request");
if ([fm fileExistsAtPath:burstRequest]) {
[fm removeItemAtPath:burstRequest error:nil];
LSRRunBurst();
}
NSString *callRequest = LSRDebugPath(@"lsr-call-request");
if ([fm fileExistsAtPath:callRequest]) {
NSString *body = [NSString stringWithContentsOfFile:callRequest encoding:NSUTF8StringEncoding error:nil];
[fm removeItemAtPath:callRequest error:nil];
LSRRunCalls(body);
}
}];
});
}
#endif