Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
ff0f3e1
Super Mario 3D All-Stars bring-up, step 1 (WIP): Sunshine (program 2)…
seedds Oct 25, 2026
1ea5382
Super Mario 3D All-Stars bring-up, step 1 (WIP): Sunshine (program 2)…
seedds Oct 25, 2026
fe17c04
Super Mario 3D All-Stars bring-up, step 2 (WIP): the launcher boots o…
seedds Oct 25, 2026
36c539f
3DAS C-1: nn::jit stand-in on the Mac: the game's JIT plugin runs in …
seedds Oct 25, 2026
9e2f3f1
3DAS A-1: Snapshot an attachment a draw samples after its pass alread…
seedds Oct 25, 2026
d2a73be
3DAS B-1: offline HTML pages in a web view on the Mac (Sunshine's pau…
seedds Oct 25, 2026
220b8c3
3DAS B-2: offline HTML pages on the iPhone: the web view over the gam…
seedds Oct 25, 2026
2b3e188
3DAS B: done
seedds Oct 25, 2026
8260253
3DAS A-3: The launcher's profile in dm/games/010049900F546000
seedds Oct 25, 2026
eb12bf1
3DAS A-2: Galaxy's tile in the launcher cannot be started
seedds Oct 25, 2026
e919e73
3DAS A-4: Multi-program applications pack and run on the Mac as one
seedds Oct 25, 2026
fa6b566
3DAS C-1: hle_jit.c compiles for iOS (the code memory pointer was dec…
seedds Oct 25, 2026
13ea3e6
3DAS C-2: Super Mario 64 plays on the Mac: image clears, dynamic sten…
seedds Oct 25, 2026
54719c2
3DAS A-5: One iPhone app holds every packed program of a multi-progra…
seedds Oct 25, 2026
8911b35
3DAS A: done
seedds Oct 25, 2026
892d4aa
3DAS D-1: The iPhone app names the next program and a notification op…
seedds Oct 25, 2026
fa5c838
3DAS C-3: nn::jit without run-time code generation: the plugin's outp…
seedds Oct 25, 2026
3223371
3DAS C-4: Super Mario 64 in the iPhone app: the NSP script captures i…
seedds Oct 25, 2026
b5bbe08
3DAS C-5: Super Mario 3D All-Stars in the docs; the whole path on the…
seedds Oct 25, 2026
791ded6
3DAS D-2: In-process program switch (DM_PROGRAM_SWITCH=inproc): Execu…
seedds Oct 25, 2026
c476c6f
3DAS C-5: docs for D-2's in-process program switch
seedds Oct 25, 2026
b9f42d8
3DAS D-3: The end of a run releases the frame-buffering ring (DM_PRES…
seedds Oct 25, 2026
5e806b2
3DAS D-4: Super Mario 3D All-Stars in upstream's docs layout
seedds Oct 25, 2026
fe2ab89
3DAS E-1: vkDestroyImage of a swap chain image is ignored (the crash …
seedds Oct 25, 2026
98d932d
3DAS E-2: The audio render thread leaves at the end of a run on its o…
seedds Oct 25, 2026
3110fc0
3DAS E-3: The nn::jit image leaves out a capture session that lacks i…
seedds Oct 25, 2026
e6cf16f
3DAS E-4: --prepare-xcode prepares one Xcode project holding every pr…
seedds Oct 25, 2026
2c85925
3DAS E-5: Super Mario 3D All-Stars documented as a collection, and as…
seedds Oct 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
3DAS A-4: Multi-program applications pack and run on the Mac as one
Super Mario 3D All-Stars ran on the Mac only through a chaining script outside the repository (allstars.sh in the NSP folder), after packing each program by hand with --program N.

- build_ipa_from_nsp.py: a Mac build from program 0 (no PROGRAM / --program) packs every program of the application that has a game profile (title ID base + index in dm/games), each into its own work folder from its own profile. That is 0 and 2 today (the launcher and Sunshine), 1 once Super Mario 64 has a profile; Galaxy, 32-bit ARM, has none. PROGRAMS / --programs lists them instead (0,2). Between programs the environment is restored, so one program's provisional or derived profile (DM_GAMES_DIR) does not reach the next. The script then writes programs.tsv in program 0's work folder (per program: its host, rewritten modules, run folder and environment) and prints one run command: program 0's, with DM_PROGRAMS pointing at it. mac_run returns the command's parts besides the command. The iPhone build is unchanged here (A-5).
- The packing now extracts each program's offline HTML pages (nx_extract --html, B-4) into extract/<version>/html beside the RomFS, where the host finds them (hle_offline.c). A program without any gets an html.none marker. The launcher has two, Sunshine has its pause menu.
- hle_oe.c: with DM_PROGRAMS, oe::ExecuteProgram(N) ends the program as Horizon does and starts program N's host in its place. That is an execve after the graceful exit, in its run folder, with this environment less every key a program's row sets, then the row's keys and DM_LAUNCH_PARAM=<run folder>/launch_param.bin holding the parameters. A program with no row is logged and the game carries on, as before. DM_EXEC_OUT stays for whoever runs the programs itself (the iOS app, A-5).
- hle_lifecycle.c: dm_host_shutdown_then runs a last step in place of _exit, also from the 1.5 s fallback. dm_host_shutdown is that with none.
- Tests: t_oe checks the plan for a packed program (host, modules, run folder, launch parameter file, the environment kept, dropped and taken) and that none exists for a program without a row. It checks ExecuteProgram writing the 16 bytes and handing prog_exec to the graceful exit, and carrying on for a program without a row. test_nsp_programs.py (new) checks the program list (profiles, PROGRAMS, a single --program), and that the Mac run over programs 0 and 2 writes programs.tsv rows and one command starting program 0 with DM_PROGRAMS. DM_WINDOW / DM_AUDIO are left to the command, and one program's DM_GAMES_DIR does not reach the next. These tests were written with the code, not before it.

Checked on the Mac: build_ipa_from_nsp.py --platform mac on the NSP folder packed programs 0 and 2 (the launcher's shaders rebuilt in 51 s for its profile's new note). The printed command, run headless and silent, showed the launcher; A on Sunshine logged ExecuteProgram(2), the graceful exit and Sunshine's host in the same process; Sunshine popped the launcher's 16-byte launch parameter and showed its opening. Not run: the way back (Sunshine's pause menu, Return to title selection → ExecuteProgram(0)), which needs B's web view in a window; it takes the same path. allstars.sh in the NSP folder is no longer needed and was left in place. dm/host/tests make run, test_nsp_programs, test_nsp_mac, test_nsp_progress, test_nsp_chain, test_nsp_alias and test_nsp_nsz pass.
  • Loading branch information
seedds committed Oct 25, 2026
commit e919e7367c665fb871a354ffeab3ff918a2ebf47
1 change: 1 addition & 0 deletions dm/host/dm.h
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,4 @@ void dm_gfx_enter(void); void dm_gfx_leave(void); // hle_nvn.c: the gate dm_gf
void dm_gfx_shot_at(long k, const char *path);
void dm_shot_written(const char *path, int ok); // The graphics side finished writing a screenshot to disk (diag.c: DM_TICK_HOLD=E:SHOT unfreezes on this)
void dm_host_shutdown(const char *why); // Graceful exit (crash.c): stop background threads and audio, drain graphics, then _exit(0); used by SIGTERM and the iOS App termination callback // graphics side: screenshot of the k-th frame after the current presented frame (nvn_mtl.m)
void dm_host_shutdown_then(const char *why, void (*then)(void *), void *arg); // the same, then runs then(arg) in place of _exit (hle_oe.c: the next program of DM_PROGRAMS)
7 changes: 5 additions & 2 deletions dm/host/hle_lifecycle.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,20 @@
#include <signal.h>
#include <unistd.h>
void hlecount_flush(void);
void dm_host_shutdown(const char *why) {
// then (oe::ExecuteProgram with DM_PROGRAMS, hle_oe.c): run instead of _exit once the host has stopped, also by the fallback (it starts another program in this process's place)
void dm_host_shutdown_then(const char *why, void (*then)(void *), void *arg) {
static _Atomic int once; if (atomic_exchange(&once, 1)) return;
uint64_t t0 = now_ns(); LOG("received %s: graceful exit", why);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1500 * NSEC_PER_MSEC), dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
LOG("[RED] graceful exit not done in 1.5 seconds, exiting at once"); _exit(0); });
LOG("[RED] graceful exit not done in 1.5 seconds, exiting at once"); if (then) then(arg); _exit(0); });
hlecount_flush(); // DM_HLECOUNT: _exit does not run atexit, write a copy here
dm_audio_suspend(1);
dm_gfx_suspend(1);
LOG("graceful exit done (%.3f s)", (now_ns() - t0) / 1e9);
if (then) then(arg);
_exit(0);
}
void dm_host_shutdown(const char *why) { dm_host_shutdown_then(why, NULL, NULL); }
void dm_term_install(void) {
signal(SIGTERM, SIG_IGN); // do not take the default action: hand over to the GCD signal source to wrap up on an ordinary thread
static dispatch_source_t src;
Expand Down
74 changes: 68 additions & 6 deletions dm/host/hle_oe.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

// The operation mode is runtime state (the front end can change it: iOS overheat downgrade switches to handheld): the single source is here, taken once from DM_OPMODE at startup, the environment variable is not read again afterwards
#include <stdatomic.h>
#include <errno.h>
#include <unistd.h>
static _Atomic int g_opmode = -1;
int dm_opmode(void) {
int m = g_opmode;
Expand Down Expand Up @@ -97,18 +99,78 @@ HLE_FORCE("_ZN2nn2oe21TryPopLaunchParameterEPmPvm", "launch parameter: the bytes
// Tears of the Kingdom (SDK 20.5.22): the index of the program that launched this one in a multi-program application. The SDK asks the applet proxy, which the host never opens
// (null read in applet::GetPreviousProgramIndex right after the window setup); -1 = launched from the home menu
HLE_FORCE("_ZN2nn2oe23GetPreviousProgramIndexEv", "previous program index: launched from HOME, -1", int, h_oe_PrevProgram, void) { return -1; }
// The programs of a multi-program application on the Mac: DM_PROGRAMS=<file> (build_ipa_from_nsp.py writes it beside program 0's work folder) has one row per packed program,
// "<index>\t<KEY=VALUE>\t…": exe= its host, arg= its rewritten modules, cwd= its run folder, and its environment (DM_ROOT, DM_ROMFS, DM_SAVE, DM_MSL_DIR, …). oe::ExecuteProgram
// then ends this program as Horizon does and starts the named one in its place: execve of its host after the graceful exit, with this environment less every key a row sets,
// then the row's keys and DM_LAUNCH_PARAM=<cwd>/launch_param.bin holding the parameters. One run command plays Super Mario 3D All-Stars' menu, the game it starts, and back
typedef struct { const char *exe, *arg, *cwd, *param; char **env; } prog_plan;
static int row_has_key(const char *row, const char *kv) { // the row (tab-separated, its index first) sets the key of kv ("KEY=…")
size_t kl = strcspn(kv, "=");
for (const char *f = strchr(row, '\t'); f && f[1]; f = strchr(f + 1, '\t')) if (!strncmp(f + 1, kv, kl) && f[1 + kl] == '=') return 1;
return 0;
}
// 1 and the plan for program index (out), 0 when no row names it. tsv: the file's text (lines that do not start with a digit are comments); envp: this process's environment
static int prog_plan_make(const char *tsv, int index, char *const *envp, prog_plan *out) {
memset(out, 0, sizeof *out);
char *text = strdup(tsv), *rows[64]; int nr = 0, hit = -1; // text stays allocated: the plan points into it until the execve
for (char *ln = strtok(text, "\n"); ln && nr < 64; ln = strtok(NULL, "\n")) {
size_t n = strlen(ln); if (n && ln[n - 1] == '\r') ln[--n] = 0;
if (*ln < '0' || *ln > '9') continue;
if (atoi(ln) == index) hit = nr;
rows[nr++] = ln;
}
if (hit < 0) { free(text); return 0; }
size_t ne = 0; while (envp && envp[ne]) ne++;
char **env = calloc(ne + 66, sizeof *env); size_t k = 0;
for (size_t i = 0; i < ne; i++) { // this environment, less the old launch parameter and every key a program's row sets (the old program's own, such as DM_AOC_DIR)
int set = !strncmp(envp[i], "DM_LAUNCH_PARAM=", 16);
for (int r = 0; r < nr && !set; r++) set = row_has_key(rows[r], envp[i]);
if (!set) env[k++] = envp[i];
}
int field = 0;
for (char *f = strtok(rows[hit], "\t"); f; f = strtok(NULL, "\t")) {
if (!field++) continue; // the index
if (!strncmp(f, "exe=", 4)) out->exe = f + 4;
else if (!strncmp(f, "arg=", 4)) out->arg = f + 4;
else if (!strncmp(f, "cwd=", 4)) out->cwd = f + 4;
else if (strchr(f, '=') && k < ne + 64) env[k++] = f;
}
if (!out->exe || !out->arg || !out->cwd) { free(env); free(text); memset(out, 0, sizeof *out); return 0; }
char *pp = malloc(strlen(out->cwd) + 20); sprintf(pp, "%s/launch_param.bin", out->cwd); out->param = pp;
char *pe = malloc(strlen(pp) + 17); sprintf(pe, "DM_LAUNCH_PARAM=%s", pp); env[k++] = pe; env[k] = NULL;
out->env = env;
return 1;
}
static void prog_exec(void *p) {
const prog_plan *P = p; char *argv[] = {(char *)P->exe, (char *)P->arg, NULL};
if (chdir(P->cwd)) LOG("[RED] oe::ExecuteProgram: cannot enter %s", P->cwd);
execve(P->exe, argv, P->env);
LOG("[RED] oe::ExecuteProgram: cannot start %s (errno %d)", P->exe, errno);
}
// Launch another program of a multi-program application (Octopath Traveler 0 imports it); on hardware it does not return: this process ends and the other program starts with the
// parameters as its launch parameter (TryPopLaunchParameter). With DM_EXEC_OUT=<file> the host does the same: it writes the program index (4 bytes, little-endian) and the
// parameters to that file and exits, and whoever started it starts the program (Super Mario 3D All-Stars' menu hands each game 16 bytes, its LanguageCode and two volumes).
// Without it the host has only this program: logged, and the game carries on
HLE_FORCE("_ZN2nn2oe14ExecuteProgramEiPKvm", "launch another program of the application: with DM_EXEC_OUT, written there and the process ends; else logged", void, h_oe_ExecProgram, int index, const void *param, size_t n) {
// parameters as its launch parameter (TryPopLaunchParameter). With DM_PROGRAMS the host starts it itself (above). With DM_EXEC_OUT=<file> (the iOS app's Documents, main.m) it writes
// the program index (4 bytes, little-endian) and the parameters to that file and exits, and whoever starts it next starts that program (Super Mario 3D All-Stars' menu hands each
// game 16 bytes, its LanguageCode and two volumes). Without either the host has only this program: logged, and the game carries on
HLE_FORCE("_ZN2nn2oe14ExecuteProgramEiPKvm", "launch another program of the application: DM_PROGRAMS starts it in this process's place, DM_EXEC_OUT records it and the process ends; else logged", void, h_oe_ExecProgram, int index, const void *param, size_t n) {
char hex[3 * 32 + 1] = ""; for (size_t i = 0; i < n && i < 32; i++) snprintf(hex + 3 * i, 4, " %02x", ((const uint8_t *)param)[i]);
const char *pf = getenv("DM_PROGRAMS");
if (pf && *pf) {
static prog_plan P; char *tsv = NULL; FILE *fp = fopen(pf, "rb");
if (fp) { fseek(fp, 0, SEEK_END); long sz = ftell(fp); fseek(fp, 0, SEEK_SET); tsv = calloc(1, (size_t)sz + 1); if (fread(tsv, 1, (size_t)sz, fp) != (size_t)sz) { free(tsv); tsv = NULL; } fclose(fp); }
extern char **environ;
if (!tsv || !prog_plan_make(tsv, index, environ, &P)) { LOG("[RED] oe::ExecuteProgram(%d, %zu bytes of parameters:%s): DM_PROGRAMS %s has no program %d; the game carries on", index, n, hex, pf, index); free(tsv); return; }
FILE *po = fopen(P.param, "wb");
if (!po || (n && fwrite(param, n, 1, po) != 1) || fclose(po)) { LOG("[RED] oe::ExecuteProgram(%d): cannot write %s; the game carries on", index, P.param); if (po) fclose(po); return; }
LOG("oe::ExecuteProgram(%d, %zu bytes of parameters:%s): this program ends, %s %s starts in %s", index, n, hex, P.exe, P.arg, P.cwd);
dm_host_shutdown_then("ExecuteProgram", prog_exec, &P);
return;
}
const char *f = getenv("DM_EXEC_OUT");
if (!f || !*f) { LOG("[RED] oe::ExecuteProgram(%d, %zu bytes of parameters:%s): the host runs only this program; the game carries on (DM_EXEC_OUT=<file> hands it over)", index, n, hex); return; }
if (!f || !*f) { LOG("[RED] oe::ExecuteProgram(%d, %zu bytes of parameters:%s): the host runs only this program; the game carries on (DM_PROGRAMS or DM_EXEC_OUT=<file> hands it over)", index, n, hex); return; }
FILE *fp = fopen(f, "wb"); int32_t ix = index;
if (!fp || fwrite(&ix, 4, 1, fp) != 1 || (n && fwrite(param, n, 1, fp) != 1) || fclose(fp)) { LOG("[RED] oe::ExecuteProgram(%d): cannot write DM_EXEC_OUT %s; the game carries on", index, f); if (fp) fclose(fp); return; }
LOG("oe::ExecuteProgram(%d, %zu bytes of parameters:%s) → %s; this program ends", index, n, hex, f);
void dm_host_shutdown(const char *why); dm_host_shutdown("ExecuteProgram");
dm_host_shutdown("ExecuteProgram");
}
HLE_FORCE("_ZN2nn2oe16DisableRecordingEv", "video recording switch; the host has no system recording", void, h_oe_DisableRec, void) {}
// Silence the game's sound in system video captures (through am; FINAL FANTASY RESONANCE imports both): the host records nothing
Expand Down
22 changes: 22 additions & 0 deletions dm/host/tests/t_oe.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ void dm_audio_suspend(int on) { (void)on; } // stubs for the bg item of DM_OE_
void guest_clock_freeze_for(int reason, int on) { (void)reason; (void)on; }
void dm_gfx_suspend(int on) { (void)on; }
void dm_host_shutdown(const char *why) { (void)why; } // hle_lifecycle.c: oe::ExecuteProgram with DM_EXEC_OUT ends the process
static void (*g_then)(void *); static void *g_then_arg; // what oe::ExecuteProgram with DM_PROGRAMS hands the graceful exit (prog_exec and its plan)
void dm_host_shutdown_then(const char *why, void (*then)(void *), void *arg) { (void)why; g_then = then; g_then_arg = arg; }
static int env_has(char **env, const char *kv) { for (; env && *env; env++) if (!strcmp(*env, kv)) return 1; return 0; }
static int env_key(char **env, const char *k) { size_t n = strlen(k); for (; env && *env; env++) if (!strncmp(*env, k, n) && (*env)[n] == '=') return 1; return 0; }
// The notification event (hle_thread.c binds a kernel event): the unit test only tracks whether it is signalled
static int ev_bound, ev_sig;
void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; ev_bound = 1; }
Expand Down Expand Up @@ -123,5 +127,23 @@ int main(void) {
CHECK(pop_is(15) && empty(), "focus mode 2: focus notification 15");
h_oe_SetFocusMode(1); dm_focus_set(2);
CHECK(pop_is(15) && empty(), "focus mode 1: focus notification 15");
// DM_PROGRAMS (the Mac's multi-program run): the plan for the named program, its environment less every key a program's row sets, and the launch parameter in its run folder
{ const char *tsv = "# programs\n0\texe=/h0\targ=/p0\tcwd=/r0\tDM_ROOT=/b0\tDM_AOC_DIR=/a0\n2\texe=/h2\targ=/p2\tcwd=/r2\tDM_ROOT=/b2\tDM_LANG=en-US\n";
char *envp[] = {"PATH=/bin", "DM_ROOT=/old", "DM_AOC_DIR=/aoc", "DM_LAUNCH_PARAM=/x", "DM_WINDOW=1", NULL}; prog_plan P;
CHECK(prog_plan_make(tsv, 2, envp, &P) && !strcmp(P.exe, "/h2") && !strcmp(P.arg, "/p2") && !strcmp(P.cwd, "/r2") && !strcmp(P.param, "/r2/launch_param.bin"), "DM_PROGRAMS: program 2's host, modules, run folder and launch parameter file");
CHECK(env_has(P.env, "PATH=/bin") && env_has(P.env, "DM_WINDOW=1") && env_has(P.env, "DM_ROOT=/b2") && env_has(P.env, "DM_LANG=en-US") && env_has(P.env, "DM_LAUNCH_PARAM=/r2/launch_param.bin"), "DM_PROGRAMS: the environment keeps what no row sets and takes the row's keys");
CHECK(!env_has(P.env, "DM_ROOT=/old") && !env_key(P.env, "DM_AOC_DIR") && !env_has(P.env, "DM_LAUNCH_PARAM=/x"), "DM_PROGRAMS: another program's keys (DM_AOC_DIR) and the old launch parameter are dropped");
CHECK(!prog_plan_make(tsv, 3, envp, &P) && !prog_plan_make("# none\n", 0, envp, &P), "DM_PROGRAMS: no row for program 3 (not packed): no plan");
char dir[] = "/tmp/t_oe_XXXXXX"; CHECK(mkdtemp(dir) != NULL, "temporary folder");
char tf[256], row[1024]; snprintf(tf, sizeof tf, "%s/programs.tsv", dir); snprintf(row, sizeof row, "0\texe=/h0\targ=/p0\tcwd=%s\tDM_ROOT=/b0\n", dir);
FILE *f = fopen(tf, "w"); fputs(row, f); fclose(f); setenv("DM_PROGRAMS", tf, 1);
g_then = NULL; h_oe_ExecProgram(3, "abc", 3);
CHECK(!g_then, "ExecuteProgram(3) with no row: logged, the game carries on (no exit)");
static const uint8_t prm[16] = {'e', 'n', '-', 'U', 'S', 0, 0, 0, 0x33, 0x33, 0xb3, 0x3e, 0x33, 0x33, 0x33, 0x3f};
h_oe_ExecProgram(0, prm, sizeof prm);
char pp[300]; snprintf(pp, sizeof pp, "%s/launch_param.bin", dir); uint8_t got[32] = {0}; size_t gn = 0; f = fopen(pp, "rb"); if (f) { gn = fread(got, 1, sizeof got, f); fclose(f); }
CHECK(g_then == prog_exec && g_then_arg && !strcmp(((prog_plan *)g_then_arg)->exe, "/h0"), "ExecuteProgram(0): the graceful exit then starts program 0's host");
CHECK(gn == sizeof prm && !memcmp(got, prm, sizeof prm), "ExecuteProgram(0): its 16 bytes of parameters are in <cwd>/launch_param.bin");
unlink(pp); unlink(tf); rmdir(dir); unsetenv("DM_PROGRAMS"); }
printf("== oe %d checks, %d failed ==\n", checks, fails); return fails != 0;
}
74 changes: 74 additions & 0 deletions dm/tools/tests/test_nsp_programs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""NSP script, multi-program applications (scripts/build_ipa_from_nsp.py program_list / main): which programs are packed together (PROGRAMS / --programs, else 0 and every program
whose title ID, base + index, has a game profile), and on the Mac the programs.tsv the host reads (DM_PROGRAMS, hle_oe.c) and the one run command over them.
No game files, keys or Xcode needed (temporary files only in a temporary folder)."""
import importlib.util
from pathlib import Path
import os
import shutil
import sys
import tempfile
import types
import unittest
from unittest import mock

REPO = Path(__file__).resolve().parents[3]
SCRIPT = REPO / 'scripts/build_ipa_from_nsp.py'
spec = importlib.util.spec_from_file_location('build_ipa_from_nsp', SCRIPT)
nsp = importlib.util.module_from_spec(spec); spec.loader.exec_module(nsp)
APP = 0x010049900F546000


class Programs(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp()); self.addCleanup(shutil.rmtree, self.tmp)
fake = types.ModuleType('game'); fake.by_title = lambda t: object() if t in (APP, APP + 2) else None # profiles of programs 0 and 2 (3D All-Stars' launcher and Sunshine)
for cm in (mock.patch.dict(sys.modules, {'game': fake}), mock.patch.object(nsp, 'scan_nsps', lambda d: (APP, {})), mock.patch.object(nsp, 'PROGRAM', 0),
mock.patch.object(nsp, 'PROGRAMS', ''), mock.patch.object(nsp, 'PROG', mock.Mock()), mock.patch.object(nsp, 'say', lambda m: None)):
cm.__enter__(); self.addCleanup(cm.__exit__, None, None, None)

def plist(self, programs=None):
return nsp.program_list(types.SimpleNamespace(programs=programs), self.tmp, REPO)

def test_profiles(self): # 0 and every program with a profile; Galaxy (3) and Super Mario 64 (1) have none here
self.assertEqual(self.plist(), [0, 2])

def test_option(self):
self.assertEqual(self.plist('2'), [0, 2])
self.assertEqual(self.plist('0, 1,2'), [0, 1, 2])
self.assertIsNone(self.plist('0')) # one program: packed as before
for bad in ('x', '0,16'):
with self.assertRaises(nsp.BuildError): self.plist(bad)

def test_one_program_by_index(self): # PROGRAM / --program N packs that program alone
with mock.patch.object(nsp, 'PROGRAM', 2): self.assertIsNone(self.plist())

def test_mac_run_over_programs(self): # each program packed from its own profile, then programs.tsv and one command that starts program 0 with DM_PROGRAMS
seen = []
def pack_one(args, multi=False):
seen.append((nsp.PROGRAM, multi, os.environ.get('DM_GAMES_DIR')))
os.environ['DM_GAMES_DIR'] = f'/provisional/{nsp.PROGRAM}' # what a provisional profile's run sets: must not reach the next program
b = self.tmp / f'{APP + nsp.PROGRAM:016X}_build'; (b / 'run').mkdir(parents=True)
env = {'DM_ROOT': b, 'DM_ROMFS': b / 'extract/v0/RomFS', 'DM_LANG': 'en-US', 'DM_WINDOW': 1, 'DM_AUDIO': 1}
if nsp.PROGRAM == 0: env['DM_NVN_SHMAP'] = REPO / 'dm/games/010049900F546000/shader_map.tsv'
return {'cmd': f'cd {b / "run"} && DM_ROOT={b} {b / "tools/dmhost"} {b / "patched_v0"}', 'env': env, 'host': b / 'tools/dmhost', 'arg': b / 'patched_v0', 'cwd': b / 'run'}
out = []
args = nsp.parse_args([str(self.tmp), '--platform', 'mac'])
with mock.patch.object(nsp, 'pack_one', pack_one), mock.patch.dict(os.environ, {}, clear=False), mock.patch.object(nsp.PROG, 'say', out.append):
os.environ.pop('DM_GAMES_DIR', None)
runs = nsp.main(args)
self.assertEqual([s[:2] for s in seen], [(0, True), (2, True)])
self.assertEqual([s[2] for s in seen], [None, None])
tsv = self.tmp / f'{APP:016X}_build/programs.tsv'
rows = [l.split('\t') for l in tsv.read_text().splitlines() if not l.startswith('#')]
self.assertEqual([r[0] for r in rows], ['0', '2'])
b2 = self.tmp / f'{APP + 2:016X}_build'
self.assertEqual(rows[1][1:4], [f'exe={b2 / "tools/dmhost"}', f'arg={b2 / "patched_v0"}', f'cwd={b2 / "run"}'])
self.assertIn('DM_LANG=en-US', rows[1]); self.assertIn(f'DM_ROOT={b2}', rows[1])
self.assertFalse(any(f.startswith(('DM_WINDOW=', 'DM_AUDIO=')) for r in rows for f in r)) # the run command's own switches, inherited
self.assertTrue(any(f.startswith('DM_NVN_SHMAP=') for f in rows[0])); self.assertFalse(any(f.startswith('DM_NVN_SHMAP=') for f in rows[1]))
self.assertEqual(len(out), 1); self.assertIn(f'&& DM_PROGRAMS={tsv} DM_ROOT=', out[0]); self.assertTrue(out[0].startswith(f'cd {self.tmp / f"{APP:016X}_build/run"} && '))
self.assertEqual(sorted(runs), [0, 2])


if __name__ == '__main__':
unittest.main()
Loading