// Loaded only into companionfindlocallyd, the daemon that plays the sound when an Apple Watch pings this iPhone. SpringBoard // never hears about a ping, so this tells the island. Foundation only, and it must stay that small: a daemon has no UIKit. #import #import #import #import "common.h" #define PING_NOTIFICATION "com.astar76.islet.ping" #define MAX_HOOKS 12 static struct { Method method; IMP orig; } gHooks[MAX_HOOKS]; static int gHookCount, gHooksToken, gFiredToken; static uint64_t gFired; // The handlers take one pointer-sized argument or none, so passing two registers through suits all of them. static void *ping_hook(id self, SEL _cmd, void *a, void *b) { notify_set_state(gFiredToken, ++gFired); notify_post(PING_NOTIFICATION); Method m = class_getInstanceMethod(object_getClass(self), _cmd); for (int i = 0; i < gHookCount; i++) if (gHooks[i].method == m) return ((void *(*)(id, SEL, void *, void *))gHooks[i].orig)(self, _cmd, a, b); return NULL; } static void HookClass(Class cls) { static const char *wanted[] = {"playSound:", "playSoundAndFlash:", "playFindLocallySound", "playNearbySound", "flashLights"}; unsigned n = 0; Method *list = class_copyMethodList(cls, &n); for (unsigned i = 0; i < n && gHookCount < MAX_HOOKS; i++) for (int w = 0; w < 5; w++) { if (strcmp(sel_getName(method_getName(list[i])), wanted[w])) continue; gHooks[gHookCount].method = list[i]; gHooks[gHookCount].orig = method_setImplementation(list[i], (IMP)ping_hook); gHookCount++; } free(list); } // Every class of this executable, found by path: at load time the image index isn't reliably the main program. The count // goes out over notify state, 1 meaning loaded and each hook adding one, so `isletctl dump` can show what happened in here. __attribute__((constructor)) static void islet_ping_init(void) { notify_register_check("com.astar76.islet.ping.hooks", &gHooksToken); notify_register_check("com.astar76.islet.ping.fired", &gFiredToken); notify_set_state(gHooksToken, 1); char path[1024]; uint32_t size = sizeof(path); if (_NSGetExecutablePath(path, &size)) return; unsigned count = 0; const char **names = objc_copyClassNamesForImage(path, &count); for (unsigned c = 0; names && c < count; c++) { Class cls = objc_getClass(names[c]); if (cls) HookClass(cls); } free(names); notify_set_state(gHooksToken, 1 + gHookCount); }