From 4aece8311acd4c6bbac23da8d8f4255508f722c6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:03:09 -0300 Subject: [PATCH] build: raise the default minSdk to 24 Google Play services and Firebase libraries require minSdk 24, so most apps already declare it. NS_DEFAULT_MIN_SDK_VERSION, which the runtime library and every app's build.gradle default to, goes from 21 to 24, as do the minSdk/ndkApiLevel entries in package.json's version_info. With 24 as the floor: - Optimized links pass -Wl,--pack-dyn-relocs=android (the loader reads the packed format from API 23); the dynamic relocation table shrinks from 1,098,144 to 153,106 bytes on arm64-v8a. clang also stops emitting the SysV .hash section next to .gnu.hash. - AChoreographer_getInstance/postFrameCallback(Delayed) are linked directly instead of through dlsym. Only the API 29 64-bit variants are still resolved at run time. - The android.view.Choreographer fallback (com.tns.FrameCallbacks), its JNI entry point and the debug-only __setFrameCallbackImpl hook that tested it are removed. - The SDK_INT >= 24 gates on default-method handling (InterfaceProxyHandler, DexFactory, Runtime.getDefaultMethodNames) and the pre-24 DexPathList reflection behind injectDexIntoClassLoader are removed; addDexPath is always available. Behavior on API 24+ devices is unchanged. Apps that declare a minSdk of 21-23 now fail the manifest merge and must raise it; apps that declare none become minSdk 24. --- docs/performance.md | 7 +- package.json | 4 +- .../assets/app/tests/testPostFrameCallback.js | 131 +++++-------- test-app/gradle.properties | 2 +- test-app/runtime/CMakeLists.txt | 7 +- .../runtime/src/main/cpp/FrameCallbacks.cpp | 185 +++--------------- .../runtime/src/main/cpp/FrameCallbacks.h | 13 +- .../src/main/java/com/tns/DexFactory.java | 59 +----- .../src/main/java/com/tns/FrameCallbacks.java | 54 ----- .../java/com/tns/InterfaceProxyHandler.java | 4 +- .../src/main/java/com/tns/Runtime.java | 3 - 11 files changed, 92 insertions(+), 377 deletions(-) delete mode 100644 test-app/runtime/src/main/java/com/tns/FrameCallbacks.java diff --git a/docs/performance.md b/docs/performance.md index b01eb7c7f..383ef3c67 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -75,11 +75,8 @@ __postFrameCallback((frameTimeNanos, performanceMillis) => { … }); frames on the very clock the time origin is captured on, so the mapping is exact rather than an approximation resampled in JS. -Two implementations sit behind that one surface: the NDK's `AChoreographer` -(API 24+, resolved with `dlsym`) and `android.view.Choreographer` through -`com.tns.FrameCallbacks` for API 21–23, where the NDK API does not exist. -Scheduling is per calling thread, so a worker schedules against its own looper. -Both paths produce the same two arguments with the same exactness. +Frames come from the NDK's `AChoreographer`. Scheduling is per calling thread, +so a worker schedules against its own looper. ## Deviations from the specs diff --git a/package.json b/package.json index 4a292a289..41423765d 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,8 @@ "gradle": "8.14.3", "gradleAndroid": "8.12.1", "ndk": "r29", - "ndkApiLevel": "21", - "minSdk": "21", + "ndkApiLevel": "24", + "minSdk": "24", "compileSdk": "35", "buildTools": "35.0.0", "kotlin": "2.0.0" diff --git a/test-app/app/src/main/assets/app/tests/testPostFrameCallback.js b/test-app/app/src/main/assets/app/tests/testPostFrameCallback.js index fbd8d47b2..d5693cf65 100644 --- a/test-app/app/src/main/assets/app/tests/testPostFrameCallback.js +++ b/test-app/app/src/main/assets/app/tests/testPostFrameCallback.js @@ -235,97 +235,64 @@ describe("requestAnimationFrame", function () { }); }); -// The two implementations behind __postFrameCallback (NDK AChoreographer, -// android.view.Choreographer for API < 24) must be indistinguishable from JS. -// A modern device always selects the NDK one, so the Java bridge is only -// reachable through __setFrameCallbackImpl, which debug runtimes expose for -// exactly this. describe("frame callback timestamps", function () { const defaultWaitTime = 300; - const impls = ["native", "java"]; - afterEach(() => { - if (typeof global.__setFrameCallbackImpl === "function") { - global.__setFrameCallbackImpl("auto"); - } - }); - - function withImpl(impl) { - if (typeof global.__setFrameCallbackImpl !== "function") { - return impl === "native"; - } - return global.__setFrameCallbackImpl(impl) === impl; - } - - impls.forEach((impl) => { - describe(impl + " implementation", function () { - it("passes the raw frame time and a performance-timeline timestamp", (done) => { - if (!withImpl(impl)) { - pending("this runtime cannot select the " + impl + " implementation"); - return; - } - - global.__postFrameCallback((frameTimeNanos, performanceMillis) => { - const now = performance.now(); - - expect(typeof frameTimeNanos).toBe("number"); - expect(typeof performanceMillis).toBe("number"); + it("passes the raw frame time and a performance-timeline timestamp", (done) => { + global.__postFrameCallback((frameTimeNanos, performanceMillis) => { + const now = performance.now(); - // Uptime-scale nanoseconds, not epoch-scale milliseconds. - expect(frameTimeNanos).toBeGreaterThan(1e9); - expect(frameTimeNanos / 1e6).toBeLessThan(Date.now()); + expect(typeof frameTimeNanos).toBe("number"); + expect(typeof performanceMillis).toBe("number"); - // The frame is stamped just before the callback runs, so its - // timeline position sits a frame or two behind the reading taken - // inside it, never ahead of it. - expect(performanceMillis).toBeGreaterThan(0); - expect(performanceMillis).not.toBeGreaterThan(now); - expect(now - performanceMillis).toBeLessThan(250); + // Uptime-scale nanoseconds, not epoch-scale milliseconds. + expect(frameTimeNanos).toBeGreaterThan(1e9); + expect(frameTimeNanos / 1e6).toBeLessThan(Date.now()); - // Both arguments describe the same instant, so their difference is - // the timeline's monotonic origin. System.nanoTime() is on that same - // clock, so the pair (nanoTime, now) must yield the same origin -- - // this is what would break if either argument moved off the base. - // The two clocks cannot be read at once, so nanoTime is bracketed - // and compared against the midpoint: the tolerance then only has to - // cover the sampling window, not whatever pause lands between them. - const beforeNow = performance.now(); - const sampledNanos = java.lang.System.nanoTime(); - const afterNow = performance.now(); - const originFromFrame = frameTimeNanos / 1e6 - performanceMillis; - const originFromClock = sampledNanos / 1e6 - (beforeNow + afterNow) / 2; - expect(Math.abs(originFromFrame - originFromClock)).toBeLessThan( - 5 + (afterNow - beforeNow) - ); - done(); - }); - }); + // The frame is stamped just before the callback runs, so its + // timeline position sits a frame or two behind the reading taken + // inside it, never ahead of it. + expect(performanceMillis).toBeGreaterThan(0); + expect(performanceMillis).not.toBeGreaterThan(now); + expect(now - performanceMillis).toBeLessThan(250); - it("advances across consecutive frames", (done) => { - if (!withImpl(impl)) { - pending("this runtime cannot select the " + impl + " implementation"); - return; - } + // Both arguments describe the same instant, so their difference is + // the timeline's monotonic origin. System.nanoTime() is on that same + // clock, so the pair (nanoTime, now) must yield the same origin -- + // this is what would break if either argument moved off the base. + // The two clocks cannot be read at once, so nanoTime is bracketed + // and compared against the midpoint: the tolerance then only has to + // cover the sampling window, not whatever pause lands between them. + const beforeNow = performance.now(); + const sampledNanos = java.lang.System.nanoTime(); + const afterNow = performance.now(); + const originFromFrame = frameTimeNanos / 1e6 - performanceMillis; + const originFromClock = sampledNanos / 1e6 - (beforeNow + afterNow) / 2; + expect(Math.abs(originFromFrame - originFromClock)).toBeLessThan( + 5 + (afterNow - beforeNow) + ); + done(); + }); + }); - const frames = []; - const callback = (frameTimeNanos, performanceMillis) => { - frames.push({ nanos: frameTimeNanos, millis: performanceMillis }); - if (frames.length === 1) { - global.__postFrameCallback(callback); - } - }; + it("advances across consecutive frames", (done) => { + const frames = []; + const callback = (frameTimeNanos, performanceMillis) => { + frames.push({ nanos: frameTimeNanos, millis: performanceMillis }); + if (frames.length === 1) { global.__postFrameCallback(callback); + } + }; + global.__postFrameCallback(callback); - setTimeout(() => { - expect(frames.length).toBe(2); - expect(frames[1].nanos).not.toBeLessThan(frames[0].nanos); - expect(frames[1].millis).not.toBeLessThan(frames[0].millis); - // The origin the two arguments imply is a constant of the isolate. - const origin = (f) => f.nanos / 1e6 - f.millis; - expect(Math.abs(origin(frames[1]) - origin(frames[0]))).toBeLessThan(1); - done(); - }, defaultWaitTime); - }); - }); + setTimeout(() => { + expect(frames.length).toBe(2); + expect(frames[1].nanos).not.toBeLessThan(frames[0].nanos); + expect(frames[1].millis).not.toBeLessThan(frames[0].millis); + // The origin the two arguments imply is a constant of the isolate. + const origin = (f) => f.nanos / 1e6 - f.millis; + expect(Math.abs(origin(frames[1]) - origin(frames[0]))).toBeLessThan(1); + done(); + }, defaultWaitTime); }); }); diff --git a/test-app/gradle.properties b/test-app/gradle.properties index e58b0da6b..798b89ab6 100644 --- a/test-app/gradle.properties +++ b/test-app/gradle.properties @@ -21,7 +21,7 @@ android.useAndroidX=true # Default versions used throughout the gradle configurations NS_DEFAULT_BUILD_TOOLS_VERSION=35.0.0 NS_DEFAULT_COMPILE_SDK_VERSION=35 -NS_DEFAULT_MIN_SDK_VERSION=21 +NS_DEFAULT_MIN_SDK_VERSION=24 NS_DEFAULT_ANDROID_BUILD_TOOLS_VERSION=8.13.2 # R8 8.x cannot read Kotlin 2.4 metadata (needs 9.1.29+), so the AGP-bundled R8 is overridden. NS_DEFAULT_R8_VERSION=9.1.43 diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 8f64c421d..57e9ab9c5 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -317,4 +317,9 @@ find_library(system-android android) # Command info: https://cmake.org/cmake/help/v3.4/command/target_link_libraries.html # Specifies libraries CMake should link to your target library. -target_link_libraries(NativeScript ${system-log} ${system-z} ${system-android}) \ No newline at end of file +target_link_libraries(NativeScript ${system-log} ${system-z} ${system-android}) + +if (OPTIMIZED_BUILD OR OPTIMIZED_WITH_INSPECTOR_BUILD) + # Android's packed relocation format, which the loader reads from API 23. + target_link_options(NativeScript PRIVATE "-Wl,--pack-dyn-relocs=android") +endif () diff --git a/test-app/runtime/src/main/cpp/FrameCallbacks.cpp b/test-app/runtime/src/main/cpp/FrameCallbacks.cpp index 7e14910df..c15400560 100644 --- a/test-app/runtime/src/main/cpp/FrameCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/FrameCallbacks.cpp @@ -1,6 +1,7 @@ #include "FrameCallbacks.h" #include +#include #include #include #include @@ -9,13 +10,10 @@ #include "NativeScriptAssert.h" #include #include -#include #include #include #include "ArgConverter.h" -#include "JEnv.h" -#include "JniLocalRef.h" #include "NativeScriptException.h" #include "Performance.h" #include "Runtime.h" @@ -28,35 +26,22 @@ namespace tns { namespace { -// ---- AChoreographer (NDK, API 24+), resolved through dlsym. +// ---- AChoreographer. The 64-bit frame-time variants are API 29, above the +// minimum, so they are resolved through dlsym. -struct AChoreographer; - -typedef void (*AChoreographer_frameCallback)(long frameTimeNanos, void* data); -typedef void (*AChoreographer_frameCallback64)(int64_t frameTimeNanos, - void* data); -typedef AChoreographer* (*func_getInstance)(); -typedef void (*func_postFrameCallback)(AChoreographer*, - AChoreographer_frameCallback, void*); typedef void (*func_postFrameCallback64)(AChoreographer*, AChoreographer_frameCallback64, void*); -typedef void (*func_postFrameCallbackDelayed)(AChoreographer*, - AChoreographer_frameCallback, - void*, long); typedef void (*func_postFrameCallbackDelayed64)(AChoreographer*, AChoreographer_frameCallback64, void*, uint32_t); -func_getInstance getInstance_ = nullptr; -func_postFrameCallback postFrameCallback_ = nullptr; -func_postFrameCallbackDelayed postFrameCallbackDelayed_ = nullptr; func_postFrameCallback64 postFrameCallback64_ = nullptr; func_postFrameCallbackDelayed64 postFrameCallbackDelayed64_ = nullptr; -void ResolveChoreographer() { +void ResolveChoreographer64() { static std::once_flag once; std::call_once(once, [] { - if (android_get_device_api_level() < 24) { + if (android_get_device_api_level() < 29) { return; } @@ -65,42 +50,14 @@ void ResolveChoreographer() { return; } - getInstance_ = reinterpret_cast( - dlsym(lib, "AChoreographer_getInstance")); - postFrameCallback_ = reinterpret_cast( - dlsym(lib, "AChoreographer_postFrameCallback")); - postFrameCallbackDelayed_ = reinterpret_cast( - dlsym(lib, "AChoreographer_postFrameCallbackDelayed")); - - if (android_get_device_api_level() >= 29) { - postFrameCallback64_ = reinterpret_cast( - dlsym(lib, "AChoreographer_postFrameCallback64")); - postFrameCallbackDelayed64_ = - reinterpret_cast( - dlsym(lib, "AChoreographer_postFrameCallbackDelayed64")); - } + postFrameCallback64_ = reinterpret_cast( + dlsym(lib, "AChoreographer_postFrameCallback64")); + postFrameCallbackDelayed64_ = + reinterpret_cast( + dlsym(lib, "AChoreographer_postFrameCallbackDelayed64")); }); } -bool NativeChoreographerAvailable() { - ResolveChoreographer(); - return getInstance_ != nullptr && postFrameCallback_ != nullptr && - postFrameCallbackDelayed_ != nullptr; -} - -// ---- Implementation selection. - -enum class Impl { kAuto, kNative, kJava }; - -Impl forcedImpl_ = Impl::kAuto; - -bool UseNativeChoreographer() { - if (forcedImpl_ == Impl::kJava) { - return false; - } - return NativeChoreographerAvailable(); -} - /* * AChoreographer_postFrameCallback hands the frame time as `long`, which is 32 * bits on the 32-bit ABIs and so wraps about every 4.3 s -- the reason @@ -125,24 +82,6 @@ int64_t WidenFrameTimeNanos(long ts) { // ---- Scheduled callbacks. -jclass FRAME_CALLBACKS_CLASS = nullptr; -jmethodID FRAME_CALLBACKS_CTOR = nullptr; -jmethodID FRAME_CALLBACKS_POST = nullptr; -jmethodID FRAME_CALLBACKS_RELEASE = nullptr; - -void ResolveFrameCallbacksClass(JEnv& env) { - static std::once_flag once; - std::call_once(once, [&env] { - // JEnv::FindClass caches a global ref to the class - FRAME_CALLBACKS_CLASS = env.FindClass("com/tns/FrameCallbacks"); - NS_CHECK(FRAME_CALLBACKS_CLASS != nullptr); - FRAME_CALLBACKS_CTOR = env.GetMethodID(FRAME_CALLBACKS_CLASS, "", "(J)V"); - FRAME_CALLBACKS_POST = env.GetMethodID(FRAME_CALLBACKS_CLASS, "post", "(J)V"); - FRAME_CALLBACKS_RELEASE = - env.GetMethodID(FRAME_CALLBACKS_CLASS, "release", "()V"); - }); -} - /* * Entries are identified to the platform by id rather than by address: an id * that no longer resolves is simply a frame arriving after its entry went @@ -161,17 +100,6 @@ struct FrameCallbackEntry { ~FrameCallbackEntry() { callback_.Reset(); - ReleaseJavaCallback(); - } - - void ReleaseJavaCallback() { - if (javaCallback_ == nullptr) { - return; - } - JEnv env; - env.CallVoidMethod(javaCallback_, FRAME_CALLBACKS_RELEASE); - env.DeleteGlobalRef(javaCallback_); - javaCallback_ = nullptr; } bool IsScheduled() const { @@ -211,7 +139,6 @@ struct FrameCallbackEntry { * touch entries carrying this flag. */ bool isAnimationFrame_; - jobject javaCallback_ = nullptr; private: bool removed_ = false; @@ -238,7 +165,7 @@ FrameCallbackEntry* FindEntryById(EntryId id) { /* * Detaches the entry from the registry and hands back its owner, so the - * destructor -- which calls into Java -- runs with the mutex released. + * destructor runs with the mutex released. */ std::unique_ptr TakeEntry(EntryId id) { std::lock_guard lock(entriesMutex_); @@ -252,7 +179,7 @@ std::unique_ptr TakeEntry(EntryId id) { } /* - * Never throws: on the NDK path this runs inside a C callback in libandroid, + * Never throws: this runs inside a C callback in libandroid, * which a C++ exception may not unwind through. A JS exception the runtime * still owns is handed to Java the way Timers::FireTimer does -- the frame * dispatch is driven by the thread's looper, so a pending Java exception is @@ -322,9 +249,10 @@ void OnNativeFrame64(int64_t ts, void* data) { Dispatch((EntryId) (uintptr_t) data, ts); } -void PostNative(EntryId id, long delayMillis) { +void Post(EntryId id, long delayMillis) { ALooper_prepare(0); - AChoreographer* instance = getInstance_(); + ResolveChoreographer64(); + AChoreographer* instance = AChoreographer_getInstance(); void* data = reinterpret_cast((uintptr_t) id); if (postFrameCallback64_ != nullptr && postFrameCallbackDelayed64_ != nullptr) { @@ -338,31 +266,10 @@ void PostNative(EntryId id, long delayMillis) { } if (delayMillis > 0) { - postFrameCallbackDelayed_(instance, &OnNativeFrame32, data, delayMillis); + AChoreographer_postFrameCallbackDelayed(instance, &OnNativeFrame32, data, + delayMillis); } else { - postFrameCallback_(instance, &OnNativeFrame32, data); - } -} - -void PostJava(FrameCallbackEntry* entry, long delayMillis) { - JEnv env; - ResolveFrameCallbacksClass(env); - - if (entry->javaCallback_ == nullptr) { - JniLocalRef instance(env.NewObject(FRAME_CALLBACKS_CLASS, FRAME_CALLBACKS_CTOR, - (jlong) entry->id_)); - entry->javaCallback_ = env.NewGlobalRef(instance); - } - - env.CallVoidMethod(entry->javaCallback_, FRAME_CALLBACKS_POST, - (jlong) delayMillis); -} - -void Post(FrameCallbackEntry* entry, long delayMillis) { - if (UseNativeChoreographer()) { - PostNative(entry->id_, delayMillis); - } else { - PostJava(entry, delayMillis); + AChoreographer_postFrameCallback(instance, &OnNativeFrame32, data); } } @@ -411,7 +318,7 @@ void FrameCallbacks::PostFrameCallback(const FunctionCallbackInfo& args) bool shouldPost = !existing->IsScheduled(); existing->MarkScheduled(); if (shouldPost) { - Post(existing, delayMillis); + Post(existing->id_, delayMillis); } return; } @@ -431,7 +338,7 @@ void FrameCallbacks::PostFrameCallback(const FunctionCallbackInfo& args) } entry->MarkScheduled(); - Post(entry, delayMillis); + Post(entry->id_, delayMillis); } void FrameCallbacks::RemoveFrameCallback(const FunctionCallbackInfo& args) { @@ -484,7 +391,7 @@ void FrameCallbacks::RequestAnimationFrame(const FunctionCallbackInfo& ar } entry->MarkScheduled(); - Post(entry, 0); + Post(entry->id_, 0); args.GetReturnValue().Set(Number::New(isolate, (double) id)); } @@ -508,8 +415,7 @@ void FrameCallbacks::CancelAnimationFrame(const FunctionCallbackInfo& arg } void FrameCallbacks::RemoveIsolateEntries(Isolate* isolate) { - // Detached first, destroyed after the mutex is released: the destructors - // call into Java. + // Detached first, destroyed after the mutex is released. std::vector> doomed; { std::lock_guard lock(entriesMutex_); @@ -540,53 +446,6 @@ void FrameCallbacks::Init(Isolate* isolate, Local globalTemplate globalTemplate->Set( ArgConverter::ConvertToV8String(isolate, "__removeFrameCallback"), FunctionTemplate::New(isolate, RemoveFrameCallback)); - -#ifdef APPLICATION_IN_DEBUG - /* - * Test-only override, absent from release runtimes: the NDK path is the - * only one a modern device would ever select, so the Java bridge would - * otherwise ship without device coverage. Takes "auto", "native" or - * "java" and returns the implementation subsequent posts will use. - */ - globalTemplate->Set( - ArgConverter::ConvertToV8String(isolate, "__setFrameCallbackImpl"), - FunctionTemplate::New( - isolate, [](const FunctionCallbackInfo& args) { - Isolate* isolate = args.GetIsolate(); - std::string requested = - args.Length() > 0 && args[0]->IsString() - ? ArgConverter::ConvertToString( - args[0].As()) - : "auto"; - if (requested == "java") { - forcedImpl_ = Impl::kJava; - } else if (requested == "native") { - forcedImpl_ = Impl::kNative; - } else { - forcedImpl_ = Impl::kAuto; - } - args.GetReturnValue().Set(ArgConverter::ConvertToV8String( - isolate, - UseNativeChoreographer() ? "native" : "java")); - })); -#endif } } // namespace tns - -extern "C" JNIEXPORT void JNICALL Java_com_tns_FrameCallbacks_nativeDoFrame( - JNIEnv* env, jclass clazz, jlong entryId, jlong frameTimeNanos) { - try { - tns::Dispatch((tns::EntryId) entryId, (int64_t) frameTimeNanos); - } catch (tns::NativeScriptException& e) { - e.ReThrowToJava(); - } catch (std::exception& e) { - std::stringstream ss; - ss << "Error: c++ exception: " << e.what() << std::endl; - tns::NativeScriptException nsEx(ss.str()); - nsEx.ReThrowToJava(); - } catch (...) { - tns::NativeScriptException nsEx(std::string("Error: c++ exception!")); - nsEx.ReThrowToJava(); - } -} diff --git a/test-app/runtime/src/main/cpp/FrameCallbacks.h b/test-app/runtime/src/main/cpp/FrameCallbacks.h index c97116145..ffe185456 100644 --- a/test-app/runtime/src/main/cpp/FrameCallbacks.h +++ b/test-app/runtime/src/main/cpp/FrameCallbacks.h @@ -25,15 +25,12 @@ namespace tns { * frameTimeNanos is the platform's raw frame time -- CLOCK_MONOTONIC * nanoseconds, the System.nanoTime() base -- and performanceMillis is the same * instant on this isolate's performance timeline, so it compares directly with - * performance.now(). Both are exact on either implementation below. + * performance.now(). Both are exact. * - * Two implementations sit behind the one JS surface: - * - AChoreographer (NDK, API 24+), reached through dlsym. - * - android.view.Choreographer (com.tns.FrameCallbacks), for API 21-23, - * where the NDK API does not exist. - * Scheduling is per calling thread, so a worker schedules against its own - * looper. Cancellation on either surface only marks the entry: a posted frame - * callback cannot be recalled, so the dispatch drops it instead. + * Frames come from the NDK's AChoreographer. Scheduling is per calling thread, + * so a worker schedules against its own looper. Cancellation on either surface + * only marks the entry: a posted frame callback cannot be recalled, so the + * dispatch drops it instead. */ class FrameCallbacks { public: diff --git a/test-app/runtime/src/main/java/com/tns/DexFactory.java b/test-app/runtime/src/main/java/com/tns/DexFactory.java index dd094e0a3..28788927f 100644 --- a/test-app/runtime/src/main/java/com/tns/DexFactory.java +++ b/test-app/runtime/src/main/java/com/tns/DexFactory.java @@ -1,6 +1,5 @@ package com.tns; -import android.os.Build; import android.util.Log; import com.tns.bindings.AnnotationDescriptor; @@ -23,9 +22,7 @@ import java.io.InputStreamReader; import java.io.InvalidClassException; import java.io.OutputStreamWriter; -import java.lang.reflect.Array; import java.lang.reflect.Constructor; -import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -596,7 +593,7 @@ private String generateDex(String proxyName, String contentDigest, String classN List defaultMethods = null; if (overridesDefaults) { defaultMethods = DefaultMethods.collect(classToProxy); - } else if ((!classToProxy.isInterface() || proxyName.contains(".")) && Build.VERSION.SDK_INT >= 24) { + } else if (!classToProxy.isInterface() || proxyName.contains(".")) { // An interface implementation with a dotted name is one extend() call's class, so // like a class it stubs only the default methods its implementation object names. List inheritedDefaults; @@ -744,61 +741,13 @@ private String getCachedProxyThumb(File proxyDir) { */ private boolean injectDexIntoClassLoader(BaseDexClassLoader targetClassLoader, String jarFilePath) { try { - if (Build.VERSION.SDK_INT >= 24) { - // BaseDexClassLoader.addDexPath exists since API 24 - Method addDexPath = BaseDexClassLoader.class.getDeclaredMethod("addDexPath", String.class); - addDexPath.setAccessible(true); - addDexPath.invoke(targetClassLoader, jarFilePath); - } else { - appendDexElements(targetClassLoader, jarFilePath); - } + Method addDexPath = BaseDexClassLoader.class.getDeclaredMethod("addDexPath", String.class); + addDexPath.setAccessible(true); + addDexPath.invoke(targetClassLoader, jarFilePath); return true; } catch (Exception e) { Log.w("JS", "Failed to inject dex into parent classloader: " + e); return false; } } - - /** - * Pre API 24 equivalent of BaseDexClassLoader.addDexPath: builds the dex elements - * through DexPathList's static factory methods (so no temporary class loader is - * involved) and splices them into the target loader's dexElements array. This is - * the same technique MultiDex used on these OS versions. - */ - private void appendDexElements(BaseDexClassLoader targetClassLoader, String jarFilePath) throws Exception { - Field pathListField = BaseDexClassLoader.class.getDeclaredField("pathList"); - pathListField.setAccessible(true); - Object pathList = pathListField.get(targetClassLoader); - - ArrayList files = new ArrayList(); - files.add(new File(jarFilePath)); - ArrayList suppressedExceptions = new ArrayList(); - - Object newElements; - if (Build.VERSION.SDK_INT >= 23) { - Method makePathElements = pathList.getClass().getDeclaredMethod("makePathElements", List.class, File.class, List.class); - makePathElements.setAccessible(true); - newElements = makePathElements.invoke(null, files, this.odexDir, suppressedExceptions); - } else { - Method makeDexElements = pathList.getClass().getDeclaredMethod("makeDexElements", ArrayList.class, File.class, ArrayList.class); - makeDexElements.setAccessible(true); - newElements = makeDexElements.invoke(null, files, this.odexDir, suppressedExceptions); - } - - if (!suppressedExceptions.isEmpty()) { - throw suppressedExceptions.get(0); - } - - Field dexElementsField = pathList.getClass().getDeclaredField("dexElements"); - dexElementsField.setAccessible(true); - Object oldElements = dexElementsField.get(pathList); - - int oldLen = Array.getLength(oldElements); - int newLen = Array.getLength(newElements); - Object merged = Array.newInstance(oldElements.getClass().getComponentType(), oldLen + newLen); - System.arraycopy(oldElements, 0, merged, 0, oldLen); - System.arraycopy(newElements, 0, merged, oldLen, newLen); - - dexElementsField.set(pathList, merged); - } } diff --git a/test-app/runtime/src/main/java/com/tns/FrameCallbacks.java b/test-app/runtime/src/main/java/com/tns/FrameCallbacks.java deleted file mode 100644 index 7fb305931..000000000 --- a/test-app/runtime/src/main/java/com/tns/FrameCallbacks.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.tns; - -import android.view.Choreographer; - -/** - * Frame callback bridge for API levels without the NDK's AChoreographer (which - * arrived in API 24). One instance per scheduled JS callback, bound to the - * Choreographer of the thread that scheduled it -- the thread that owns the - * isolate -- so doFrame arrives on that thread. Created and used exclusively - * from native code (FrameCallbacks.cpp). - */ -final class FrameCallbacks implements Choreographer.FrameCallback { - private final long entryId; - private final Choreographer choreographer; - // Read on the frame thread, set from Runtime teardown, which is not - // guaranteed to be that thread. - private volatile boolean released; - - // constructed from native code (FrameCallbacks::PostJava) - FrameCallbacks(long entryId) { - this.entryId = entryId; - this.choreographer = Choreographer.getInstance(); - } - - @RuntimeCallable - void post(long delayMillis) { - if (delayMillis > 0) { - choreographer.postFrameCallbackDelayed(this, delayMillis); - } else { - choreographer.postFrameCallback(this); - } - } - - /** - * Called from native when the entry is dropped. A frame already queued for - * this instance still arrives, so the flag -- not removeFrameCallback -- - * is what keeps it from reaching a retired native entry. - */ - @RuntimeCallable - void release() { - released = true; - choreographer.removeFrameCallback(this); - } - - @Override - public void doFrame(long frameTimeNanos) { - if (released) { - return; - } - nativeDoFrame(entryId, frameTimeNanos); - } - - private static native void nativeDoFrame(long entryId, long frameTimeNanos); -} diff --git a/test-app/runtime/src/main/java/com/tns/InterfaceProxyHandler.java b/test-app/runtime/src/main/java/com/tns/InterfaceProxyHandler.java index 0c493ecd1..7ee286904 100644 --- a/test-app/runtime/src/main/java/com/tns/InterfaceProxyHandler.java +++ b/test-app/runtime/src/main/java/com/tns/InterfaceProxyHandler.java @@ -1,7 +1,5 @@ package com.tns; -import android.os.Build; - import com.tns.bindings.DefaultMethods; import java.lang.reflect.InvocationHandler; @@ -61,7 +59,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl return proxy == args[0]; } - if (Build.VERSION.SDK_INT >= 24 && method.isDefault() && !isOverriddenInJs(proxy.getClass(), method)) { + if (method.isDefault() && !isOverriddenInJs(proxy.getClass(), method)) { return Runtime.invokeInterfaceDefault(proxy, method, args); } diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index c9e5ea27f..536c109fa 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1021,9 +1021,6 @@ private int createJSInstance(Object instance) { */ @RuntimeCallable private static String[] getDefaultMethodNames(String interfaceName) { - if (android.os.Build.VERSION.SDK_INT < 24) { - return new String[0]; - } try { Class iface = classStorageService.retrieveClass(interfaceName.replace('/', '.')); String[] names = DefaultMethods.names(iface);