From 5881a8514184cf04030dfc7d15b0ca1cf3f532e6 Mon Sep 17 00:00:00 2001 From: HugeFrog24 <62775760+HugeFrog24@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:58:28 +0100 Subject: [PATCH] Handle process restoration and initialize native mods once Return restored game and stale bootstrap activities to the mod manager before accessing process-scoped resources. Guard incomplete lifecycle callbacks and publish the native mod registry only after initialization completes. Report required directory and library failures, resolve mods by path, close map readers, and reuse the existing static scanner. Add regression tests for restoration, loading, and initialization. Validated with 103 Java tests, four native tests, and OnePlus Android 16 process-death and repeated-Play checks. --- .../main/cpp/Core/Canvas/InitializationGate.h | 32 +++ app/src/main/cpp/include/misc/Utils.h | 4 +- app/src/main/cpp/main.cpp | 29 ++- .../main/java/com/tgc/sky/GameActivity.java | 26 +- .../java/com/tgc/sky/TGCNativeActivity.java | 48 ++-- .../git/artdeell/skymodloader/ElfLoader.java | 126 ++++++---- .../artdeell/skymodloader/GameRuntime.java | 73 ++++++ .../artdeell/skymodloader/MainActivity.java | 232 +++++++++--------- .../elfmod/ElfRefcountLoader.java | 44 +++- .../elfmod/ModManagerActivity.java | 2 +- app/src/test/cpp/CMakeLists.txt | 8 + app/src/test/cpp/InitializationGateTest.cpp | 59 +++++ .../tgc/sky/GameActivityRestorationTest.java | 56 +++++ .../artdeell/skymodloader/ElfLoaderTest.java | 103 ++++++++ .../skymodloader/GameRuntimeTest.java | 107 ++++++++ .../elfmod/ElfRefcountLoaderTest.java | 112 +++++++++ 16 files changed, 869 insertions(+), 192 deletions(-) create mode 100644 app/src/main/cpp/Core/Canvas/InitializationGate.h create mode 100644 app/src/main/java/git/artdeell/skymodloader/GameRuntime.java create mode 100644 app/src/test/cpp/InitializationGateTest.cpp create mode 100644 app/src/test/java/com/tgc/sky/GameActivityRestorationTest.java create mode 100644 app/src/test/java/git/artdeell/skymodloader/ElfLoaderTest.java create mode 100644 app/src/test/java/git/artdeell/skymodloader/GameRuntimeTest.java create mode 100644 app/src/test/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoaderTest.java diff --git a/app/src/main/cpp/Core/Canvas/InitializationGate.h b/app/src/main/cpp/Core/Canvas/InitializationGate.h new file mode 100644 index 0000000..328b9f0 --- /dev/null +++ b/app/src/main/cpp/Core/Canvas/InitializationGate.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +namespace Canvas { + +// Registry writes belong to the bootstrap thread, before publication to native readers. +class InitializationGate { + enum class State { New, Loading, Ready }; + std::atomic state{State::New}; + +public: + bool begin() { + State expected = State::New; + return state.compare_exchange_strong(expected, State::Loading); + } + + bool isLoading() const { + return state.load(std::memory_order_acquire) == State::Loading; + } + + bool publish() { + State expected = State::Loading; + return state.compare_exchange_strong(expected, State::Ready); + } + + bool isReady() const { + return state.load(std::memory_order_acquire) == State::Ready; + } +}; + +} diff --git a/app/src/main/cpp/include/misc/Utils.h b/app/src/main/cpp/include/misc/Utils.h index 0ee361d..9cd91e8 100644 --- a/app/src/main/cpp/include/misc/Utils.h +++ b/app/src/main/cpp/include/misc/Utils.h @@ -77,9 +77,9 @@ bool isLibraryLoaded(const char *libraryName) { FILE *fp = fopen(OBFUSCATE("/proc/self/maps"), OBFUSCATE("rt")); if (fp != NULL) { while (fgets(line, sizeof(line), fp)) { - std::string a = line; if (strstr(line, libraryName)) { libLoaded = true; + fclose(fp); return true; } } @@ -110,4 +110,4 @@ uintptr_t string2Offset(const char *c) { namespace ToastLength { inline const int LENGTH_LONG = 1; inline const int LENGTH_SHORT = 0; -} \ No newline at end of file +} diff --git a/app/src/main/cpp/main.cpp b/app/src/main/cpp/main.cpp index 0c5dea7..a2574c4 100644 --- a/app/src/main/cpp/main.cpp +++ b/app/src/main/cpp/main.cpp @@ -16,6 +16,7 @@ #include #include #include "Canvas/Canvas.h" +#include "Canvas/InitializationGate.h" #include "Cipher/CipherUtils.h" #include "Cipher/Cipher.h" #include "include/misc/visibility.h" @@ -31,6 +32,7 @@ extern "C" { } static std::string g_skyBuildKey; +static Canvas::InitializationGate g_modInitialization; void fsel_setup(JNIEnv*); @@ -171,6 +173,7 @@ PRIVATE_API void DrawMods() { } PRIVATE_API void Canvas::CanvasMenu() { + if (!g_modInitialization.isReady()) return; ImGui::GetStyle() = canvasBaseStyle; if(Canvas::hideCanvasMenu) { @@ -256,8 +259,12 @@ Java_git_artdeell_skymodloader_MainActivity_settle( jboolean _ceserver_enabled, jboolean _hideCanvasMenu ) { + if (!g_modInitialization.begin()) { + jclass error = env->FindClass("java/lang/IllegalStateException"); + if (error != nullptr) env->ThrowNew(error, "Native game initialization already started"); + return; + } fsel_setup(env); - Canvas::userLibs.clear(); Canvas::MainActivity = clazz; Canvas::CeserverEnabled = _ceserver_enabled; Canvas::hideCanvasMenu = _hideCanvasMenu; @@ -293,7 +300,7 @@ PRIVATE_API void *UserThread(Canvas::UserLib *pUserLib){ return nullptr; } -PRIVATE_API void crash(JNIEnv *env, char* crashReason) { +PRIVATE_API void crash(JNIEnv *env, const char* crashReason) { jclass exception = env->FindClass("java/lang/Exception"); if(exception != nullptr) { env->ThrowNew(exception, crashReason); @@ -313,7 +320,10 @@ Java_git_artdeell_skymodloader_LibrarySelectorListener_onModLibrary( jstring _version, jboolean _selfManagedUI ) { - + if (!g_modInitialization.isLoading()) { + crash(env, "Mod registration outside initialization"); + return; + } const char *temp = env->GetStringUTFChars(_path, 0); void *dl_entry = dlopen(temp, RTLD_LOCAL); if(dl_entry == nullptr) { @@ -376,9 +386,18 @@ Java_git_artdeell_skymodloader_MainActivity_setDeviceInfoNative( Canvas::deviceInfo.deviceModel = env->GetStringUTFChars(_model, nullptr); } +extern "C" +JNIEXPORT void JNICALL +Java_git_artdeell_skymodloader_MainActivity_completeModInitialization(JNIEnv *env, jclass clazz) { + if (!g_modInitialization.publish()) { + crash(env, "Invalid native initialization state"); + } +} + extern "C" JNIEXPORT void JNICALL Java_git_artdeell_skymodloader_MainActivity_lateInitUserLibs(JNIEnv *env, jclass clazz) { + if (!g_modInitialization.isReady()) return; std::thread lateInitThread([]() -> void { for (auto& userlib : Canvas::userLibs) { if (userlib.InitLate != nullptr) { @@ -395,8 +414,8 @@ Java_git_artdeell_skymodloader_MainActivity_lateInitUserLibs(JNIEnv *env, jclass extern "C" JNIEXPORT void JNICALL Java_git_artdeell_skymodloader_MainActivity_customServer(JNIEnv *env, jclass clazz, jstring url) { - uintptr_t ssl = (new CipherUtils())->CipherScan("\\x00\\x00\\x00\\x52\\xE2\\x03\\x1F\\xAA\\x00\\x00\\x00\\x94\\x00\\x00\\x00\\xF9\\x00\\x00\\x00\\x52", "???xxxxx???x???x???x"); - LOGD("scanner %p", ssl); + uintptr_t ssl = CipherUtils::CipherScan("\\x00\\x00\\x00\\x52\\xE2\\x03\\x1F\\xAA\\x00\\x00\\x00\\x94\\x00\\x00\\x00\\xF9\\x00\\x00\\x00\\x52", "???xxxxx???x???x???x"); + LOGD("scanner %p", reinterpret_cast(ssl)); } extern "C" diff --git a/app/src/main/java/com/tgc/sky/GameActivity.java b/app/src/main/java/com/tgc/sky/GameActivity.java index 2827de5..182d311 100644 --- a/app/src/main/java/com/tgc/sky/GameActivity.java +++ b/app/src/main/java/com/tgc/sky/GameActivity.java @@ -231,6 +231,7 @@ private void fixTextRenderingOnProblemDevices_HACK() { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); + if (!hasNativeActivity()) return; DialogJNI.setActivity(this); hideNavigationFullScreen(getWindow().getDecorView()); getWindow().addFlags(2097280); @@ -319,7 +320,7 @@ private void setupDisplayListener() { @Override public void onDisplayAdded(int i) {} @Override public void onDisplayRemoved(int i) {} @Override public void onDisplayChanged(int i) { - if (displayManager.getDisplay(i) != null) GameActivity.this.onDisplayChangedNative(); + if (hasNativeActivity() && displayManager.getDisplay(i) != null) GameActivity.this.onDisplayChangedNative(); } }, null); } @@ -328,14 +329,20 @@ private void setupDisplayListener() { @Override public void onDestroy() { - FMOD.close(); - FileSelector.unsetActivity(); - this.m_systemIO.onDestroy(); + if (hasNativeActivity()) { + FMOD.close(); + FileSelector.unsetActivity(); + } + if (this.m_systemIO != null) this.m_systemIO.onDestroy(); super.onDestroy(); } @Override public void onResume() { + if (!hasNativeActivity()) { + super.onResume(); + return; + } if (this.m_sensorManager != null && this.m_motionListening) { this.m_motionListening = registerMotionListeners(); } @@ -353,6 +360,10 @@ public void onResume() { @Override public void onPause() { + if (!hasNativeActivity()) { + super.onPause(); + return; + } if (this.portraitOnResume) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); this.m_systemIO.onPause(); if (this.m_sensorManager != null && this.m_motionListening) { @@ -530,7 +541,10 @@ public void onWindowFocusChanged(boolean z) { } @Override - public void onBackPressed() { onBackPressedNative(); } + public void onBackPressed() { + if (hasNativeActivity()) onBackPressedNative(); + else super.onBackPressed(); + } public void AddOnActivityIntentListener(OnActivityIntentListener l) { if (this.mOnActivityIntentListeners == null) this.mOnActivityIntentListeners = new ArrayList<>(); @@ -544,6 +558,8 @@ public void RemoveOnActivityIntentListeners(OnActivityIntentListener l) { @Override public void onNewIntent(Intent intent) { + super.onNewIntent(intent); + if (!hasNativeActivity()) return; ArrayList a = this.mOnActivityIntentListeners; if (a != null) { Iterator it = a.iterator(); diff --git a/app/src/main/java/com/tgc/sky/TGCNativeActivity.java b/app/src/main/java/com/tgc/sky/TGCNativeActivity.java index 1b66b22..62c274d 100644 --- a/app/src/main/java/com/tgc/sky/TGCNativeActivity.java +++ b/app/src/main/java/com/tgc/sky/TGCNativeActivity.java @@ -11,6 +11,7 @@ import java.io.File; import git.artdeell.skymodloader.SMLApplication; +import git.artdeell.skymodloader.GameRuntime; /* loaded from: classes2.dex */ public abstract class TGCNativeActivity extends Activity implements SurfaceHolder.Callback2, ViewTreeObserver.OnGlobalLayoutListener { @@ -21,6 +22,7 @@ public abstract class TGCNativeActivity extends Activity implements SurfaceHolde int m_lastContentX; int m_lastContentY; private boolean m_destroyed = false; + private boolean m_nativeCreated = false; private long m_handle = 0; final int[] m_location = new int[2]; @@ -57,12 +59,27 @@ public abstract class TGCNativeActivity extends Activity implements SurfaceHolde @Override // android.app.Activity public void onCreate(Bundle bundle) { super.onCreate(bundle); + if (!GameRuntime.isReady()) { + GameRuntime.returnToManager(this); + return; + } findViewById(android.R.id.content).getRootView().getViewTreeObserver().addOnGlobalLayoutListener(this); this.m_handle = onCreateNative(getAbsolutePath(getFilesDir()), getAbsolutePath(getObbDir()), getAbsolutePath(getExternalFilesDir(null)), Build.VERSION.SDK_INT, SMLApplication.skyRes.getAssets(), bundle != null ? bundle.getByteArray(KEY_NATIVE_SAVED_STATE) : null); + m_nativeCreated = true; + } + + protected final boolean hasNativeActivity() { + return m_nativeCreated && !m_destroyed; } @Override public void onDestroy() { + if (!hasNativeActivity()) { + m_destroyed = true; + super.onDestroy(); + return; + } + findViewById(android.R.id.content).getRootView().getViewTreeObserver().removeOnGlobalLayoutListener(this); git.artdeell.skymodloader.AccountStorage.saveActive(this); this.m_destroyed = true; SurfaceHolder surfaceHolder = this.m_currentSurfaceHolder; @@ -71,25 +88,28 @@ public void onDestroy() { this.m_currentSurfaceHolder = null; } onDestroyNative(this.m_handle); + m_nativeCreated = false; + m_handle = 0; super.onDestroy(); } @Override public void onPause() { - git.artdeell.skymodloader.AccountStorage.saveActive(this); + if (hasNativeActivity()) git.artdeell.skymodloader.AccountStorage.saveActive(this); super.onPause(); - onPauseNative(this.m_handle); + if (hasNativeActivity()) onPauseNative(this.m_handle); } @Override public void onResume() { super.onResume(); - onResumeNative(this.m_handle); + if (hasNativeActivity()) onResumeNative(this.m_handle); } @Override protected void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); + if (!hasNativeActivity()) return; byte[] onSaveInstanceStateNative = onSaveInstanceStateNative(this.m_handle); if (onSaveInstanceStateNative != null) { bundle.putByteArray(KEY_NATIVE_SAVED_STATE, onSaveInstanceStateNative); @@ -99,20 +119,20 @@ protected void onSaveInstanceState(Bundle bundle) { @Override protected void onStart() { super.onStart(); - onStartNative(this.m_handle); + if (hasNativeActivity()) onStartNative(this.m_handle); } @Override protected void onStop() { - git.artdeell.skymodloader.AccountStorage.saveActive(this); + if (hasNativeActivity()) git.artdeell.skymodloader.AccountStorage.saveActive(this); super.onStop(); - onStopNative(this.m_handle); + if (hasNativeActivity()) onStopNative(this.m_handle); } @Override // android.app.Activity, android.content.ComponentCallbacks public void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } onConfigurationChangedNative(this.m_handle); @@ -121,7 +141,7 @@ public void onConfigurationChanged(Configuration configuration) { @Override // android.app.Activity, android.content.ComponentCallbacks public void onLowMemory() { super.onLowMemory(); - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } onLowMemoryNative(this.m_handle); @@ -130,7 +150,7 @@ public void onLowMemory() { @Override // android.app.Activity, android.view.Window.Callback public void onWindowFocusChanged(boolean z) { super.onWindowFocusChanged(z); - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } onWindowFocusChangedNative(this.m_handle, z); @@ -138,7 +158,7 @@ public void onWindowFocusChanged(boolean z) { @Override // android.view.SurfaceHolder.Callback public void surfaceCreated(SurfaceHolder surfaceHolder) { - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } this.m_currentSurfaceHolder = surfaceHolder; @@ -147,7 +167,7 @@ public void surfaceCreated(SurfaceHolder surfaceHolder) { @Override // android.view.SurfaceHolder.Callback public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } this.m_currentSurfaceHolder = surfaceHolder; @@ -156,7 +176,7 @@ public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { @Override // android.view.SurfaceHolder.Callback2 public void surfaceRedrawNeeded(SurfaceHolder surfaceHolder) { - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } this.m_currentSurfaceHolder = surfaceHolder; @@ -166,7 +186,7 @@ public void surfaceRedrawNeeded(SurfaceHolder surfaceHolder) { @Override // android.view.SurfaceHolder.Callback public void surfaceDestroyed(SurfaceHolder surfaceHolder) { this.m_currentSurfaceHolder = null; - if (this.m_destroyed) { + if (!hasNativeActivity()) { return; } onSurfaceDestroyedNative(this.m_handle, surfaceHolder.getSurface()); @@ -186,7 +206,7 @@ public void onGlobalLayout() { this.m_lastContentY = i2; this.m_lastContentWidth = width; this.m_lastContentHeight = height; - if (!this.m_destroyed) { + if (hasNativeActivity()) { onContentRectChangedNative(this.m_handle, i, i2, width, height); } } diff --git a/app/src/main/java/git/artdeell/skymodloader/ElfLoader.java b/app/src/main/java/git/artdeell/skymodloader/ElfLoader.java index a2570fe..12760f2 100644 --- a/app/src/main/java/git/artdeell/skymodloader/ElfLoader.java +++ b/app/src/main/java/git/artdeell/skymodloader/ElfLoader.java @@ -9,65 +9,101 @@ import java.io.BufferedReader; import java.io.File; +import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; +import java.io.Reader; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; public class ElfLoader { - final List alreadyLoadedLibs = new ArrayList<>(); - final List> dirCache = new ArrayList<>(); //Directory cache - here are all the files in loader path. Well, they would appear there after class' construction - /* - * Constructs an ElfSequencer with specified search paths. Search paths should be a list of directory paths separated by : - */ - public ElfLoader(String libraryPaths) throws IOException{ - for(String path : libraryPaths.split(":")) { - ArrayMap caching = new ArrayMap<>(); - File[] filesInDir = new File(path).listFiles((pathname)->pathname.isFile() && pathname.exists()); - if(filesInDir != null) { - for (File file : filesInDir) { - caching.put(file.getName(), file); + private final Set loadedPaths = new HashSet<>(); + private final Set mappedPaths = new HashSet<>(); + private final Set mappedNames = new HashSet<>(); + private final List> dirCache = new ArrayList<>(); + + public ElfLoader(String libraryPaths) throws IOException { + this(libraryPaths, new FileReader("/proc/self/maps")); + } + + protected ElfLoader(String libraryPaths, Reader processMaps) throws IOException { + try (BufferedReader maps = new BufferedReader(processMaps)) { + for (String path : libraryPaths.split(File.pathSeparator)) { + ArrayMap cache = new ArrayMap<>(); + for (File file : listRequiredFiles(new File(path), "SEARCH_PATH_UNAVAILABLE", + File::isFile)) { + cache.put(file.getName(), file); } - dirCache.add(caching); - }else{ - Log.w("ElfLoader","Omitted directory during initialization: "+path); + dirCache.add(cache); } - } - BufferedReader selfMapsReader = new BufferedReader(new FileReader(new File("/proc/self/maps"))); - String mapLine = null; - while((mapLine = selfMapsReader.readLine()) != null) { - if(mapLine.endsWith(".so")) { - String map = mapLine.substring(mapLine.lastIndexOf("/")+1); - addLoaded(map); + String line; + while ((line = maps.readLine()) != null) { + String[] fields = line.trim().split("\\s+", 6); + if (fields.length == 6 && fields[5].endsWith(".so")) { + File library = new File(fields[5]); + mappedPaths.add(library.getCanonicalPath()); + mappedNames.add(library.getName()); + } } } } - private void addLoaded(String libName) { - if(!alreadyLoadedLibs.contains(libName)) { - alreadyLoadedLibs.add(libName); + + protected static File[] listRequiredFiles(File directory, String stage, FileFilter filter) + throws IOException { + File[] files = directory.listFiles(filter); + if (files == null) { + Log.e("ElfLoader", stage + ": " + directory.getAbsolutePath()); + throw new IOException("Cannot list directory: " + directory.getAbsolutePath()); } + return files; } - /* - * Loads a library by it's name, searching in the specified search paths. - */ - public void loadLib(String libName) throws IOException { - if(alreadyLoadedLibs.contains(libName)) - return; - File library = getLibrary(libName); - if(library == null) { - Log.w("ElfSequencer","Library " +libName + " not found in search paths"); - return; + + /** Explicit requests must resolve; only transitive linker dependencies may be deferred. */ + public void loadLib(String name) throws IOException { + File library = getLibrary(name); + if (library == null) { + Log.e("ElfLoader", "LIB_NOT_IN_SEARCH_PATHS: " + name); + throw new IOException("Library not found: " + name); } - ElfFile file = ElfFile.from(library); - ElfDynamicSection section = file.firstSectionByType(ElfDynamicSection.class); - List needed = section.getNeededLibraries(); - for(String neededLibrary : needed) { - Log.i("ElfSequencer","Needed: "+neededLibrary); - loadLib(neededLibrary); + loadLib(library); + } + + public void loadLib(File library) throws IOException { + File resolved = library.getCanonicalFile(); + if (!resolved.isFile()) throw new IOException("Library not found: " + resolved); + String path = resolved.getPath(); + if (loadedPaths.contains(path) || isMappedLibrary(resolved)) return; + for (String needed : readDependencies(resolved)) { + File dependency = getLibrary(needed); + // Keep linker SONAME handling for preloaded game/platform dependencies. + // Mapped mods still need Canvas registration. + if (mappedNames.contains(needed) && (dependency == null || !isModLibrary(dependency))) { + continue; + } + if (dependency == null) { + Log.d("ElfLoader", "DEPENDENCY_DEFERRED_TO_LINKER: " + needed + " from " + path); + } else { + loadLib(dependency); + } } - Log.i("ElfLoader", "Loading library "+library.getName()); - loadNative(library.getAbsolutePath(), library.getName()); - alreadyLoadedLibs.add(libName); + Log.i("ElfLoader", "Loading library " + path); + loadNative(path, resolved.getName()); + loadedPaths.add(path); + } + + protected List readDependencies(File library) throws IOException { + ElfDynamicSection section = ElfFile.from(library).firstSectionByType(ElfDynamicSection.class); + return section == null ? java.util.Collections.emptyList() : section.getNeededLibraries(); + } + + protected boolean isModLibrary(File library) throws IOException { + return false; + } + + protected boolean isMappedLibrary(File library) throws IOException { + return mappedPaths.contains(library.getCanonicalPath()); } public void loadNative(String absolutePath, String name) { @@ -81,4 +117,4 @@ public File getLibrary(String libName) { } return null; } -} \ No newline at end of file +} diff --git a/app/src/main/java/git/artdeell/skymodloader/GameRuntime.java b/app/src/main/java/git/artdeell/skymodloader/GameRuntime.java new file mode 100644 index 0000000..3344cdb --- /dev/null +++ b/app/src/main/java/git/artdeell/skymodloader/GameRuntime.java @@ -0,0 +1,73 @@ +package git.artdeell.skymodloader; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; + +import java.util.UUID; + +import git.artdeell.skymodloader.elfmod.ModManagerActivity; + +/** Process lifetime state; never restore this from an Activity's saved state. */ +public final class GameRuntime { + private static final String LAUNCH_SESSION = "canvas.launch_session"; + private static final String SESSION = UUID.randomUUID().toString(); + private static final Initialization INITIALIZATION = new Initialization(); + + private GameRuntime() {} + + public static Intent launchIntent(Context context) { + return new Intent(context, MainActivity.class).putExtra(LAUNCH_SESSION, SESSION); + } + + public static boolean isCurrentLaunch(Intent intent) { + return intent != null && SESSION.equals(intent.getStringExtra(LAUNCH_SESSION)); + } + + public static void initialize(Initializer initializer) throws Throwable { + INITIALIZATION.run(initializer); + } + + public static boolean isReady() { + return INITIALIZATION.isReady() && SMLApplication.skyRes != null; + } + + public static void returnToManager(Activity activity) { + activity.startActivity(new Intent(activity, ModManagerActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); + activity.finish(); + } + + @FunctionalInterface + public interface Initializer { + void run() throws Throwable; + } + + static final class Initialization { + private enum State { NEW, INITIALIZING, READY, FAILED } + private State state = State.NEW; + private Throwable failure; + + synchronized void run(Initializer initializer) throws Throwable { + if (state == State.READY) return; + if (state == State.FAILED) throw failure; + if (state == State.INITIALIZING) { + throw new IllegalStateException("Reentrant game initialization"); + } + state = State.INITIALIZING; + try { + initializer.run(); + state = State.READY; + } catch (Throwable error) { + // Native loads and mod hooks cannot be rolled back for a retry. + failure = error; + state = State.FAILED; + throw error; + } + } + + synchronized boolean isReady() { + return state == State.READY; + } + } +} diff --git a/app/src/main/java/git/artdeell/skymodloader/MainActivity.java b/app/src/main/java/git/artdeell/skymodloader/MainActivity.java index 6b89ff5..6b9c8c0 100644 --- a/app/src/main/java/git/artdeell/skymodloader/MainActivity.java +++ b/app/src/main/java/git/artdeell/skymodloader/MainActivity.java @@ -47,7 +47,21 @@ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + if (!GameRuntime.isCurrentLaunch(getIntent())) { + GameRuntime.returnToManager(this); + return; + } + try { + GameRuntime.initialize(this::initializeGame); + startActivity(new Intent(this, GameActivity.class)); + } catch (PackageManager.NameNotFoundException e) { + alertDialog(getString(R.string.sky_not_installed)); + } catch (Throwable e) { + alertDialog(e); + } + } + private void initializeGame() throws Exception { deviceInfo = getDeviceInfo(); sharedPreferences = getSharedPreferences("package_configs", Context.MODE_PRIVATE); @@ -127,135 +141,128 @@ private void loadCppShared(String libPath) { } } - private void loadGame() { + private void loadGame() throws Exception { PackageManager pm = getPackageManager(); - try { - PackageInfo info = pm.getPackageInfo(SKY_PACKAGE_NAME, PackageManager.GET_SHARED_LIBRARY_FILES); - SMLApplication.skyPName = info.packageName; - SMLApplication.skyRes = pm.getResourcesForApplication(info.packageName); - SMLApplication.smlRes = getResources(); - String versionName = info.versionName; - BuildConfig.SKY_VERSION = versionName.substring(0, versionName.indexOf(' ')).trim(); - BuildConfig.VERSION_CODE = info.versionCode; - - String libPath = resolveLibPath(info.applicationInfo); - String elfLibPath = resolveElfLibPath(info.applicationInfo, libPath); - Log.i("MainActivity", "elfLibPath: " + elfLibPath); - - File modsDir = new File(getFilesDir(), "mods"); - File configDir = new File(getFilesDir(), "config"); - if (!configDir.isDirectory() && !configDir.mkdirs()) - throw new IOException("Failed to create mod configuration directory"); - - Log.i("MainActivity", "Pre-loading FMOD dependencies from: " + libPath); - org.fmod.FMOD.init(this); - - if (!libPath.contains("!/lib")) { - File fmodLibDir = new File(libPath); - Log.i("MainActivity", "Listing all files in: " + libPath); - File[] allFiles = fmodLibDir.listFiles(); - if (allFiles != null) { - for (File f : allFiles) { - Log.i("MainActivity", "Found file: " + f.getName()); - } - } else { - Log.e("MainActivity", "Directory is empty or doesn't exist!"); + PackageInfo info = pm.getPackageInfo(SKY_PACKAGE_NAME, PackageManager.GET_SHARED_LIBRARY_FILES); + SMLApplication.skyPName = info.packageName; + SMLApplication.skyRes = pm.getResourcesForApplication(info.packageName); + SMLApplication.smlRes = getResources(); + String versionName = info.versionName; + BuildConfig.SKY_VERSION = versionName.substring(0, versionName.indexOf(' ')).trim(); + BuildConfig.VERSION_CODE = info.versionCode; + + String libPath = resolveLibPath(info.applicationInfo); + String elfLibPath = resolveElfLibPath(info.applicationInfo, libPath); + Log.i("MainActivity", "elfLibPath: " + elfLibPath); + + File modsDir = new File(getFilesDir(), "mods"); + File configDir = new File(getFilesDir(), "config"); + if (!configDir.isDirectory() && !configDir.mkdirs()) + throw new IOException("Failed to create mod configuration directory"); + + Log.i("MainActivity", "Pre-loading FMOD dependencies from: " + libPath); + org.fmod.FMOD.init(this); + + if (!libPath.contains("!/lib")) { + File fmodLibDir = new File(libPath); + Log.i("MainActivity", "Listing all files in: " + libPath); + File[] allFiles = fmodLibDir.listFiles(); + if (allFiles != null) { + for (File f : allFiles) { + Log.i("MainActivity", "Found file: " + f.getName()); } } else { - Log.i("MainActivity", "Loading libs directly from APK (no extraction)"); + Log.e("MainActivity", "Directory is empty or doesn't exist!"); } + } else { + Log.i("MainActivity", "Loading libs directly from APK (no extraction)"); + } - loadCppShared(libPath); + loadCppShared(libPath); - String[] libsToLoad = { - "libOpenSLES.so", - "libfmod.so", - "libfmodstudio.so" - }; + String[] libsToLoad = { + "libOpenSLES.so", + "libfmod.so", + "libfmodstudio.so" + }; - for (String libName : libsToLoad) { - try { - if (libPath.contains("!/lib")) { - String fullApkLibPath = libPath + "/" + libName; - Log.i("MainActivity", "Loading from APK: " + fullApkLibPath); - System.load(fullApkLibPath); - } else { - File lib = new File(libPath, libName); - if (!lib.exists()) { - Log.w("MainActivity", "Not found: " + libName + " at " + lib.getAbsolutePath()); - continue; - } - Log.i("MainActivity", "Loading: " + libName); - System.load(lib.getAbsolutePath()); + for (String libName : libsToLoad) { + try { + if (libPath.contains("!/lib")) { + String fullApkLibPath = libPath + "/" + libName; + Log.i("MainActivity", "Loading from APK: " + fullApkLibPath); + System.load(fullApkLibPath); + } else { + File lib = new File(libPath, libName); + if (!lib.exists()) { + Log.w("MainActivity", "Not found: " + libName + " at " + lib.getAbsolutePath()); + continue; } - Log.i("MainActivity", "Successfully loaded: " + libName); - } catch (Throwable e) { - Log.e("MainActivity", "Failed to load " + libName + ": " + e.getMessage()); + Log.i("MainActivity", "Loading: " + libName); + System.load(lib.getAbsolutePath()); } + Log.i("MainActivity", "Successfully loaded: " + libName); + } catch (Throwable e) { + Log.e("MainActivity", "Failed to load " + libName + ": " + e.getMessage()); } + } - ElfLoader loader = new ElfLoader(elfLibPath); - loader.loadLib("libBootloader.so"); - System.loadLibrary("ciphered"); - if (getSharedPreferences("daybreaker_configs", MODE_PRIVATE).getBoolean("enable_daybreaker", false)) { - try { - System.loadLibrary("DayBreaker"); - } catch (Throwable ignored) { - } + ElfLoader loader = new ElfLoader(elfLibPath); + loader.loadLib("libBootloader.so"); + System.loadLibrary("ciphered"); + if (getSharedPreferences("daybreaker_configs", MODE_PRIVATE).getBoolean("enable_daybreaker", false)) { + try { + System.loadLibrary("DayBreaker"); + } catch (Throwable ignored) { } + } - String buildKey = getSkyBuildAccessKey(); - if (buildKey != null) { - BuildConfig.SKY_BUILD_ACCESS_KEY = buildKey; - nativeSetSkyBuildKey(buildKey); - Log.i("MainActivity", "BuildKey applied: " + buildKey.substring(0, Math.min(20, buildKey.length())) + "..."); - } else { - Log.w("MainActivity", "NOT FOUND, DEFAULT INSTEAD: " + BuildConfig.SKY_BUILD_ACCESS_KEY); - } + String buildKey = getSkyBuildAccessKey(); + if (buildKey != null) { + BuildConfig.SKY_BUILD_ACCESS_KEY = buildKey; + nativeSetSkyBuildKey(buildKey); + Log.i("MainActivity", "BuildKey applied: " + buildKey.substring(0, Math.min(20, buildKey.length())) + "..."); + } else { + Log.w("MainActivity", "NOT FOUND, DEFAULT INSTEAD: " + BuildConfig.SKY_BUILD_ACCESS_KEY); + } - setDeviceInfoNative( - deviceInfo.xdpi, - deviceInfo.ydpi, - deviceInfo.density, - Optional.ofNullable(deviceInfo.deviceName).orElse(""), - Optional.ofNullable(deviceInfo.deviceManufacturer).orElse(""), - Optional.ofNullable(deviceInfo.deviceModel).orElse("")); - IconLoader.findIcons(); - BuildConfig.VERSION_CODE = sharedPreferences.getBoolean("skip_updates", false) ? 0x99999 : info.versionCode; - Integer gameType = skyPackages.getOrDefault(SKY_PACKAGE_NAME, 0); - if (sharedPreferences.getBoolean("custom_server", false)) { - String customHost = sharedPreferences.getString("server_host", ServerManager.getDefaultHost()); - if (customHost != null) { - customHost = ServerManager.sanitizeHost(customHost); - if (!customHost.isEmpty()) { - BuildConfig.SKY_SERVER_HOSTNAME = customHost; - Log.i("MainActivity", "Custom server hostname configured: " + BuildConfig.SKY_SERVER_HOSTNAME); - } else { - Log.w("MainActivity", "Custom server is enabled but server_host is empty"); - } + setDeviceInfoNative( + deviceInfo.xdpi, + deviceInfo.ydpi, + deviceInfo.density, + Optional.ofNullable(deviceInfo.deviceName).orElse(""), + Optional.ofNullable(deviceInfo.deviceManufacturer).orElse(""), + Optional.ofNullable(deviceInfo.deviceModel).orElse("")); + IconLoader.findIcons(); + BuildConfig.VERSION_CODE = sharedPreferences.getBoolean("skip_updates", false) ? 0x99999 : info.versionCode; + Integer gameType = skyPackages.getOrDefault(SKY_PACKAGE_NAME, 0); + if (sharedPreferences.getBoolean("custom_server", false)) { + String customHost = sharedPreferences.getString("server_host", ServerManager.getDefaultHost()); + if (customHost != null) { + customHost = ServerManager.sanitizeHost(customHost); + if (!customHost.isEmpty()) { + BuildConfig.SKY_SERVER_HOSTNAME = customHost; + Log.i("MainActivity", "Custom server hostname configured: " + BuildConfig.SKY_SERVER_HOSTNAME); + } else { + Log.w("MainActivity", "Custom server is enabled but server_host is empty"); } - MainActivity.customServer(BuildConfig.SKY_SERVER_HOSTNAME); } - MainActivity.settle( - info.versionCode, - gameType == null ? 0 : gameType, - BuildConfig.SKY_SERVER_HOSTNAME, - configDir.getAbsolutePath(), - SMLApplication.skyRes.getAssets(), - ceserverEnabled, - hideCanvasMenu - ); - AccountStorage.sync(this); - - new ElfRefcountLoader(elfLibPath, modsDir).load(); - BuildConfig.APPLICATION_ID = SKY_PACKAGE_NAME; - startActivity(new Intent(this, GameActivity.class)); - - } catch (PackageManager.NameNotFoundException e) { - alertDialog(getString(R.string.sky_not_installed)); - } catch (Throwable e) { - alertDialog(e); + MainActivity.customServer(BuildConfig.SKY_SERVER_HOSTNAME); } + MainActivity.settle( + info.versionCode, + gameType == null ? 0 : gameType, + BuildConfig.SKY_SERVER_HOSTNAME, + configDir.getAbsolutePath(), + SMLApplication.skyRes.getAssets(), + ceserverEnabled, + hideCanvasMenu + ); + AccountStorage.sync(this); + + new ElfRefcountLoader(elfLibPath, modsDir).load(); + completeModInitialization(); + BuildConfig.APPLICATION_ID = SKY_PACKAGE_NAME; } private String resolveLibPath(ApplicationInfo appInfo) throws IOException { @@ -536,6 +543,7 @@ public static native void setDeviceInfoNative( public static native void onKeyboardCompleteNative(String message); public static native void customServer(String url); public static native void lateInitUserLibs(); + private static native void completeModInitialization(); public static native void getSysetemUI(Object systemUI); private static native void nativeSetSkyBuildKey(String key); diff --git a/app/src/main/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoader.java b/app/src/main/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoader.java index eeca8cf..8b2c864 100644 --- a/app/src/main/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoader.java +++ b/app/src/main/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoader.java @@ -10,8 +10,10 @@ import org.json.JSONObject; import java.io.File; +import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; +import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -24,18 +26,27 @@ public class ElfRefcountLoader extends ElfLoader{ private final List elfFileReferences = new ArrayList<>(); private final Map metadataByName = new ArrayMap<>(); + private final Map filesByName = new ArrayMap<>(); private final File modsFolder; public ElfRefcountLoader(String defaultPaths, File modsFolder) throws IOException { - super(defaultPaths+":"+modsFolder.getAbsolutePath()); - this.modsFolder = modsFolder; - if(!modsFolder.exists()) { - modsFolder.mkdirs(); + this(preparePaths(defaultPaths, modsFolder), modsFolder, new FileReader("/proc/self/maps")); + } + + ElfRefcountLoader(String preparedPaths, File modsFolder, Reader processMaps) throws IOException { + super(preparedPaths, processMaps); + this.modsFolder = modsFolder.getCanonicalFile(); + } + + static String preparePaths(String defaultPaths, File modsFolder) throws IOException { + if (!modsFolder.isDirectory() && !modsFolder.mkdirs()) { + throw new IOException("Cannot create mod directory: " + modsFolder); } + return defaultPaths + File.pathSeparator + modsFolder.getAbsolutePath(); } public void load() throws Exception { - File[] modFiles = modsFolder.listFiles(new SharedObjectFileFilter()); - if(modFiles == null) return; + File[] modFiles = listRequiredFiles(modsFolder, "MOD_ENUMERATION_FAILED", + new SharedObjectFileFilter()); for(File f : modFiles) { try { if (f.getName().endsWith(".so")&&(!new File(f.getPath() + "_invalid.txt").exists())) { @@ -48,13 +59,29 @@ public void load() throws Exception { scanDeps(); Collections.sort(elfFileReferences); for(ElfFileReference ref : elfFileReferences) { - loadLib(ref.modMeta.name); + loadLib(filesByName.get(ref.modMeta.name)); } } + @Override + public File getLibrary(String name) { + File mod = filesByName.get(name); + return mod != null ? mod : super.getLibrary(name); + } + + @Override + protected boolean isModLibrary(File library) throws IOException { + return modsFolder.equals(library.getCanonicalFile().getParentFile()); + } + + @Override + protected boolean isMappedLibrary(File library) throws IOException { + return !isModLibrary(library) && super.isMappedLibrary(library); + } + @Override public void loadNative(String absolutePath, String name) { - if (absolutePath.startsWith(modsFolder.getAbsolutePath())) { + if (modsFolder.equals(new File(absolutePath).getParentFile())) { ElfModMetadata metadata = metadataByName.get(name); if (metadata == null) { throw new IllegalStateException("WTF? No saved metadata for mod library " + name); @@ -78,6 +105,7 @@ public void addElf(File file) throws Exception { ElfModMetadata metadata = loadMetadata(file); elfFileReferences.add(new ElfFileReference(metadata)); metadataByName.put(metadata.name, metadata); + filesByName.put(metadata.name, file); } public static ElfModMetadata loadMetadata(File file) throws Exception { diff --git a/app/src/main/java/git/artdeell/skymodloader/elfmod/ModManagerActivity.java b/app/src/main/java/git/artdeell/skymodloader/elfmod/ModManagerActivity.java index 64bca25..c2e377f 100644 --- a/app/src/main/java/git/artdeell/skymodloader/elfmod/ModManagerActivity.java +++ b/app/src/main/java/git/artdeell/skymodloader/elfmod/ModManagerActivity.java @@ -650,7 +650,7 @@ public boolean findPackage(String packageName) { public void launchGame() { if (findPackage(skyPackageName)) { setSkyPackageName(skyPackageName); - startActivity(new Intent(this, MainActivity.class)); + startActivity(git.artdeell.skymodloader.GameRuntime.launchIntent(this)); } else { Toast.makeText( getApplicationContext(), diff --git a/app/src/test/cpp/CMakeLists.txt b/app/src/test/cpp/CMakeLists.txt index 2b2da41..e87858c 100644 --- a/app/src/test/cpp/CMakeLists.txt +++ b/app/src/test/cpp/CMakeLists.txt @@ -7,6 +7,14 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) enable_testing() +find_package(Threads REQUIRED) +add_executable(initialization_gate_test InitializationGateTest.cpp) +target_include_directories(initialization_gate_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../../main/cpp/Core) +target_compile_options(initialization_gate_test PRIVATE -Wall -Wextra -Werror -UNDEBUG) +target_link_libraries(initialization_gate_test PRIVATE Threads::Threads) +add_test(NAME initialization_gate_test COMMAND initialization_gate_test) + add_executable(chat_flag_fix_test ChatFlagFixTest.cpp) target_include_directories(chat_flag_fix_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} diff --git a/app/src/test/cpp/InitializationGateTest.cpp b/app/src/test/cpp/InitializationGateTest.cpp new file mode 100644 index 0000000..291b795 --- /dev/null +++ b/app/src/test/cpp/InitializationGateTest.cpp @@ -0,0 +1,59 @@ +#include "Canvas/InitializationGate.h" + +#include +#include +#include +#include +#include +#include + +int main() { + for (int run = 0; run < 100; ++run) { + Canvas::InitializationGate gate; + assert(!gate.isReady()); + assert(!gate.publish()); + assert(gate.begin()); + assert(gate.isLoading()); + assert(!gate.begin()); + + std::vector registry; + std::mutex mutex; + std::condition_variable changed; + bool reading = false; + bool release = false; + std::thread lateReader([&] { + while (!gate.isReady()) std::this_thread::yield(); + // Read data published by the bootstrap thread, without a registry lock. + assert(registry.size() == 3); + const int& item = registry[1]; + std::unique_lock lock(mutex); + reading = true; + changed.notify_one(); + changed.wait(lock, [&] { return release; }); + assert(item == 20); + assert(registry.size() == 3); + }); + registry = {10, 20, 30}; + assert(gate.publish()); + { + std::unique_lock lock(mutex); + changed.wait(lock, [&] { return reading; }); + // A new bootstrap cannot reach registry mutation while a reader holds an item. + assert(!gate.begin()); + assert(!gate.isLoading()); + assert(!gate.publish()); + release = true; + } + changed.notify_one(); + lateReader.join(); + } + + Canvas::InitializationGate gate; + std::atomic winners{0}; + std::vector contenders; + for (int i = 0; i < 16; ++i) { + contenders.emplace_back([&] { if (gate.begin()) ++winners; }); + } + for (auto& contender : contenders) contender.join(); + assert(winners == 1); +} diff --git a/app/src/test/java/com/tgc/sky/GameActivityRestorationTest.java b/app/src/test/java/com/tgc/sky/GameActivityRestorationTest.java new file mode 100644 index 0000000..a7bed9c --- /dev/null +++ b/app/src/test/java/com/tgc/sky/GameActivityRestorationTest.java @@ -0,0 +1,56 @@ +package com.tgc.sky; + +import static org.junit.Assert.*; +import static org.robolectric.Shadows.shadowOf; + +import android.app.Application; +import android.content.Intent; +import android.content.res.Configuration; +import android.os.Bundle; +import android.view.SurfaceView; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +import git.artdeell.skymodloader.SMLApplication; +import git.artdeell.skymodloader.elfmod.ModManagerActivity; + +@RunWith(RobolectricTestRunner.class) +@Config(application = Application.class, manifest = Config.NONE, sdk = {26, 34, 36}) +public class GameActivityRestorationTest { + @Test + public void restoredGameRedirectsBeforeResourcesOrJniAndSafelyFinishes() { + SMLApplication.skyRes = null; + Bundle saved = new Bundle(); + saved.putByteArray("android:native_state", new byte[]{1, 2}); + var controller = Robolectric.buildActivity(GameActivity.class).create(saved); + GameActivity activity = controller.get(); + Intent destination = shadowOf(activity).getNextStartedActivity(); + assertEquals(ModManagerActivity.class.getName(), destination.getComponent().getClassName()); + assertEquals(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK, destination.getFlags()); + assertTrue(activity.isFinishing()); + assertFalse(activity.hasNativeActivity()); + + // JNI is deliberately absent in this test. Any unguarded native call fails it. + controller.start().resume(); + activity.onWindowFocusChanged(true); + activity.onConfigurationChanged(new Configuration()); + activity.onLowMemory(); + activity.onGlobalLayout(); + activity.onNewIntent(new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("sky://test"))); + var holder = new SurfaceView(activity).getHolder(); + activity.surfaceCreated(holder); + activity.surfaceChanged(holder, android.graphics.PixelFormat.RGBA_8888, 100, 100); + activity.surfaceRedrawNeeded(holder); + activity.surfaceDestroyed(holder); + Bundle output = new Bundle(); + controller.saveInstanceState(output); + assertFalse(output.containsKey("android:native_state")); + controller.pause().stop().destroy(); + assertFalse(activity.hasNativeActivity()); + assertNull(SMLApplication.skyRes); + } +} diff --git a/app/src/test/java/git/artdeell/skymodloader/ElfLoaderTest.java b/app/src/test/java/git/artdeell/skymodloader/ElfLoaderTest.java new file mode 100644 index 0000000..f315c22 --- /dev/null +++ b/app/src/test/java/git/artdeell/skymodloader/ElfLoaderTest.java @@ -0,0 +1,103 @@ +package git.artdeell.skymodloader; + +import static org.junit.Assert.*; + +import android.app.Application; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@RunWith(RobolectricTestRunner.class) +@Config(application = Application.class, manifest = Config.NONE, sdk = 34) +public class ElfLoaderTest { + @Rule public TemporaryFolder files = new TemporaryFolder(); + + private static class RecordingLoader extends ElfLoader { + final List loaded = new ArrayList<>(); + List needed = Collections.emptyList(); + + RecordingLoader(String paths, Reader maps) throws IOException { super(paths, maps); } + @Override protected List readDependencies(File library) { return needed; } + @Override public void loadNative(String path, String name) { loaded.add(path); } + } + + private static class TrackedReader extends StringReader { + boolean closed; + TrackedReader() { super(""); } + @Override public void close() { closed = true; super.close(); } + } + + private String mapping(File file) { + return "1000-2000 r-xp 0000 00:00 1 " + file.getAbsolutePath() + "\n"; + } + + @Test + public void requiredDirectoryFailureClosesMapsAndThrows() throws Exception { + TrackedReader reader = new TrackedReader(); + File notDirectory = files.newFile("not-a-directory"); + assertThrows(IOException.class, () -> new RecordingLoader(notDirectory.getPath(), reader)); + assertTrue(reader.closed); + } + + @Test + public void emptyDirectoryIsValidButMissingRequiredLibraryFails() throws Exception { + TrackedReader reader = new TrackedReader(); + RecordingLoader loader = new RecordingLoader(files.getRoot().getPath(), reader); + assertTrue(reader.closed); + assertThrows(IOException.class, () -> loader.loadLib("libBootloader.so")); + assertTrue(loader.loaded.isEmpty()); + } + + @Test + public void mappedBasenameCollisionDoesNotSkipRequestedLibrary() throws Exception { + File system = files.newFolder("system"); + File mods = files.newFolder("mods"); + File mapped = new File(system, "same.so"); + File requested = new File(mods, "same.so"); + assertTrue(mapped.createNewFile()); + assertTrue(requested.createNewFile()); + RecordingLoader loader = new RecordingLoader(mods.getPath(), new StringReader(mapping(mapped))); + loader.loadLib("same.so"); + loader.loadLib(new File(mods, "." + File.separator + "same.so")); + assertEquals(Collections.singletonList(requested.getCanonicalPath()), loader.loaded); + } + + @Test + public void missingPlatformDependencyIsLeftToTheLinker() throws Exception { + File mod = files.newFile("mod.so"); + RecordingLoader loader = new RecordingLoader(files.getRoot().getPath(), new StringReader("")); + loader.needed = Collections.singletonList("liblog.so"); + loader.loadLib(mod); + assertEquals(Collections.singletonList(mod.getCanonicalPath()), loader.loaded); + } + + @Test + public void cachedLibraryRemovedBeforeLoadFails() throws Exception { + File mod = files.newFile("mod.so"); + RecordingLoader loader = new RecordingLoader(files.getRoot().getPath(), new StringReader("")); + assertTrue(mod.delete()); + assertThrows(IOException.class, () -> loader.loadLib("mod.so")); + assertTrue(loader.loaded.isEmpty()); + } + + @Test + public void nullModEnumerationIsAnError() { + File unreadable = new File("fixture") { + @Override public File[] listFiles(java.io.FileFilter filter) { return null; } + }; + assertThrows(IOException.class, + () -> ElfLoader.listRequiredFiles(unreadable, "MOD_ENUMERATION_FAILED", f -> true)); + } +} diff --git a/app/src/test/java/git/artdeell/skymodloader/GameRuntimeTest.java b/app/src/test/java/git/artdeell/skymodloader/GameRuntimeTest.java new file mode 100644 index 0000000..39f1093 --- /dev/null +++ b/app/src/test/java/git/artdeell/skymodloader/GameRuntimeTest.java @@ -0,0 +1,107 @@ +package git.artdeell.skymodloader; + +import static org.junit.Assert.*; +import static org.robolectric.Shadows.shadowOf; + +import android.app.Application; +import android.content.Intent; +import android.os.Bundle; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import git.artdeell.skymodloader.elfmod.ModManagerActivity; + +@RunWith(RobolectricTestRunner.class) +@Config(application = Application.class, manifest = Config.NONE, sdk = {26, 34, 36}) +public class GameRuntimeTest { + @Test + public void repeatedBootstrapPreservesRegistration() throws Throwable { + GameRuntime.Initialization state = new GameRuntime.Initialization(); + AtomicInteger registrations = new AtomicInteger(); + for (int i = 0; i < 10; i++) state.run(registrations::incrementAndGet); + assertEquals(1, registrations.get()); + assertTrue(state.isReady()); + } + + @Test + public void failedNativeInitializationCannotBeRetried() { + GameRuntime.Initialization state = new GameRuntime.Initialization(); + IOException failure = new IOException("fixture"); + assertSame(failure, assertThrows(IOException.class, () -> state.run(() -> { throw failure; }))); + assertSame(failure, assertThrows(IOException.class, () -> state.run(() -> fail("retry")))); + assertFalse(state.isReady()); + } + + @Test + public void reentrantInitializationNeverRunsTheSecondInitializer() { + GameRuntime.Initialization state = new GameRuntime.Initialization(); + assertThrows(IllegalStateException.class, + () -> state.run(() -> state.run(() -> fail("reentered")))); + assertFalse(state.isReady()); + } + + @Test + public void concurrentRequestsWaitForTheSameInitialization() throws Exception { + GameRuntime.Initialization state = new GameRuntime.Initialization(); + AtomicInteger registrations = new AtomicInteger(); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + var pool = Executors.newFixedThreadPool(2); + try { + var first = pool.submit(() -> { + try { + state.run(() -> { + entered.countDown(); + assertTrue(release.await(5, TimeUnit.SECONDS)); + registrations.incrementAndGet(); + }); + } catch (Throwable e) { throw new AssertionError(e); } + }); + assertTrue(entered.await(5, TimeUnit.SECONDS)); + var second = pool.submit(() -> { + try { state.run(registrations::incrementAndGet); } + catch (Throwable e) { throw new AssertionError(e); } + }); + release.countDown(); + first.get(5, TimeUnit.SECONDS); + second.get(5, TimeUnit.SECONDS); + assertEquals(1, registrations.get()); + assertTrue(state.isReady()); + } finally { + release.countDown(); + pool.shutdownNow(); + } + } + + @Test + public void staleBootstrapReturnsToManagerWithoutLoadingTheGame() { + Intent stale = new Intent().putExtra("canvas.launch_session", "previous-process"); + var controller = Robolectric.buildActivity(MainActivity.class, stale).create(new Bundle()); + MainActivity activity = controller.get(); + Intent destination = shadowOf(activity).getNextStartedActivity(); + assertEquals(ModManagerActivity.class.getName(), destination.getComponent().getClassName()); + assertEquals(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK, destination.getFlags()); + assertTrue(activity.isFinishing()); + assertFalse(GameRuntime.isReady()); + controller.destroy(); + } + + @Test + public void playIntentBelongsToThisProcessOnly() { + Application app = org.robolectric.RuntimeEnvironment.getApplication(); + assertTrue(GameRuntime.isCurrentLaunch(GameRuntime.launchIntent(app))); + assertFalse(GameRuntime.isCurrentLaunch(new Intent())); + assertFalse(GameRuntime.isCurrentLaunch(null)); + assertFalse(GameRuntime.isCurrentLaunch(new Intent().putExtra("canvas.launch_session", "old"))); + } +} diff --git a/app/src/test/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoaderTest.java b/app/src/test/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoaderTest.java new file mode 100644 index 0000000..ca63476 --- /dev/null +++ b/app/src/test/java/git/artdeell/skymodloader/elfmod/ElfRefcountLoaderTest.java @@ -0,0 +1,112 @@ +package git.artdeell.skymodloader.elfmod; + +import static org.junit.Assert.*; + +import android.app.Application; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@RunWith(RobolectricTestRunner.class) +@Config(application = Application.class, manifest = Config.NONE, sdk = 34) +public class ElfRefcountLoaderTest { + @Rule public TemporaryFolder files = new TemporaryFolder(); + + private static class RecordingLoader extends ElfRefcountLoader { + final List loaded = new ArrayList<>(); + RecordingLoader(File game, File mods, String maps) throws IOException { + super(preparePaths(game.getPath(), mods), mods, new StringReader(maps)); + } + @Override public void loadNative(String path, String name) { loaded.add(path); } + } + + // A section-only ELF fixture with real mod metadata, parsed by the production jelf code. + private File mod(File directory, String name) throws IOException { + byte[] names = "\0.shstrtab\0.config\0".getBytes(StandardCharsets.UTF_8); + byte[] metadata = ("{\"name\":\"" + name + "\",\"description\":\"fixture\"," + + "\"majorVersion\":1,\"minorVersion\":0,\"patchVersion\":0,\"dependencies\":[]}") + .getBytes(StandardCharsets.UTF_8); + ByteBuffer elf = ByteBuffer.allocate(256 + names.length + metadata.length) + .order(ByteOrder.LITTLE_ENDIAN); + elf.put(new byte[]{0x7f, 'E', 'L', 'F', 2, 1, 1}); + elf.position(16); + elf.putShort((short)3).putShort((short)183).putInt(1); + elf.putLong(0).putLong(0).putLong(64).putInt(0); + elf.putShort((short)64).putShort((short)0).putShort((short)0); + elf.putShort((short)64).putShort((short)3).putShort((short)1); + elf.position(128); + section(elf, 1, 3, 256, names.length); + section(elf, 11, 1, 256 + names.length, metadata.length); + elf.put(names).put(metadata); + File result = new File(directory, name); + Files.write(result.toPath(), elf.array()); + return result; + } + + private void section(ByteBuffer elf, int name, int type, long offset, long size) { + elf.putInt(name).putInt(type).putLong(0).putLong(0).putLong(offset).putLong(size); + elf.putInt(0).putInt(0).putLong(1).putLong(0); + } + + @Test + public void missingModsDirectoryIsCreatedBeforeCachingAndNewModLoads() throws Exception { + File game = files.newFolder("game"); + File mods = new File(files.getRoot(), "mods"); + RecordingLoader loader = new RecordingLoader(game, mods, ""); + assertTrue(mods.isDirectory()); + File requested = mod(mods, "new.so"); + loader.load(); + assertEquals(Collections.singletonList(requested.getCanonicalPath()), loader.loaded); + } + + @Test + public void explicitModWinsGameNameCollisionAndRegistersEvenWhenMapped() throws Exception { + File game = files.newFolder("game"); + File mods = files.newFolder("mods"); + mod(game, "same.so"); + File requested = mod(mods, "same.so"); + String maps = "1000-2000 r-xp 0 00:00 1 " + requested.getAbsolutePath() + "\n"; + RecordingLoader loader = new RecordingLoader(game, mods, maps); + loader.load(); + assertEquals(Collections.singletonList(requested.getCanonicalPath()), loader.loaded); + } + + @Test + public void disabledMarkerRemainsAnIntentionalSkip() throws Exception { + File game = files.newFolder("game"); + File mods = files.newFolder("mods"); + File requested = mod(mods, "disabled.so"); + File marker = new File(requested.getPath() + "_invalid.txt"); + assertTrue(marker.createNewFile()); + RecordingLoader loader = new RecordingLoader(game, mods, ""); + loader.load(); + assertTrue(loader.loaded.isEmpty()); + assertTrue(marker.exists()); + } + + @Test + public void directoryBecomingUnlistableAfterConstructionFailsLoad() throws Exception { + File game = files.newFolder("game"); + File mods = files.newFolder("mods"); + RecordingLoader loader = new RecordingLoader(game, mods, ""); + assertTrue(mods.delete()); + assertTrue(mods.createNewFile()); + assertThrows(IOException.class, loader::load); + assertTrue(loader.loaded.isEmpty()); + } +}