Skip to content

Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.

C

chore: FLEX builds keep a crash's stack, the driver reads and writes key paths and prints layer trees, and the tree dump shows opaque paint (#141)

My-Name-Is-Jeffae538ffcd13f
diff --git a/docs/tweaks.md b/docs/tweaks.md
index c7d0298f..677f52d9 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -778,6 +778,8 @@ leaves it running:
scripts/phone.py settings.open | settings.page "Appearance"
scripts/phone.py wait --id X [--gone 1] | --menu 1 | --log "system menu: the player's menu is up" [--timeout 3]
scripts/phone.py screenshot out.png
+ scripts/phone.py layers --id sheet-view [--depth 6] [--up 1]
+ scripts/phone.py get | set --id sheet-view --path layer.sublayers.0.enabled [--value false]
Views are addressed as the tree prints them: `id=` is the accessibility identifier, `a11y=` the accessibility
label, the quoted text a label's, and a class with an index counts that class's views in the tree's order.
@@ -786,7 +788,10 @@ way: a UITouch and the IOHIDEvent gesture recognizers read, through `-[UIApplica
controls get their control events, recognizers recognize, and a button whose menu is its primary action opens
it on the touch down. `menu.pick` taps a row of the system's menu, not of Spotify's own sheet (tap that by
`--text`). `log` reads the app's last 2000 `SGLog` lines from memory, so no device log capture is needed;
-a log wait looks from the start of the last command that did something. Everything runs on the main thread
+a log wait looks from the start of the last command that did something. `get` and `set` read and write a
+property by key path from the view named (or the key window), a number indexing an array, so a guess about what
+draws something is tried live; `layers` prints the layer tree with what changes how it draws (opacity, masks,
+filters, a backdrop's own keys). Everything runs on the main thread
through `dispatch_async` and a semaphore with a timeout, waited on from the server's thread only. Checked in
the simulator by harness/driver/.
diff --git a/scripts/phone.py b/scripts/phone.py
index fcada6bf..897595b7 100755
--- a/scripts/phone.py
+++ b/scripts/phone.py
@@ -27,6 +27,9 @@
scripts/phone.py wait --log "system menu: the player's menu is up" --timeout 3
scripts/phone.py log [--since N] # the app's last SGLog lines; each has a seq
scripts/phone.py screenshot out.png [--scale 1]
+ scripts/phone.py layers --id sheet-view [--depth 6] [--up 1] # a view's layer tree, or its layers up to the window
+ scripts/phone.py get --id sheet-view --path layer.sublayers.0.opacity # a property by key path (numbers index arrays)
+ scripts/phone.py set --id sheet-view --path backgroundColor --value '#FF000080' # nil, true, false, a number, a colour, text
Every command prints the app's JSON answer, {"ok": true, ...} or {"ok": false, "error": ...}, and exits 1
when it is not ok. --label and --text match whole and ignore case; --contains 1 matches a part. Points are
diff --git a/tweak/Sources/Diagnostics/Diagnostics.x b/tweak/Sources/Diagnostics/Diagnostics.x
index eca64516..d1742b3c 100644
--- a/tweak/Sources/Diagnostics/Diagnostics.x
+++ b/tweak/Sources/Diagnostics/Diagnostics.x
@@ -30,6 +30,30 @@ static void appendTree(UIView *view, NSUInteger depth, NSMutableString *out) {
if (view.hidden) [line appendString:@" hidden"];
if (view.layer.mask) [line appendString:@" masked"];
if (view.clipsToBounds) [line appendString:@" clips"];
+ // What draws black without a background colour: an opaque layer with no fill, a layer's own opacity, filters and
+ // a picture in the layer itself, and sublayers that are not views (their fill, their picture, a gradient). Not
+ // view.opaque, which is YES on nearly every view.
+ if (view.layer.opaque) [line appendString:@" opaque"];
+ if (view.layer.opacity < 1) [line appendFormat:@" op=%.2f", view.layer.opacity];
+ if (view.layer.filters.count) [line appendFormat:@" filters=%lu", (unsigned long)view.layer.filters.count];
+ if (view.layer.compositingFilter) [line appendFormat:@" comp=%@", view.layer.compositingFilter];
+ if (view.layer.contents && ![view isKindOfClass:UIImageView.class]) [line appendString:@" contents"];
+ if (view.layer.shouldRasterize) [line appendString:@" raster"];
+ if (![NSStringFromClass(view.layer.class) isEqualToString:@"CALayer"]) [line appendFormat:@" layer=%@", NSStringFromClass(view.layer.class)];
+ NSMutableArray<NSString *> *loose = [NSMutableArray array];
+ NSSet<CALayer *> *viewLayers = [NSSet setWithArray:[view.subviews valueForKey:@"layer"]];
+ for (CALayer *sub in view.layer.sublayers) {
+ if ([viewLayers containsObject:sub]) continue;
+ NSMutableString *desc = [NSMutableString stringWithString:NSStringFromClass(sub.class)];
+ if (sub.backgroundColor && CGColorGetAlpha(sub.backgroundColor) > 0) [desc appendFormat:@" bg=%@", hexColor(sub.backgroundColor)];
+ if (sub.contents) [desc appendString:@" contents"];
+ if ([sub isKindOfClass:CAGradientLayer.class] && ((CAGradientLayer *)sub).colors.count) [desc appendString:@" gradient"];
+ if (sub.hidden) [desc appendString:@" hidden"];
+ if (sub.opacity < 1) [desc appendFormat:@" op=%.2f", sub.opacity];
+ [desc appendFormat:@" %@", NSStringFromCGRect(sub.frame)];
+ [loose addObject:desc];
+ }
+ if (loose.count) [line appendFormat:@" sublayers=[%@]", [loose componentsJoinedByString:@"; "]];
if (view.accessibilityIdentifier.length) [line appendFormat:@" id=%@", view.accessibilityIdentifier];
// Controls and accessibility elements, the views the phone driver's `tap --label` finds.
if (([view isKindOfClass:UIControl.class] || (view.isAccessibilityElement && ![view isKindOfClass:UILabel.class])) && view.accessibilityLabel.length) {
diff --git a/tweak/Sources/Diagnostics/Driver.m b/tweak/Sources/Diagnostics/Driver.m
index 8c0a86a3..16035278 100644
--- a/tweak/Sources/Diagnostics/Driver.m
+++ b/tweak/Sources/Diagnostics/Driver.m
@@ -597,6 +597,139 @@ static CGPoint clampedOffset(UIScrollView *scroll, CGPoint offset) {
#pragma mark - commands
+#pragma mark - properties by key path (get, set, layers)
+
+// A view or layer's properties read and written live, so a guess about what draws something can be tried on the
+// phone without a build: `set --id sheet-view --path layer.sublayers.0.enabled --value false`.
+
+static NSString *driverHex(CGColorRef color) {
+ if (!color) return @"nil";
+ static CGColorSpaceRef srgb;
+ if (!srgb) srgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ CGColorRef rgb = CGColorCreateCopyByMatchingToColorSpace(srgb, kCGRenderingIntentDefault, color, NULL);
+ if (!rgb) return @"?";
+ const CGFloat *c = CGColorGetComponents(rgb);
+ NSString *hex = [NSString stringWithFormat:@"#%02X%02X%02X@%.2f", (int)lround(c[0] * 255), (int)lround(c[1] * 255), (int)lround(c[2] * 255), CGColorGetAlpha(rgb)];
+ CGColorRelease(rgb);
+ return hex;
+}
+
+// What a value reads as in the answer: numbers and strings as they are, colours as hex, anything else its description.
+static id plainValue(id value) {
+ if (!value || value == NSNull.null) return [NSNull null];
+ if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) return value;
+ if ([value isKindOfClass:UIColor.class]) return driverHex(((UIColor *)value).CGColor);
+ if (CFGetTypeID((__bridge CFTypeRef)value) == CGColorGetTypeID()) return driverHex((__bridge CGColorRef)value);
+ if ([value isKindOfClass:NSArray.class]) {
+ NSMutableArray *items = [NSMutableArray array];
+ for (id item in (NSArray *)value) [items addObject:[item isKindOfClass:NSNumber.class] || [item isKindOfClass:NSString.class] ? item : NSStringFromClass([item class])];
+ return items;
+ }
+ NSString *text = [value description];
+ return text.length > 300 ? [text substringToIndex:300] : text;
+}
+
+// One step of a path: a number indexes an array (subviews, sublayers, filters), anything else is a key.
+static id stepInto(id object, NSString *step) {
+ NSScanner *scanner = [NSScanner scannerWithString:step];
+ NSInteger index;
+ if ([object isKindOfClass:NSArray.class] && [scanner scanInteger:&index] && scanner.isAtEnd) {
+ NSArray *array = object;
+ if (index < 0 || index >= (NSInteger)array.count) fail(@"index %ld is past the %lu items", (long)index, (unsigned long)array.count);
+ return array[(NSUInteger)index];
+ }
+ @try {
+ return [object valueForKey:step];
+ } @catch (NSException *e) {
+ fail(@"%@ has no key %@", NSStringFromClass([object class]), step);
+ }
+}
+
+static id walk(id object, NSArray<NSString *> *steps) {
+ for (NSString *step in steps) {
+ object = stepInto(object, step);
+ if (!object) fail(@"%@ is nil", step);
+ }
+ return object;
+}
+
+// A value typed on the Mac: nil, true/false, a number, a colour (#RRGGBB or #RRGGBBAA, a CGColor for a layer's key and
+// a UIColor for a view's), or else the string.
+static id typedValue(NSString *text, id target) {
+ if (!text || [text isEqualToString:@"nil"] || [text isEqualToString:@"null"]) return nil;
+ if ([text isEqualToString:@"true"] || [text isEqualToString:@"YES"]) return @YES;
+ if ([text isEqualToString:@"false"] || [text isEqualToString:@"NO"]) return @NO;
+ if ([text hasPrefix:@"#"] && (text.length == 7 || text.length == 9)) {
+ unsigned long long rgba = 0;
+ [[NSScanner scannerWithString:[text substringFromIndex:1]] scanHexLongLong:&rgba];
+ if (text.length == 7) rgba = (rgba << 8) | 0xFF;
+ UIColor *color = [UIColor colorWithRed:((rgba >> 24) & 0xFF) / 255.0 green:((rgba >> 16) & 0xFF) / 255.0 blue:((rgba >> 8) & 0xFF) / 255.0 alpha:(rgba & 0xFF) / 255.0];
+ return [target isKindOfClass:CALayer.class] ? (id)color.CGColor : color;
+ }
+ NSScanner *scanner = [NSScanner scannerWithString:text];
+ double number;
+ if ([scanner scanDouble:&number] && scanner.isAtEnd) return @(number);
+ return text;
+}
+
+static NSArray<NSString *> *pathSteps(NSDictionary *p) {
+ NSString *path = p[@"path"];
+ if (!path.length) fail(@"takes --path, keys and indexes joined by dots (layer.sublayers.0.opacity)");
+ return [path componentsSeparatedByString:@"."];
+}
+
+// The object a path starts from: the view the selector names, or the key window.
+static id pathRoot(NSDictionary *p) {
+ return hasSelector(p) ? require(p, nil) : keyWindow();
+}
+
+// A layer's line: its class, frame, and whatever about it changes how it and what is under it draw.
+static NSString *layerLine(CALayer *layer) {
+ NSMutableString *line = [NSMutableString stringWithString:NSStringFromClass(layer.class)];
+ if ([layer.delegate isKindOfClass:UIView.class]) [line appendFormat:@" (%@)", NSStringFromClass([(id)layer.delegate class])];
+ if (layer.name.length) [line appendFormat:@" name=%@", layer.name];
+ [line appendFormat:@" %@", NSStringFromCGRect(layer.frame)];
+ if (layer.hidden) [line appendString:@" hidden"];
+ if (layer.opacity < 1) [line appendFormat:@" op=%.2f", layer.opacity];
+ if (layer.opaque) [line appendString:@" opaque"];
+ if (layer.masksToBounds) [line appendString:@" clips"];
+ if (layer.cornerRadius > 0) [line appendFormat:@" r=%.1f", layer.cornerRadius];
+ if (layer.backgroundColor && CGColorGetAlpha(layer.backgroundColor) > 0) [line appendFormat:@" bg=%@", driverHex(layer.backgroundColor)];
+ if (layer.contents) [line appendString:@" contents"];
+ if (layer.mask) [line appendFormat:@" mask=%@", NSStringFromClass(layer.mask.class)];
+ if (layer.shouldRasterize) [line appendString:@" rasterized"];
+ if (!layer.allowsGroupOpacity) [line appendString:@" noGroupOpacity"];
+ if (layer.compositingFilter) [line appendFormat:@" compositing=%@", layer.compositingFilter];
+ if (!CATransform3DIsIdentity(layer.transform)) [line appendString:@" transformed"];
+ if (layer.filters.count) {
+ NSMutableArray *names = [NSMutableArray array];
+ for (id filter in layer.filters) {
+ id name = nil;
+ @try { name = [filter valueForKey:@"type"]; } @catch (__unused NSException *e) {}
+ [names addObject:name ?: NSStringFromClass([filter class])];
+ }
+ [line appendFormat:@" filters=%@", [names componentsJoinedByString:@","]];
+ }
+ if ([NSStringFromClass(layer.class) containsString:@"Backdrop"]) {
+ for (NSString *key in @[@"enabled", @"scale", @"groupName", @"captureOnly", @"windowServerAware", @"allowsInPlaceFiltering", @"marginWidth", @"zoom", @"ignoresScreenClip", @"disablesOccludedBackdropBlurs", @"reducesCaptureBitDepth"]) {
+ id value = nil;
+ @try { value = [layer valueForKey:key]; } @catch (__unused NSException *e) { continue; }
+ [line appendFormat:@" %@=%@", key, plainValue(value)];
+ }
+ id mesh = nil;
+ @try { mesh = [layer valueForKey:@"meshTransform"]; } @catch (__unused NSException *e) {}
+ if (mesh) [line appendString:@" mesh"];
+ }
+ return line;
+}
+
+static void dumpLayers(CALayer *layer, NSUInteger depth, NSUInteger maxDepth, NSMutableArray<NSString *> *lines) {
+ if (lines.count > 600) return;
+ [lines addObject:[[@"" stringByPaddingToLength:depth * 2 withString:@" " startingAtIndex:0] stringByAppendingString:layerLine(layer)]];
+ if (depth >= maxDepth) return;
+ for (CALayer *sub in layer.sublayers) dumpLayers(sub, depth + 1, maxDepth, lines);
+}
+
typedef NSDictionary *(^SGCommand)(NSDictionary *p);
// The log number when the last command that does something began: a log wait looks from there, so
@@ -937,13 +1070,59 @@ static NSDictionary<NSString *, SGCommand> *commands(void) {
});
return touchAt(where, 0.08);
},
+ @"get" : ^NSDictionary *(NSDictionary *p) {
+ NSArray<NSString *> *steps = pathSteps(p);
+ return onMain(^id {
+ id value = walk(pathRoot(p), steps);
+ return @{@"path" : p[@"path"], @"value" : plainValue(value), @"class" : NSStringFromClass([value class]) ?: @"nil"};
+ });
+ },
+ @"set" : ^NSDictionary *(NSDictionary *p) {
+ NSArray<NSString *> *steps = pathSteps(p);
+ if (!p[@"value"]) fail(@"set takes --value (nil, true, false, a number, #RRGGBB[AA] or text)");
+ return onMain(^id {
+ id target = walk(pathRoot(p), [steps subarrayWithRange:NSMakeRange(0, steps.count - 1)]);
+ NSString *key = steps.lastObject;
+ id before = nil;
+ @try { before = [target valueForKey:key]; } @catch (__unused NSException *e) {}
+ id value = typedValue(p[@"value"], target);
+ @try {
+ [CATransaction begin];
+ [CATransaction setDisableActions:YES];
+ [target setValue:value forKey:key];
+ [CATransaction commit];
+ } @catch (NSException *e) {
+ [CATransaction commit];
+ fail(@"%@ did not take %@: %@", NSStringFromClass([target class]), key, e.reason);
+ }
+ id after = nil;
+ @try { after = [target valueForKey:key]; } @catch (__unused NSException *e) {}
+ return @{@"on" : NSStringFromClass([target class]), @"key" : key, @"before" : plainValue(before), @"after" : plainValue(after)};
+ });
+ },
+ // The layer tree under a view (--depth, 6 by default), or with --up 1 the chain of layers from it to the window.
+ @"layers" : ^NSDictionary *(NSDictionary *p) {
+ return onMain(^id {
+ id root = pathRoot(p);
+ if (p[@"path"]) root = walk(root, pathSteps(p));
+ CALayer *layer = [root isKindOfClass:UIView.class] ? ((UIView *)root).layer : root;
+ if (![layer isKindOfClass:CALayer.class]) fail(@"not a view or layer: %@", NSStringFromClass([root class]));
+ NSMutableArray<NSString *> *lines = [NSMutableArray array];
+ if ([p[@"up"] boolValue]) {
+ for (CALayer *l = layer; l; l = l.superlayer) [lines addObject:layerLine(l)];
+ } else {
+ dumpLayers(layer, 0, (NSUInteger)number(p, @"depth", 6), lines);
+ }
+ return @{@"layers" : lines};
+ });
+ },
};
});
return all;
}
static NSSet<NSString *> *readOnly(void) {
- return [NSSet setWithArray:@[@"find", @"state", @"screenshot", @"log", @"wait"]];
+ return [NSSet setWithArray:@[@"find", @"state", @"screenshot", @"log", @"wait", @"get", @"layers"]];
}
BOOL SGDriverHandles(NSString *command) {
diff --git a/tweak/Sources/Diagnostics/SGCrashTrace.m b/tweak/Sources/Diagnostics/SGCrashTrace.m
new file mode 100644
index 00000000..8e6f7b3e
--- /dev/null
+++ b/tweak/Sources/Diagnostics/SGCrashTrace.m
@@ -0,0 +1,213 @@
+// A crash's stack for FLEX builds, where iOS writes none: on a jailbroken iPhone 11 the kernel answered every crash
+// with "Corpse failure, too many 6" and no report reached the phone (2026-10-23). On SIGSEGV, SIGBUS, SIGILL, SIGTRAP
+// and SIGABRT the faulting thread's frames are walked from its registers by their frame pointers and written to a file
+// in Caches, each as image + offset; the next launch logs the file and removes it. The handler runs on a stack of its
+// own for the main thread, so a stack overflow (a recursion) is caught too, and hands the signal on to the handler
+// that was there before it or to the default. Spotify's Crashlytics, set up after it, keeps it and calls it in turn.
+//
+// Threading: installed on the main thread. The handler only writes to a descriptor and reads tables filled before
+// it runs (the images, the main thread's stack), as nothing that takes a lock may run in it.
+#import <Foundation/Foundation.h>
+#import <dlfcn.h>
+#import <fcntl.h>
+#import <signal.h>
+#import <unistd.h>
+#import <sys/ucontext.h>
+#import <mach/mach.h>
+#import <mach-o/dyld.h>
+#import <mach-o/getsect.h>
+#import <pthread.h>
+#import <stdatomic.h>
+#if __has_feature(ptrauth_calls)
+#import <ptrauth.h>
+#endif
+#import "Core/SGCore.h"
+
+#if SG_DRIVER
+
+static char sg_path[1024];
+static const int kSignals[] = {SIGSEGV, SIGBUS, SIGILL, SIGTRAP, SIGABRT};
+enum { kSignalCount = sizeof kSignals / sizeof *kSignals, kMaxFrames = 96 };
+static struct sigaction sg_previous[kSignalCount];
+
+// Every image's code as dyld reports it loading, for the handler: dladdr takes dyld's lock, which the crashed thread
+// may hold. The name is copied, so an image closed since leaves nothing freed behind.
+typedef struct {
+ uintptr_t base, start, end;
+ char name[64];
+} Image;
+enum { kMaxImages = 2048 };
+static Image sg_images[kMaxImages];
+static atomic_int sg_imageCount;
+
+static void addImage(const struct mach_header *header, intptr_t slide) {
+ int count = atomic_load(&sg_imageCount);
+ Dl_info info;
+ unsigned long size = 0;
+ uint8_t *text = getsegmentdata((const struct mach_header_64 *)header, SEG_TEXT, &size);
+ if (count >= kMaxImages || !text || !dladdr(header, &info) || !info.dli_fname) return;
+ const char *slash = info.dli_fname;
+ for (const char *c = info.dli_fname; *c; c++) if (*c == '/') slash = c + 1;
+ sg_images[count] = (Image){(uintptr_t)header, (uintptr_t)text, (uintptr_t)text + size, {0}};
+ strlcpy(sg_images[count].name, slash, sizeof sg_images[count].name);
+ atomic_store(&sg_imageCount, count + 1);
+}
+
+// The main thread's stack, read when the handler is installed, so a frame pointer is followed only inside its stack.
+static pthread_t sg_mainThread;
+static uintptr_t sg_mainBottom, sg_mainTop;
+
+static void put(int fd, const char *text) {
+ size_t length = 0;
+ while (text[length]) length++;
+ if (length) (void)write(fd, text, length);
+}
+
+static void putHex(int fd, uintptr_t value) {
+ char digits[19] = "0x";
+ int n = 0;
+ char reversed[16];
+ do {
+ reversed[n++] = "0123456789abcdef"[value & 15];
+ value >>= 4;
+ } while (value && n < 16);
+ for (int i = 0; i < n; i++) digits[2 + i] = reversed[n - 1 - i];
+ digits[2 + n] = 0;
+ put(fd, digits);
+}
+
+static uintptr_t strip(uintptr_t address) {
+#if __has_feature(ptrauth_calls)
+ return (uintptr_t)ptrauth_strip((void *)address, ptrauth_key_return_address);
+#else
+ return address;
+#endif
+}
+
+static void putFrame(int fd, uintptr_t address) {
+ put(fd, " ");
+ putHex(fd, address);
+ int count = atomic_load(&sg_imageCount);
+ for (int i = 0; i < count; i++) {
+ if (address < sg_images[i].start || address >= sg_images[i].end) continue;
+ put(fd, " ");
+ put(fd, sg_images[i].name);
+ put(fd, " +");
+ putHex(fd, address - sg_images[i].base);
+ break;
+ }
+ put(fd, "\n");
+}
+
+static volatile sig_atomic_t sg_inHandler;
+
+static void writeTrace(siginfo_t *info, void *context, int signal) {
+ int fd = open(sg_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+ if (fd < 0) return;
+ put(fd, "signal ");
+ putHex(fd, (uintptr_t)signal);
+ put(fd, " at ");
+ putHex(fd, (uintptr_t)(info ? info->si_addr : 0));
+ put(fd, "\n");
+ ucontext_t *uc = context;
+ if (uc && uc->uc_mcontext) {
+ uintptr_t pc = strip((uintptr_t)arm_thread_state64_get_pc(uc->uc_mcontext->__ss));
+ uintptr_t lr = strip((uintptr_t)arm_thread_state64_get_lr(uc->uc_mcontext->__ss));
+ uintptr_t fp = (uintptr_t)arm_thread_state64_get_fp(uc->uc_mcontext->__ss);
+ // A frame is followed only inside the crashed thread's stack: a frame pointer out of it faults again. The
+ // main thread's was read at install; another thread's is read from its pthread, a field read with no lock.
+ pthread_t self = pthread_self();
+ BOOL onMain = pthread_equal(self, sg_mainThread);
+ uintptr_t top = onMain ? sg_mainTop : (uintptr_t)pthread_get_stackaddr_np(self);
+ uintptr_t bottom = onMain ? sg_mainBottom : top - pthread_get_stacksize_np(self);
+ #define SG_IN_STACK(p) ((p) >= bottom && (p) + 16 <= top && !((p) & 7))
+ putFrame(fd, pc);
+ // lr is the caller only in a function that has not saved it in a frame yet; otherwise the walk prints it.
+ if (!SG_IN_STACK(fp) || lr != strip(((uintptr_t *)fp)[1])) putFrame(fd, lr);
+ // A recursion repeats one frame thousands of times: the first kMaxFrames say which.
+ for (int i = 0; i < kMaxFrames && SG_IN_STACK(fp); i++) {
+ uintptr_t *frame = (uintptr_t *)fp;
+ uintptr_t next = frame[0], ret = strip(frame[1]);
+ if (!ret) break;
+ putFrame(fd, ret);
+ if (next <= fp) break;
+ fp = next;
+ }
+ #undef SG_IN_STACK
+ }
+ close(fd);
+}
+
+static void handler(int signal, siginfo_t *info, void *context) {
+ // Handed back to by a handler this one handed on to, or a fault in this one: end it here.
+ if (sg_inHandler) {
+ struct sigaction fallback = {0};
+ fallback.sa_handler = SIG_DFL;
+ sigaction(signal, &fallback, NULL);
+ raise(signal);
+ return;
+ }
+ sg_inHandler = 1;
+ writeTrace(info, context, signal);
+ // The handler that was there before, or the default, which ends the process with this signal.
+ for (int i = 0; i < kSignalCount; i++) {
+ if (kSignals[i] != signal) continue;
+ struct sigaction previous = sg_previous[i];
+ if ((previous.sa_flags & SA_SIGINFO) && previous.sa_sigaction) {
+ sigaction(signal, &previous, NULL);
+ previous.sa_sigaction(signal, info, context);
+ return;
+ }
+ if (previous.sa_handler != SIG_DFL && previous.sa_handler != SIG_IGN && previous.sa_handler) {
+ sigaction(signal, &previous, NULL);
+ previous.sa_handler(signal);
+ return;
+ }
+ }
+ struct sigaction fallback = {0};
+ fallback.sa_handler = SIG_DFL;
+ sigaction(signal, &fallback, NULL);
+ raise(signal);
+}
+
+static void logLastCrash(NSString *path) {
+ NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
+ if (!text.length) return;
+ [NSFileManager.defaultManager removeItemAtPath:path error:nil];
+ SGLog(@"crash trace: the last launch ended on a signal");
+ for (NSString *line in [text componentsSeparatedByString:@"\n"]) {
+ if (line.length) SGLog(@"crash trace: %@", line);
+ }
+}
+
+static void install(void) {
+ static void *altStack;
+ altStack = malloc(SIGSTKSZ * 4);
+ stack_t stack = {.ss_sp = altStack, .ss_size = SIGSTKSZ * 4, .ss_flags = 0};
+ sigaltstack(&stack, NULL);
+ sg_mainThread = pthread_self();
+ sg_mainTop = (uintptr_t)pthread_get_stackaddr_np(sg_mainThread);
+ sg_mainBottom = sg_mainTop - pthread_get_stacksize_np(sg_mainThread);
+ // Called for every image already loaded, then for each one loaded later.
+ _dyld_register_func_for_add_image(addImage);
+ struct sigaction action = {0};
+ action.sa_sigaction = handler;
+ action.sa_flags = SA_SIGINFO | SA_ONSTACK;
+ sigemptyset(&action.sa_mask);
+ for (int i = 0; i < kSignalCount; i++) sigaction(kSignals[i], &action, &sg_previous[i]);
+}
+
+__attribute__((constructor)) static void SGCrashTraceInit(void) {
+ NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
+ NSString *path = [caches stringByAppendingPathComponent:@"sg-crash.txt"];
+ if (!path || path.length >= sizeof sg_path) return;
+ strlcpy(sg_path, path.fileSystemRepresentation, sizeof sg_path);
+ logLastCrash(path);
+ // Before Spotify sets up Crashlytics, which keeps the handlers it finds, puts them back on a crash and calls them.
+ // Installed after it, ours is reset to the default by its Mach exception handler before the signal comes (likely
+ // why a crash on the phone left no trace, 2026-10-24).
+ install();
+ SGLog(@"crash trace: watching for a crash");
+}
+
+#endif