Skip to content

Commit 2798a14

Browse files
committed
Route signed iOS game frameworks to their own host
1 parent 6b5870d commit 2798a14

5 files changed

Lines changed: 283 additions & 12 deletions

File tree

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// Link only into a self-hosted game framework, never the shared launcher.
2+
#import <UIKit/UIKit.h>
3+
#include <pthread.h>
4+
#include <signal.h>
5+
#include <sys/stat.h>
6+
#include "IndependentGameHost.h"
7+
#include "dmsh_chain.h"
8+
#include "front.h"
9+
#include "loader_image.h"
10+
#ifdef DM_MULTI_GAME
11+
#include "game_profile_runtime.h"
12+
#endif
13+
14+
#define DM_EXPORT __attribute__((used, visibility("default")))
15+
DM_EXPORT const int dm_glue_version = TONTON_GAME_HOST_VERSION;
16+
#ifndef DM_INDEPENDENT_SHADER_CHAIN
17+
#define DM_INDEPENDENT_SHADER_CHAIN DMSH_CHAIN
18+
#endif
19+
DM_EXPORT const char *dm_glue_shader_chain(void) { return "b-" DM_INDEPENDENT_SHADER_CHAIN; }
20+
21+
int dm_main(int argc, char **argv);
22+
UIViewController *front_ios_root(void);
23+
void front_ios_audio_session(void);
24+
void front_ios_focus_event(int event);
25+
static char *game_argv[3];
26+
static BOOL prepared;
27+
static void *(*game_catalog)(void *returnBlock);
28+
29+
DM_EXPORT void dm_glue_set_catalog(void *(*catalog)(void *returnBlock)) {
30+
game_catalog = catalog;
31+
}
32+
33+
UIViewController *TonTonInGameCatalogController(dispatch_block_t returned) {
34+
return game_catalog ? (__bridge_transfer UIViewController *)game_catalog((__bridge void *)returned) : nil;
35+
}
36+
37+
DM_EXPORT const char *dm_glue_start_game(const char *const *argv, int argc, const void *image) {
38+
if (prepared || argc != 2 || !argv || !argv[0] || !argv[1] || !image)
39+
return "Invalid or repeated game start.";
40+
#ifdef DM_INDEPENDENT_GAME_TITLE
41+
const char *title = getenv("DM_LIBRARY_GAME_ID");
42+
if (!title || strcasecmp(title, DM_INDEPENDENT_GAME_TITLE))
43+
return "The selected game is not the one embedded in this engine.";
44+
#ifdef DM_MULTI_GAME
45+
if (!dm_profile_select(DM_INDEPENDENT_GAME_TITLE)) return "The game's engine profile is missing.";
46+
#endif
47+
#endif
48+
game_argv[0] = strdup(argv[0]);
49+
game_argv[1] = strdup(argv[1]);
50+
if (!game_argv[0] || !game_argv[1] || !dm_set_game_image_header(image)) {
51+
free(game_argv[0]); free(game_argv[1]);
52+
game_argv[0] = game_argv[1] = NULL;
53+
return "Cannot initialize the game's signed module image.";
54+
}
55+
front_hud_env();
56+
dm_host_preload_start(2, game_argv);
57+
prepared = YES;
58+
return NULL;
59+
}
60+
61+
DM_EXPORT void dm_glue_present_game(void *window) {
62+
if (!prepared || !window) return;
63+
UIWindow *target = (__bridge UIWindow *)window;
64+
UIViewController *game = front_ios_root();
65+
target.rootViewController = game;
66+
if (@available(iOS 16.0, *)) {
67+
[game setNeedsUpdateOfSupportedInterfaceOrientations];
68+
[target.windowScene requestGeometryUpdateWithPreferences:
69+
[[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskLandscape]
70+
errorHandler:^(NSError *error) {
71+
fprintf(stderr, "boot: independent game landscape request: %s\n", error.localizedDescription.UTF8String);
72+
}];
73+
}
74+
}
75+
76+
DM_EXPORT void dm_glue_focus_event(int event) {
77+
if (prepared) front_ios_focus_event(event);
78+
}
79+
80+
static void *game_thread(void *arg) {
81+
(void)arg;
82+
static char alternate[65536];
83+
stack_t stack = {.ss_sp = alternate, .ss_size = sizeof alternate};
84+
sigaltstack(&stack, NULL);
85+
int status = dm_main(2, game_argv);
86+
fprintf(stderr, "boot: independent game returned %d\n", status);
87+
return NULL;
88+
}
89+
90+
void front_ios_boot(void) {
91+
static BOOL started;
92+
if (!prepared || started) return;
93+
front_ios_audio_session();
94+
pthread_attr_t attr;
95+
if (pthread_attr_init(&attr)) return;
96+
pthread_t thread;
97+
int error = pthread_attr_setstacksize(&attr, 64u << 20);
98+
if (!error) error = pthread_create(&thread, &attr, game_thread, NULL);
99+
pthread_attr_destroy(&attr);
100+
if (error) {
101+
fprintf(stderr, "[RED] boot: independent game thread: %s\n", strerror(error));
102+
return;
103+
}
104+
started = YES;
105+
pthread_detach(thread);
106+
}
107+
108+
int front_ios_boot_ok(void) { return prepared; }
109+
const char *front_ios_boot_message(void) { return NULL; }
110+
const char *front_ios_device_check(void) { return NULL; }
111+
int dm_locate_game_data(void) {
112+
const char *romfs = getenv("DM_ROMFS");
113+
struct stat st;
114+
return romfs && !stat(romfs, &st);
115+
}
116+
bool dm_show_launcher(void *controller, void (*done)(void)) {
117+
(void)controller; (void)done;
118+
return false;
119+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#pragma once
2+
3+
#import <Foundation/Foundation.h>
4+
#include <dlfcn.h>
5+
#include <mach-o/loader.h>
6+
#include <string.h>
7+
8+
// TonTon's signed module layout is distinct from upstream FH. Keep a
9+
// separate ABI so a manifest cannot opt foreign code into this loader.
10+
#define TONTON_INDEPENDENT_ABI @"tonton-independent-host-v1"
11+
#define TONTON_GAME_HOST_VERSION 1
12+
13+
typedef struct {
14+
const char *(*start)(const char *const *argv, int argc, const void *image);
15+
void (*present)(void *window);
16+
void (*focus)(int event);
17+
void (*setCatalog)(void *(*catalog)(void *returnBlock));
18+
} TonTonGameHost;
19+
20+
static BOOL TonTonIndependentManifest(NSDictionary *manifest) {
21+
return [manifest isKindOfClass:NSDictionary.class] && [manifest[@"loader"] isEqual:@"FH"] &&
22+
[manifest[@"tonton_host_abi"] isEqual:TONTON_INDEPENDENT_ABI];
23+
}
24+
25+
static BOOL TonTonIndependentChain(id value) {
26+
if (![value isKindOfClass:NSString.class] || [value length] != 14 ||
27+
![value hasPrefix:@"b-"]) return NO;
28+
NSString *hash = [value substringFromIndex:2];
29+
NSCharacterSet *other = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet];
30+
return [hash rangeOfCharacterFromSet:other].location == NSNotFound;
31+
}
32+
33+
static void *TonTonImageSymbol(void *handle, const char *name, const void *image) {
34+
void *symbol = dlsym(handle, name);
35+
Dl_info owner = {0};
36+
return symbol && dladdr(symbol, &owner) && owner.dli_fbase == image ? symbol : NULL;
37+
}
38+
39+
static BOOL TonTonReadIndependentHost(void *handle, const void *image, NSString *chain,
40+
TonTonGameHost *out) {
41+
const int *version = TonTonImageSymbol(handle, "dm_glue_version", image);
42+
const char *(*ownChain)(void) = TonTonImageSymbol(handle, "dm_glue_shader_chain", image);
43+
TonTonGameHost host = {
44+
.start = TonTonImageSymbol(handle, "dm_glue_start_game", image),
45+
.present = TonTonImageSymbol(handle, "dm_glue_present_game", image),
46+
.focus = TonTonImageSymbol(handle, "dm_glue_focus_event", image),
47+
.setCatalog = TonTonImageSymbol(handle, "dm_glue_set_catalog", image),
48+
};
49+
if (!version || *version != TONTON_GAME_HOST_VERSION || !ownChain ||
50+
!host.start || !host.present || !host.focus || !host.setCatalog) return NO;
51+
const char *builtChain = ownChain();
52+
if (!builtChain || !TonTonIndependentChain(chain) || strcmp(builtChain, chain.UTF8String)) return NO;
53+
*out = host;
54+
return YES;
55+
}

‎dm/ios/LibraryApp/Sources/LibraryFramework.h‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include "loader_image.h"
77
#include "game_profile_runtime.h"
88
#include "dmsh_chain.h"
9+
#import "IndependentGameHost.h"
910

1011
// This fork's signed __TEXT layout differs from newer upstream frameworks.
1112
// Never accept a foreign framework merely because its title ID matches.
@@ -19,13 +20,15 @@ static NSString *TonTonFrameworkProblem(NSDictionary *manifest, NSString *title,
1920
if (![manifest[@"title_id"] isEqual:title.uppercaseString] ||
2021
![manifest[@"modules"] isEqual:modules] || !modules.count)
2122
return @"游戏程序与所选卡带不匹配。";
22-
if (![manifest[@"chain"] isEqual:@"b-" DMSH_CHAIN] ||
23-
![manifest[@"tonton_host_abi"] isEqual:TONTON_FRAMEWORK_ABI])
23+
BOOL independent = TonTonIndependentManifest(manifest);
24+
if (independent ? !TonTonIndependentChain(manifest[@"chain"]) :
25+
(![manifest[@"chain"] isEqual:@"b-" DMSH_CHAIN] ||
26+
![manifest[@"tonton_host_abi"] isEqual:TONTON_FRAMEWORK_ABI]))
2427
return @"游戏程序需要用当前游戏匣的兼容引擎重新构建。";
2528
NSString *fw=[@"DmGame" stringByAppendingFormat:@"%@.framework",title.uppercaseString];
2629
if (![manifest[@"framework"] isEqual:fw] || ![manifest[@"framework_executable"] isEqual:@"DmGame"] ||
2730
![manifest[@"image_marker"] isEqual:@"dm_game_image_marker"] ||
28-
![manifest[@"loader"] isEqual:@"FR"] || ![manifest[@"nro_count"] isEqual:@0])
31+
(!independent && ![manifest[@"loader"] isEqual:@"FR"]) || ![manifest[@"nro_count"] isEqual:@0])
2932
return @"游戏程序的加载格式尚不兼容。";
3033
NSString *min=manifest[@"min_os"];
3134
NSCharacterSet *invalid=[[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
@@ -40,7 +43,10 @@ static NSString *TonTonFrameworkProblem(NSDictionary *manifest, NSString *title,
4043

4144
// nil framework means the existing embedded cartridge remains in use. Foreign
4245
// downloaded code in Documents is never searched or dlopened.
43-
static BOOL TonTonPrepareGameFramework(NSString *title, NSString **tables, NSString **failure) {
46+
static BOOL TonTonPrepareGameFramework(NSString *title, NSString **tables, NSString **failure,
47+
TonTonGameHost *host, const void **image) {
48+
*host = (TonTonGameHost){0};
49+
*image = NULL;
4450
NSString *fw=[NSBundle.mainBundle.privateFrameworksPath stringByAppendingPathComponent:
4551
[NSString stringWithFormat:@"DmGame%@.framework",title.uppercaseString]];
4652
if (![NSFileManager.defaultManager fileExistsAtPath:fw]) return YES;
@@ -64,16 +70,28 @@ static BOOL TonTonPrepareGameFramework(NSString *title, NSString **tables, NSStr
6470
}
6571
if (problem) { if(failure)*failure=problem;return NO; }
6672
NSString *executable=[fw stringByAppendingPathComponent:@"DmGame"];
67-
void *handle=dlopen(executable.fileSystemRepresentation,RTLD_LOCAL|RTLD_NOW);
73+
void *handle=dlopen(executable.fileSystemRepresentation,RTLD_LOCAL|RTLD_NOW|RTLD_FIRST);
6874
if (!handle) { if(failure)*failure=@"系统无法验证并加载这款游戏的签名程序。";return NO; }
6975
void *marker=dlsym(handle,"dm_game_image_marker");Dl_info info={0};
7076
if (!marker || !dladdr(marker,&info) || !info.dli_fbase || !info.dli_fname ||
7177
![[@(info.dli_fname) stringByResolvingSymlinksInPath] isEqual:executable.stringByResolvingSymlinksInPath] ||
72-
((const struct mach_header_64 *)info.dli_fbase)->filetype!=MH_DYLIB ||
73-
!dm_set_game_image_header(info.dli_fbase)) {
78+
((const struct mach_header_64 *)info.dli_fbase)->filetype!=MH_DYLIB) {
7479
// Do not unload an image whose static initialization may have run.
7580
if(failure)*failure=@"这款游戏的签名模块身份不正确,未启动。";return NO;
7681
}
82+
if (TonTonIndependentManifest(manifest)) {
83+
if (!TonTonReadIndependentHost(handle, info.dli_fbase, manifest[@"chain"], host)) {
84+
if(failure)*failure=@"游戏自带引擎的接口或着色器版本不匹配。";
85+
return NO;
86+
}
87+
*image = info.dli_fbase;
88+
*tables = dm;
89+
return YES;
90+
}
91+
if (!dm_set_game_image_header(info.dli_fbase)) {
92+
if(failure)*failure=@"这款游戏的签名模块身份不正确,未启动。";
93+
return NO;
94+
}
7795
*tables=dm;
7896
fprintf(stderr,"boot: signed game framework %s, ABI tonton-signed-text-v1\n",executable.fileSystemRepresentation);
7997
return YES;

‎dm/ios/Sources/main.m‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@
3636
void front_ios_focus_event(int ev);
3737

3838
static char *g_argv[4]; static int g_argc;
39+
#ifdef DM_LIBRARY_HOST
40+
static TonTonGameHost g_independent_host;
41+
static const void *g_independent_image;
42+
#endif
3943

4044
// Documents/romfs.img, one RomFS image file (dm/tools/romfs_image.py, scripts/push_romfs.sh): only a complete one counts. Its index is written last and ends the file, so a copy cut off partway is skipped
4145
static int romfs_image_complete(NSString *path) {
@@ -269,7 +273,8 @@ static int boot_env(void) {
269273
NSString *moduleTables=dm;
270274
#ifdef DM_LIBRARY_HOST
271275
NSString *frameworkError=nil;
272-
if (!TonTonPrepareGameFramework(@(getenv("DM_LIBRARY_GAME_ID")),&moduleTables,&frameworkError)) {
276+
if (!TonTonPrepareGameFramework(@(getenv("DM_LIBRARY_GAME_ID")),&moduleTables,&frameworkError,
277+
&g_independent_host,&g_independent_image)) {
273278
fprintf(stderr,"[RED] boot: %s\n",frameworkError.UTF8String);return 0;
274279
}
275280
#endif
@@ -281,6 +286,9 @@ static int boot_env(void) {
281286
if ([fm fileExistsAtPath:pso]) setenv("DM_PSO_BUNDLE", pso.fileSystemRepresentation, 0);
282287
chdir(doc.fileSystemRepresentation);
283288
g_argv[0] = strdup("dmhost"); g_argv[1] = strdup(moduleTables.fileSystemRepresentation); g_argc = 2;
289+
#ifdef DM_LIBRARY_HOST
290+
if (g_independent_host.start) return 1; // Start after the library applies per-game settings.
291+
#endif
284292
dm_host_preload_start(g_argc, g_argv); // Module tables / relocation / takeover run early in the background, in parallel with UIKit startup (and the launcher: the settings it sets are read when the game starts)
285293
return 1;
286294
}
@@ -301,6 +309,16 @@ void front_ios_boot(void) { // Called by front_ios.m once the window and Metal
301309
}
302310
int front_ios_boot_ok(void) { return g_boot_ok; }
303311

312+
static void focus_game(int event) {
313+
#ifdef DM_LIBRARY_HOST
314+
if (g_boot_ok && g_independent_host.focus) {
315+
g_independent_host.focus(event);
316+
return;
317+
}
318+
#endif
319+
front_ios_focus_event(event);
320+
}
321+
304322
@class SceneDelegate;
305323
@interface App : UIResponder <UIApplicationDelegate>
306324
@end
@@ -354,6 +372,21 @@ - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session op
354372
[owner.window.rootViewController presentViewController:alert animated:YES completion:nil];return;
355373
}
356374
TonTonApplyGlobalSettings(titleID);
375+
if (g_independent_host.start) {
376+
const char *error = g_independent_host.start((const char *const *)g_argv, g_argc, g_independent_image);
377+
if (error) {
378+
fprintf(stderr,"[RED] boot: independent game host: %s\n",error);
379+
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"卡带暂时无法启动"
380+
message:@"游戏自带引擎未能启动。" preferredStyle:UIAlertControllerStyleAlert];
381+
[alert addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
382+
[owner.window.rootViewController presentViewController:alert animated:YES completion:nil];
383+
g_independent_host = (TonTonGameHost){0};
384+
return;
385+
}
386+
g_boot_ok=1;
387+
g_independent_host.present((__bridge void *)owner.window);
388+
return;
389+
}
357390
g_boot_ok=1;
358391
owner.window.rootViewController=front_ios_root();
359392
});
@@ -366,22 +399,22 @@ - (void)sceneWillResignActive:(UIScene *)s {
366399
#ifdef DM_GTA_NATIVE
367400
if(TonTonGTAVIsActive()){TonTonGTAVFocus(0,0);return;}
368401
#endif
369-
front_ios_focus_event(0); }
402+
focus_game(0); }
370403
- (void)sceneDidEnterBackground:(UIScene *)s {
371404
#ifdef DM_GTA_NATIVE
372405
if(TonTonGTAVIsActive()){TonTonGTAVFocus(0,1);return;}
373406
#endif
374-
front_ios_focus_event(1); }
407+
focus_game(1); }
375408
- (void)sceneWillEnterForeground:(UIScene *)s {
376409
#ifdef DM_GTA_NATIVE
377410
if(TonTonGTAVIsActive()){TonTonGTAVFocus(0,0);return;}
378411
#endif
379-
front_ios_focus_event(2); }
412+
focus_game(2); }
380413
- (void)sceneDidBecomeActive:(UIScene *)s {
381414
#ifdef DM_GTA_NATIVE
382415
if(TonTonGTAVIsActive()){TonTonGTAVFocus(1,0);return;}
383416
#endif
384-
front_ios_focus_event(3); }
417+
focus_game(3); }
385418
@end
386419

387420
int main(int argc, char **argv) {

0 commit comments

Comments
 (0)