Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

HackiOS pane in Settings, behind HACKIOS_PANE=1, added the way tweaks add theirs

vcvkkc56051d057b0
diff --git a/.gitignore b/.gitignore
index f349cc9..210f09a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,6 +44,7 @@ __pycache__/
!/userland/rc.*
!/userland/com.redwood.*.plist
!/userland/src/
+!/userland/hackios/
!/userland/libmini/
!/userland/var/
diff --git a/README.md b/README.md
index 83412d6..e598a4c 100644
--- a/README.md
+++ b/README.md
@@ -97,6 +97,16 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 ми
преобразование в ядре (`iokit/Kernel/MiniAppleKeyStore.cpp`), и всё записанное лежит в `/private/var`, то есть в
памяти, и пропадает при следующем старте. Проверка: `/redwood/bin/keychain_test` (подписывается `ldid`
с группой доступа к связке; без `ldid` связка такой программе отказывает).
+- **Панель HackiOS в Настройках (опытно): `HACKIOS_PANE=1 userland/build.sh`.** В главном списке Настроек
+ появляется пункт «HackiOS» — своей группой ниже настроек Apple, там же, где их ставят твики (так делает
+ PreferenceLoader). За ним панель только для чтения: сборка (коммит и дата), ядро, параметры загрузки (без адреса
+ радио), время работы, память, процессоры и их частота, GPU, Wi-Fi (имя сети — только если его показывают и сами
+ Настройки — и уровень сигнала), батарея (с `battery=1`), драйвер кнопок; и одна кнопка, «Return to the Loader»,
+ с подтверждением — то же, что пять пальцев на экране. Устроено как у твиков: запись
+ `userland/hackios/HackiOS.plist` ложится в `/redwood/Library/PreferenceLoader/Preferences/`, бандл панели — в
+ `/redwood/Library/PreferenceBundles/HackiOS.bundle`, а подхватывает их наша вставка в Настройки
+ (`userland/src/inject_prefs.m`, без Substrate). Новая строка панели — элемент в `userland/hackios/Root.plist` и
+ источник в `userland/src/hackios_pane.m`.
- **Wi-Fi телефона (опытно): `wifi=1`.** Радио телефона подключается к одной сети WPA2 с паролем, и iOS выходит
через него в интернет: адрес по DHCP, DNS, HTTPS. Нужны прошивка радио в `fw-wifi/` (см. `wifi_step=N` в
таблице параметров ядра), адрес радио одной строкой в `fw-wifi/mac` и файл `fw-wifi/network` — имя сети первой
@@ -391,7 +401,7 @@ Userland не изменён ни в одном байте: всё, чего е
| `xnu/` | наши правки XNU: патч, новые файлы, `apply.sh`/`export.sh` |
| `xnu-deps/` | всё для сборки XNU на Linux: `setup.sh`, обёртки инструментов, заглушки |
| `xnu-build.sh`, `xnu-env.sh` | сборка ядра |
-| `userland/` | наш init, вставки (`src/inject.c` — backboardd, `src/inject_sb.c` — SpringBoard, `src/inject_media.c` — mediaserverd), тесты, сборка образов |
+| `userland/` | наш init, вставки (`src/inject.c` — backboardd, `src/inject_sb.c` — SpringBoard, `src/inject_media.c` — mediaserverd, `src/inject_prefs.m` — Настройки), тесты, сборка образов |
| `ios165/` | добыча файлов iOS из IPSW и выбор того, что идёт в образ |
| `mkpackfs.py` | сборщик образов packfs (формат описан в `bsd/miscfs/packfs/packfs.h` ядра) |
| `qemu/` | запуск в QEMU, касания, снимки экрана, разбор стеков |
diff --git a/userland/build.sh b/userland/build.sh
index 2ebd366..fbfe17a 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -10,6 +10,9 @@
# JOBS="..." labels of the stock iOS launchd jobs to load (default: IOS_JOBS)
# REST=1 ... and the rest of them, started only when asked for (see mkjobs.py)
# WIFID=1 ... and wifid, iOS's Wi-Fi daemon (see below at IOS_JOBS)
+# HACKIOS_PANE=1 an entry "HackiOS" in Settings' main list and a pane of ours behind it, the
+# way tweaks add theirs (src/inject_prefs.m, src/hackios_pane.m, hackios/); not
+# yet in every image
# OSLOG="..." labels of the jobs whose os_log output goes to the console ("all": every
# one of JOBS; default: only the window server, which says little)
# INJECT="..." the programs started with a library of ours, "LIBRARY NAME..." per line
@@ -69,7 +72,8 @@ IOS_JOBS=${JOBS-"
# libredwood-media.dylib).
INJECT=${INJECT-"/redwood/lib/libredwood.dylib backboardd containermanagerd containermanagerd_system
/redwood/lib/libredwood-sb.dylib SpringBoard
-/redwood/lib/libredwood-media.dylib mediaserverd"}
+/redwood/lib/libredwood-media.dylib mediaserverd
+/redwood/lib/libredwood-prefs.dylib Preferences"}
mkdir -p obj
if [ -z "$PREBUILT" ] && ! command -v ld64 >/dev/null; then PREBUILT=1; fi
@@ -120,6 +124,40 @@ if [ -d $IOS/rootfs/usr/lib ]; then
-o obj/libredwood-sb.dylib src/inject_sb.c
$DYN -dynamiclib -install_name /redwood/lib/libredwood-media.dylib -framework CoreFoundation -lobjc \
-o obj/libredwood-media.dylib src/inject_media.c
+ if [ -n "$HACKIOS_PANE" ]; then
+ # the loader of Settings' entries, as PreferenceLoader is on a jailbroken phone (src/inject_prefs.m) ...
+ $DYN -dynamiclib -install_name /redwood/lib/libredwood-prefs.dylib -fobjc-arc \
+ -F${THEOS:-$HOME/theos}/sdks/iPhoneOS16.5.sdk/System/Library/PrivateFrameworks -framework Preferences \
+ -framework UIKit -framework Foundation -o obj/libredwood-prefs.dylib src/inject_prefs.m
+ # ... and the HackiOS pane, a preference bundle as tweaks ship theirs; the build it says it is: the
+ # repository's commit and its date (and whether the tree had changes)
+ build="HackiOS $(git -C .. rev-parse --short HEAD 2>/dev/null || echo ?) of $(git -C .. log -1 --format=%cd \
+ --date=short 2>/dev/null)$(git -C .. diff --quiet HEAD 2>/dev/null || echo ', with changes')"
+ rm -rf obj/HackiOS.bundle && mkdir -p obj/HackiOS.bundle
+ $DYN -bundle -fobjc-arc -DHACKIOS_BUILD="\"$build\"" \
+ -F${THEOS:-$HOME/theos}/sdks/iPhoneOS16.5.sdk/System/Library/PrivateFrameworks -framework Preferences \
+ -framework UIKit -framework Foundation -framework SystemConfiguration -o obj/HackiOS.bundle/HackiOS \
+ src/hackios_pane.m
+ cp hackios/Info.plist hackios/Root.plist obj/HackiOS.bundle/
+ # its icon: a glyph of our own, drawn here (no artwork of Apple's)
+ python3 -c '
+import sys
+from PIL import Image, ImageDraw, ImageFont
+for scale, name in ((1, "icon.png"), (2, "[email protected]"), (3, "[email protected]")):
+ size = 29 * scale
+ image = Image.new("RGBA", (size, size), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ draw.rounded_rectangle((0, 0, size - 1, size - 1), radius=6.5 * scale, fill=(36, 41, 56, 255))
+ try:
+ font = ImageFont.truetype("DejaVuSans-Bold.ttf", 19 * scale)
+ except OSError:
+ font = ImageFont.load_default()
+ draw.text((size / 2, size / 2), "H", font=font, fill=(255, 255, 255, 255), anchor="mm")
+ image.save(sys.argv[1] + "/" + name)
+' obj/HackiOS.bundle
+ else
+ rm -rf obj/libredwood-prefs.dylib obj/HackiOS.bundle
+ fi
if [ -n "$GL" ]; then
# the OpenGL ES library, and the table of functions that hands CoreAnimation's calls to it
# (Mesa says beside the library what it was built from: one from other patches is built again)
@@ -142,6 +180,13 @@ if [ -d $IOS/rootfs/usr/lib ]; then
mkdir -p root/lib
cp obj/libredwood.dylib obj/libredwood-sb.dylib root/lib/
[ -f obj/libredwood-media.dylib ] && cp obj/libredwood-media.dylib root/lib/ # (as with cpu_test)
+ rm -rf root/lib/libredwood-prefs.dylib root/Library/PreferenceLoader root/Library/PreferenceBundles
+ if [ -f obj/libredwood-prefs.dylib ] && [ -d obj/HackiOS.bundle ]; then
+ cp obj/libredwood-prefs.dylib root/lib/
+ mkdir -p root/Library/PreferenceLoader/Preferences root/Library/PreferenceBundles
+ cp hackios/HackiOS.plist root/Library/PreferenceLoader/Preferences/
+ cp -r obj/HackiOS.bundle root/Library/PreferenceBundles/
+ fi
if [ -n "$GL" ]; then
cp obj/libOSMesa.8.dylib root/lib/
cp obj/gl_test root/bin/
diff --git a/userland/hackios/HackiOS.plist b/userland/hackios/HackiOS.plist
new file mode 100644
index 0000000..f66152f
--- /dev/null
+++ b/userland/hackios/HackiOS.plist
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- The entry in Settings' main list, as a tweak ships one (/redwood/Library/PreferenceLoader/Preferences/). -->
+<plist version="1.0">
+<dict>
+ <key>entry</key>
+ <dict>
+ <key>bundle</key>
+ <string>HackiOS</string>
+ <key>cell</key>
+ <string>PSLinkCell</string>
+ <key>detail</key>
+ <string>HackiOSListController</string>
+ <key>icon</key>
+ <string>icon.png</string>
+ <key>isController</key>
+ <true/>
+ <key>label</key>
+ <string>HackiOS</string>
+ </dict>
+</dict>
+</plist>
diff --git a/userland/hackios/Info.plist b/userland/hackios/Info.plist
new file mode 100644
index 0000000..ce06b71
--- /dev/null
+++ b/userland/hackios/Info.plist
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>HackiOS</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.hackios.settings</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>HackiOS</string>
+ <key>CFBundlePackageType</key>
+ <string>BNDL</string>
+ <key>CFBundleVersion</key>
+ <string>1.0</string>
+ <key>NSPrincipalClass</key>
+ <string>HackiOSListController</string>
+</dict>
+</plist>
diff --git a/userland/hackios/Root.plist b/userland/hackios/Root.plist
new file mode 100644
index 0000000..2a59c71
--- /dev/null
+++ b/userland/hackios/Root.plist
@@ -0,0 +1,126 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- The HackiOS pane. A row: a dictionary here and, for hackiosSource, a function of src/hackios_pane.m. -->
+<plist version="1.0">
+<dict>
+ <key>title</key>
+ <string>HackiOS</string>
+ <key>items</key>
+ <array>
+ <dict>
+ <key>cell</key>
+ <string>PSGroupCell</string>
+ <key>label</key>
+ <string>Build</string>
+ <key>hackiosSource</key>
+ <string>build</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSGroupCell</string>
+ <key>label</key>
+ <string>Kernel</string>
+ <key>hackiosSource</key>
+ <string>kernel</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSGroupCell</string>
+ <key>label</key>
+ <string>Boot Arguments</string>
+ <key>hackiosSource</key>
+ <string>bootargs</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSGroupCell</string>
+ <key>label</key>
+ <string>Now</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>Up for</string>
+ <key>hackiosSource</key>
+ <string>uptime</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>Memory</string>
+ <key>hackiosSource</key>
+ <string>memory</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>Processors</string>
+ <key>hackiosSource</key>
+ <string>processors</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>GPU</string>
+ <key>hackiosSource</key>
+ <string>gpu</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>Wi-Fi</string>
+ <key>hackiosSource</key>
+ <string>wifi</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>Battery</string>
+ <key>hackiosSource</key>
+ <string>battery</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSTitleValueCell</string>
+ <key>label</key>
+ <string>Buttons</string>
+ <key>hackiosSource</key>
+ <string>buttons</string>
+ <key>get</key>
+ <string>hackiosValue:</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSGroupCell</string>
+ <key>footerText</key>
+ <string>iOS stops at once and the phone goes back to the loader's menu, as with five fingers held on the screen. You are asked first.</string>
+ </dict>
+ <dict>
+ <key>cell</key>
+ <string>PSButtonCell</string>
+ <key>label</key>
+ <string>Return to the Loader</string>
+ <key>action</key>
+ <string>hackiosLeave:</string>
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/userland/src/hackios_pane.m b/userland/src/hackios_pane.m
new file mode 100644
index 0000000..c2eac57
--- /dev/null
+++ b/userland/src/hackios_pane.m
@@ -0,0 +1,278 @@
+/*
+ * HackiOS.bundle: the pane behind Settings' entry "HackiOS", a preference bundle as tweaks ship
+ * theirs (/redwood/Library/PreferenceBundles/HackiOS.bundle; its entry is
+ * /redwood/Library/PreferenceLoader/Preferences/HackiOS.plist, read by src/inject_prefs.m).
+ *
+ * Its rows are in Root.plist (userland/hackios/), each with "hackiosSource": the name of one of the
+ * functions below that says the row's text, read-only and true, each from where it really comes:
+ * the kernel's sysctls (kern.redwood.* are ours: bsd/dev/redwood_*.c), the host's figures, configd's
+ * store. A group with a hackiosSource has the text under its title (for what is too long for a
+ * row). To add a row: a dictionary in Root.plist and a function here in sources[].
+ */
+#import <Foundation/Foundation.h>
+#import <UIKit/UIKit.h>
+#include <mach/mach.h>
+#include <sys/sysctl.h>
+#include <sys/time.h>
+
+/* ---- Preferences.framework, as much of it as is used (a private framework: no headers) ---- */
+
+@interface PSSpecifier : NSObject
+- (void)setProperty:(id)value forKey:(NSString *)key;
+- (id)propertyForKey:(NSString *)key;
+- (long long)cellType;
+@end
+
+@interface PSListController : UIViewController
+- (NSArray *)loadSpecifiersFromPlistName:(NSString *)name target:(id)target;
+@end
+
+enum { PSGroupCell = 0 };
+
+/* configd's store: in SystemConfiguration, not in the iOS SDK's headers */
+typedef const struct __SCDynamicStore *SCDynamicStoreRef;
+extern SCDynamicStoreRef SCDynamicStoreCreate(CFAllocatorRef allocator, CFStringRef name, void *callout, void *context);
+extern CFPropertyListRef SCDynamicStoreCopyValue(SCDynamicStoreRef store, CFStringRef key);
+
+#ifndef HACKIOS_BUILD
+#define HACKIOS_BUILD "HackiOS (a build without its commit)"
+#endif
+
+/* ---- the sources ---------------------------------------------------------------------------------------- */
+
+static NSString *
+sysctl_text(const char *name)
+{
+ char buffer[2048];
+ size_t size = sizeof(buffer) - 1;
+
+ if (sysctlbyname(name, buffer, &size, NULL, 0) != 0) {
+ return nil;
+ }
+ buffer[size] = 0;
+ return @(buffer);
+}
+
+static bool
+sysctl_number(const char *name, long long *value)
+{
+ union {
+ int32_t i32;
+ int64_t i64;
+ } u = { 0 };
+ size_t size = sizeof(u);
+
+ if (sysctlbyname(name, &u, &size, NULL, 0) != 0) {
+ return false;
+ }
+ *value = size == sizeof(int32_t) ? u.i32 : u.i64;
+ return true;
+}
+
+static NSString *
+source_build(void)
+{
+ return @HACKIOS_BUILD;
+}
+
+static NSString *
+source_kernel(void)
+{
+ NSString *version = sysctl_text("kern.version");
+ NSRange colon = [version rangeOfString:@": "], semicolon = [version rangeOfString:@";"];
+
+ /* "Darwin Kernel Version 22.5.0: <date>; root:xnu-8796.121.2~1/..." */
+ if (version == nil || colon.location == NSNotFound || semicolon.location == NSNotFound || semicolon.location < colon.location) {
+ return version ?: @"?";
+ }
+ return [NSString stringWithFormat:@"%@, built %@", sysctl_text("kern.osrelease") ?: @"?",
+ [version substringWithRange:NSMakeRange(colon.location + 2, semicolon.location - colon.location - 2)]];
+}
+
+/* The boot arguments, less what is the user's own: the radio's address. */
+static NSString *
+source_bootargs(void)
+{
+ NSMutableArray *kept = [NSMutableArray array];
+
+ for (NSString *word in [sysctl_text("kern.bootargs") componentsSeparatedByString:@" "]) {
+ if (word.length != 0 && ![word hasPrefix:@"wifi_mac="]) {
+ [kept addObject:word];
+ }
+ }
+ return kept.count ? [kept componentsJoinedByString:@" "] : @"none";
+}
+
+static NSString *
+source_uptime(void)
+{
+ struct timeval boot = { 0 }, now;
+ size_t size = sizeof(boot);
+ long seconds;
+
+ if (sysctlbyname("kern.boottime", &boot, &size, NULL, 0) != 0) {
+ return @"?";
+ }
+ gettimeofday(&now, NULL);
+ seconds = now.tv_sec - boot.tv_sec;
+ return seconds >= 3600 ? [NSString stringWithFormat:@"%ld h %ld min", seconds / 3600, seconds / 60 % 60] :
+ [NSString stringWithFormat:@"%ld min %ld s", seconds / 60, seconds % 60];
+}
+
+static NSString *
+source_memory(void)
+{
+ vm_statistics64_data_t vm;
+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
+ long long total = 0;
+ vm_size_t page = 0;
+
+ sysctl_number("hw.memsize", &total);
+ host_page_size(mach_host_self(), &page);
+ if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vm, &count) != KERN_SUCCESS) {
+ return [NSString stringWithFormat:@"%.1f GB", total / 1073741824.0];
+ }
+ return [NSString stringWithFormat:@"%.1f GB, %llu MB free", total / 1073741824.0, (unsigned long long)vm.free_count * page >> 20];
+}
+
+static NSString *
+source_processors(void)
+{
+ long long running = 0, khz = 0;
+
+ sysctl_number("hw.activecpu", &running);
+ sysctl_number("kern.redwood.cpu_khz", &khz);
+ return khz > 0 ? [NSString stringWithFormat:@"%lld, up to %.2f GHz", running, khz / 1e6] :
+ [NSString stringWithFormat:@"%lld, the loader's speed", running];
+}
+
+static NSString *
+source_gpu(void)
+{
+ long long khz = 0;
+
+ return sysctl_number("kern.redwood.gpu_khz", &khz) && khz > 0 ? [NSString stringWithFormat:@"on, %lld MHz", khz / 1000] :
+ @"off (the screen is drawn by the processors)";
+}
+
+/* The radio: the kernel's word for its state; the network's name and signal as Settings itself shows them (configd's store). */
+static NSString *
+source_wifi(void)
+{
+ NSString *state = sysctl_text("kern.redwood.wifi") ?: @"none";
+ SCDynamicStoreRef store;
+ NSDictionary *airport = nil;
+ long long rssi = 0;
+
+ if (![state isEqualToString:@"joined"]) {
+ return [state isEqualToString:@"none"] ? @"no radio (wifi=1 not given)" : [state isEqualToString:@"off"] ?
+ @"turned off" : [state isEqualToString:@"joining"] ? @"joining" : @"on, not joined";
+ }
+ sysctl_number("kern.redwood.wifi_rssi", &rssi);
+ /* (the name only where Settings shows it too: when iOS's Wi-Fi daemon runs, it is in configd's store) */
+ if ((store = SCDynamicStoreCreate(NULL, CFSTR("HackiOS"), NULL, NULL)) != NULL) {
+ airport = CFBridgingRelease(SCDynamicStoreCopyValue(store, CFSTR("State:/Network/Interface/en0/AirPort")));
+ CFRelease(store);
+ }
+ if ([airport isKindOfClass:NSDictionary.class] && [airport[@"SSID_STR"] isKindOfClass:NSString.class]) {
+ return [NSString stringWithFormat:@"%@, %lld dBm", airport[@"SSID_STR"], rssi];
+ }
+ return [NSString stringWithFormat:@"joined, %lld dBm", rssi];
+}
+
+static NSString *
+source_battery(void)
+{
+ long long present = 0, soc = 0, mv = 0, ma = 0;
+
+ if (![[sysctl_text("kern.bootargs") componentsSeparatedByString:@" "] containsObject:@"battery=1"]) {
+ return @"not read (battery=1 not given)";
+ }
+ if (!sysctl_number("kern.redwood.battery_present", &present) || !present) {
+ return @"the fuel gauge sees no battery";
+ }
+ sysctl_number("kern.redwood.battery_soc", &soc);
+ sysctl_number("kern.redwood.battery_voltage_mv", &mv);
+ sysctl_number("kern.redwood.battery_current_ma", &ma);
+ return [NSString stringWithFormat:@"%lld %%, %.2f V, %@", soc, mv / 1000.0, ma < 0 ?
+ [NSString stringWithFormat:@"charging at %lld mA", -ma] : [NSString stringWithFormat:@"%lld mA", ma]];
+}
+
+static NSString *
+source_buttons(void)
+{
+ long long on = 0;
+
+ return sysctl_number("kern.redwood.buttons", &on) && on ? @"running" : @"off";
+}
+
+/* ---- the pane ------------------------------------------------------------------------------------------ */
+
+static const struct {
+ NSString *name;
+ NSString *(*text)(void);
+} sources[] = {
+ { @"build", source_build }, { @"kernel", source_kernel }, { @"bootargs", source_bootargs }, { @"uptime", source_uptime },
+ { @"memory", source_memory }, { @"processors", source_processors }, { @"gpu", source_gpu }, { @"wifi", source_wifi },
+ { @"battery", source_battery }, { @"buttons", source_buttons },
+};
+
+static NSString *
+source_text(NSString *name)
+{
+ for (unsigned i = 0; i < sizeof(sources) / sizeof(sources[0]); i++) {
+ if ([sources[i].name isEqualToString:name]) {
+ return sources[i].text();
+ }
+ }
+ return nil;
+}
+
+@interface HackiOSListController : PSListController
+@end
+
+@implementation HackiOSListController
+
+- (NSArray *)specifiers
+{
+ NSMutableArray *list = [self valueForKey:@"_specifiers"];
+
+ if (list == nil) {
+ list = [[self loadSpecifiersFromPlistName:@"Root" target:self] mutableCopy];
+ for (PSSpecifier *specifier in list) {
+ NSString *source = [specifier propertyForKey:@"hackiosSource"];
+
+ if (source != nil && [specifier cellType] == PSGroupCell) {
+ [specifier setProperty:source_text(source) forKey:@"footerText"];
+ }
+ }
+ [self setValue:list forKey:@"_specifiers"];
+ }
+ return list;
+}
+
+/* the "get" of Root.plist's rows */
+- (id)hackiosValue:(PSSpecifier *)specifier
+{
+ return source_text([specifier propertyForKey:@"hackiosSource"]);
+}
+
+/* What five fingers held on the screen do (bsd/dev/redwood_input.c), behind a confirmation. */
+- (void)hackiosLeave:(PSSpecifier *)specifier
+{
+ UIAlertController *ask = [UIAlertController alertControllerWithTitle:@"Return to the Loader?"
+ message:@"iOS stops at once and the phone goes back to the loader, as with five fingers held on the screen."
+ preferredStyle:UIAlertControllerStyleAlert];
+
+ [ask addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
+ [ask addAction:[UIAlertAction actionWithTitle:@"Return" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+ int one = 1;
+
+ if (sysctlbyname("kern.redwood.leave", NULL, NULL, &one, sizeof(one)) != 0) {
+ NSLog(@"HackiOS: kern.redwood.leave: %s", strerror(errno));
+ }
+ }]];
+ [self presentViewController:ask animated:YES completion:nil];
+}
+
+@end
diff --git a/userland/src/inject_prefs.m b/userland/src/inject_prefs.m
new file mode 100644
index 0000000..1990057
--- /dev/null
+++ b/userland/src/inject_prefs.m
@@ -0,0 +1,146 @@
+/*
+ * libredwood-prefs.dylib: code of ours inside the Settings app (its process is "Preferences"; see
+ * inject.c for how a library of ours gets into a stock program). It does what PreferenceLoader
+ * does for tweaks on a jailbroken phone, and in the same way, so that a pane of ours is added the
+ * way a tweak adds one:
+ *
+ * - an entry is a property list with a dictionary "entry" in
+ * /redwood/Library/PreferenceLoader/Preferences/ (and in /Library/PreferenceLoader/Preferences/,
+ * where a jailbreak keeps them), as tweaks ship them: label, cell (PSLinkCell), icon, bundle,
+ * isController, detail;
+ * - the bundle it names is a preference bundle in /redwood/Library/PreferenceBundles/ (then
+ * /Library/PreferenceBundles/, then /System/Library/PreferenceBundles/), loaded only when the
+ * entry is tapped;
+ * - the entries, sorted by their labels, are one group of their own in Settings' main list, put
+ * where PreferenceLoader puts it: after Apple's own settings, at the end of the list as it is
+ * first built (the App Store applications' group, which comes later, goes below it).
+ *
+ * After rpetrich's and DHowett's PreferenceLoader (Tweak.xm, prefs.xm), without Substrate: the
+ * root list controller's -specifiers is replaced with the runtime's own calls. The first pane of
+ * ours this way is HackiOS's (src/hackios_pane.m).
+ */
+#import <Foundation/Foundation.h>
+#import <UIKit/UIKit.h>
+#include <objc/runtime.h>
+
+/* ---- Preferences.framework, as much of it as is used (a private framework: no headers) ---- */
+
+@interface PSSpecifier : NSObject
++ (instancetype)groupSpecifierWithName:(NSString *)name;
+- (void)setProperty:(id)value forKey:(NSString *)key;
+@property (nonatomic, retain) NSString *name;
+@property (nonatomic, retain) NSString *identifier;
+@end
+
+@interface PSListController : UIViewController
+@end
+
+extern NSArray *SpecifiersFromPlist(NSDictionary *plist, PSSpecifier *previous, id target, NSString *plistName, NSBundle *bundle,
+ NSString **title, NSString **specifierID, PSListController *callerList, NSMutableArray **bundleControllers);
+extern NSString *PSLazilyLoadedBundleKey;
+
+static NSString *const entry_directories[] = { @"/redwood/Library/PreferenceLoader/Preferences", @"/Library/PreferenceLoader/Preferences" };
+static NSString *const bundle_directories[] = { @"/redwood/Library/PreferenceBundles", @"/Library/PreferenceBundles",
+ @"/System/Library/PreferenceBundles" };
+
+/* An entry's specifiers (PreferenceLoader's -specifiersFromEntry:...), or nil. */
+static NSArray *
+entry_specifiers(PSListController *root, NSDictionary *entry, NSString *title)
+{
+ NSString *name = entry[@"bundle"], *path = nil;
+ NSMutableArray *controllers = nil;
+ NSArray *specifiers;
+ NSBundle *bundle;
+
+ if (![name isKindOfClass:NSString.class]) {
+ NSLog(@"HackiOS: the entry %@ names no bundle: left out", title);
+ return nil;
+ }
+ for (unsigned i = 0; i < sizeof(bundle_directories) / sizeof(bundle_directories[0]) && path == nil; i++) {
+ NSString *candidate = [NSString stringWithFormat:@"%@/%@.bundle", bundle_directories[i], name];
+
+ path = [NSFileManager.defaultManager fileExistsAtPath:candidate] ? candidate : nil;
+ }
+ if (path == nil || (bundle = [NSBundle bundleWithPath:path]) == nil) {
+ NSLog(@"HackiOS: the entry %@: no bundle %@ in any of the places for them: left out", title, name);
+ return nil;
+ }
+ specifiers = SpecifiersFromPlist(@{ @"items": @[ entry ] }, nil, root, title, bundle, NULL, NULL, root, &controllers);
+ if ([entry[@"isController"] boolValue]) {
+ for (PSSpecifier *specifier in specifiers) {
+ [specifier setProperty:path forKey:PSLazilyLoadedBundleKey]; /* (the bundle is loaded when tapped) */
+ if (specifier.name == nil) {
+ specifier.name = title;
+ }
+ }
+ }
+ return specifiers.count ? specifiers : nil;
+}
+
+static NSArray *(*root_specifiers)(id self, SEL _cmd);
+static Ivar specifiers_ivar;
+
+static NSArray *
+our_root_specifiers(id self, SEL _cmd)
+{
+ bool first = object_getIvar(self, specifiers_ivar) == nil;
+ NSArray *list = root_specifiers(self, _cmd);
+ NSMutableArray *loaded = [NSMutableArray array], *mutable;
+ NSUInteger at;
+
+ if (!first || ![list isKindOfClass:NSMutableArray.class]) {
+ return list;
+ }
+ for (unsigned d = 0; d < sizeof(entry_directories) / sizeof(entry_directories[0]); d++) {
+ NSArray *files = [NSFileManager.defaultManager subpathsOfDirectoryAtPath:entry_directories[d] error:NULL];
+
+ for (NSString *file in [files sortedArrayUsingSelector:@selector(compare:)]) {
+ NSDictionary *plist = [file.pathExtension isEqualToString:@"plist"] ? [NSDictionary dictionaryWithContentsOfFile:
+ [entry_directories[d] stringByAppendingPathComponent:file]] : nil;
+ NSArray *specifiers = [plist[@"entry"] isKindOfClass:NSDictionary.class] ? entry_specifiers(self, plist[@"entry"],
+ file.lastPathComponent.stringByDeletingPathExtension) : nil;
+
+ if (specifiers != nil) {
+ [loaded addObjectsFromArray:specifiers];
+ }
+ }
+ }
+ if (loaded.count == 0) {
+ return list;
+ }
+ [loaded sortUsingComparator:^NSComparisonResult(PSSpecifier *a, PSSpecifier *b) {
+ return [a.name localizedCaseInsensitiveCompare:b.name];
+ }];
+ [loaded insertObject:[PSSpecifier groupSpecifierWithName:nil] atIndex:0];
+ /* (PreferenceLoader puts the group after the one that holds TWITTER, where there is one: iOS 6 to 10; else at the end) */
+ mutable = (NSMutableArray *)list;
+ at = mutable.count;
+ for (NSUInteger i = 0; i < mutable.count; i++) {
+ if ([[mutable[i] identifier] isEqualToString:@"TWITTER"]) {
+ for (at = i + 1; at < mutable.count && ![[mutable[at] valueForKey:@"cellType"] isEqual:@0]; at++) {
+ }
+ break;
+ }
+ }
+ [mutable insertObjects:loaded atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(at, loaded.count)]];
+ return list;
+}
+
+__attribute__((constructor))
+static void
+start(void)
+{
+ Class root = objc_getClass("PSUIPrefsListController"), list = objc_getClass("PSListController");
+ Method method = root != Nil ? class_getInstanceMethod(root, @selector(specifiers)) : NULL;
+
+ specifiers_ivar = list != Nil ? class_getInstanceVariable(list, "_specifiers") : NULL;
+ if (method == NULL || specifiers_ivar == NULL) {
+ NSLog(@"HackiOS: no PSUIPrefsListController -specifiers here: Settings' main list is left as it is");
+ return;
+ }
+ /* (the root's own method if it has one; else one of its own is added: PSListController's stays as it is for every other pane) */
+ root_specifiers = (NSArray *(*)(id, SEL))method_getImplementation(method);
+ if (!class_addMethod(root, @selector(specifiers), (IMP)our_root_specifiers, method_getTypeEncoding(method))) {
+ method_setImplementation(method, (IMP)our_root_specifiers);
+ }
+}