From 9e2a57700fb8f90b12c9377698fc81ab98f1b409 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 09:43:08 +0100 Subject: [PATCH] fix: check every JNI call for exceptions and test under -Xcheck:jni in CI The iterator, map, list and boxing helpers, the VideoFrame buffer conversion and the uncaught exception reporting now check each Java call before the next JNI call, so the tests run without any -Xcheck:jni warning. A new CI job reruns the tests under -Xcheck:jni on linux x86_64 and fails on any JNI error or warning. --- .github/actions/test-natives/action.yml | 33 ++++++- .../actions/test-natives/jni-check-report.sh | 85 +++++++++++++++++++ .github/workflows/platforms.yml | 24 ++++++ .../jni-voithos/include/JavaEnum.h | 1 + .../jni-voithos/include/JavaPrimitive.h | 4 +- .../jni-voithos/src/JavaArrayList.cpp | 15 +++- .../jni-voithos/src/JavaClassUtils.cpp | 1 + .../jni-voithos/src/JavaHashMap.cpp | 1 + .../jni-voithos/src/JavaIterable.cpp | 3 + .../jni-voithos/src/JavaMapIterator.cpp | 5 ++ webrtc-jni/src/main/cpp/src/WebRTCContext.cpp | 5 +- .../src/main/cpp/src/api/VideoFrame.cpp | 31 ++++--- .../src/main/cpp/src/api/WebRTCUtils.cpp | 5 ++ webrtc-media/pom.xml | 6 +- .../src/main/cpp/src/media/JniBoundary.cpp | 6 ++ webrtc/pom.xml | 27 +++--- .../onvoid/webrtc/RTCRtpTransceiverTests.java | 39 +++++++++ 17 files changed, 261 insertions(+), 30 deletions(-) create mode 100644 .github/actions/test-natives/jni-check-report.sh diff --git a/.github/actions/test-natives/action.yml b/.github/actions/test-natives/action.yml index 22cfb8103..2897f925f 100644 --- a/.github/actions/test-natives/action.yml +++ b/.github/actions/test-natives/action.yml @@ -35,6 +35,11 @@ inputs: required: false default: '' + jni-check: + description: 'Run the tests under -Xcheck:jni instead, and fail on any JNI error or warning it reports.' + required: false + default: 'false' + runs: using: "composite" steps: @@ -144,17 +149,43 @@ runs: - name: Test run: mvn -B -pl webrtc,webrtc-media test -DskipNativeBuild -P${{ inputs.profile }} -Dsurefire.timeout=1800 shell: bash + if: inputs.jni-check != 'true' + + # The same tests under -Xcheck:jni, which checks every JNI call of the + # natives: a fatal error ends the test JVM, and a call made without + # checking for the exception the previous one may have thrown is a + # warning. The JVM writes them to native stdout, so the log goes to a file: + # one warning comes with a whole stack, and many of them would make an + # unreadable job log. The report counts them, sums them up by where they + # come from and fails on any, so that a missing check cannot creep back in. + - name: Test under -Xcheck:jni + if: inputs.jni-check == 'true' + run: | + status=0 + mvn -B -pl webrtc,webrtc-media test -DskipNativeBuild -P${{ inputs.profile }} -Pjni-check \ + -Dsurefire.timeout=1800 > jni-check.log 2>&1 || status=$? + + # What Maven reported about the tests, which went to the file as well. + grep -E '^\[(INFO|WARNING|ERROR)\] (Tests run:|BUILD|Reactor Summary)|^\[ERROR\]' jni-check.log | tail -n 200 || true + + bash "$GITHUB_ACTION_PATH/jni-check-report.sh" jni-check.log 0 || status=1 + + exit $status + shell: bash # What failed, for runners that cannot be reproduced locally. - name: Upload test reports if: failure() uses: actions/upload-artifact@v7 with: - name: test-reports-native-${{ inputs.platform-name }} + name: test-reports-native-${{ inputs.platform-name }}${{ inputs.jni-check == 'true' && '-jni-check' || '' }} # A native crash ends the test JVM with a report of its own beside the # module, which names the thread that crashed and what it ran. + # Under -Xcheck:jni, the first of its diagnostics with their stacks, + # rather than the whole log. path: | **/target/surefire-reports/ **/hs_err_pid*.log + jni-check-excerpt.txt if-no-files-found: ignore retention-days: 7 diff --git a/.github/actions/test-natives/jni-check-report.sh b/.github/actions/test-natives/jni-check-report.sh new file mode 100644 index 000000000..b253d3f76 --- /dev/null +++ b/.github/actions/test-natives/jni-check-report.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# +# Evaluates the output of a test run under -Xcheck:jni. The JVM writes its +# diagnostics straight to native stdout, one block each: the message, then the +# Java stack of the thread (or its native frames on a thread without Java +# frames). Fails on any fatal error, and on more warnings than allowed. +# +# Usage: jni-check-report.sh [max-warnings] +# +# A summary groups the warnings by the JNI function whose exception was left +# unchecked and by the native method the warning was raised in, which is where +# to look for the missing check. On failure, the first diagnostics with their +# stacks go to jni-check-excerpt.txt, since the whole log can grow to hundreds +# of megabytes. + +set -euo pipefail + +log="$1" +max_warnings="${2:-0}" + +fatal=$(grep -c 'FATAL ERROR in native method' "$log" || true) +warnings=$(grep -cE 'WARNING in native method|WARNING: JNI local refs' "$log" || true) + +summary=$(awk ' + function flush() { + if (kind != "") { + key = kind " | " (frame != "" ? frame : (native ? "" : "")) + count[key]++ + } + kind = "" + } + /WARNING in native method|WARNING: JNI local refs/ { + flush() + kind = $0 + sub(/.*when required to from /, "", kind) + sub(/.*WARNING in native method: /, "", kind) + sub(/.*WARNING: /, "", kind) + gsub(/[0-9]+/, "N", kind) + frame = "" + native = 0 + next + } + kind != "" && /^\tat / { + if (frame == "" && index($0, "Native Method)") > 0) { + frame = $0 + sub(/^\tat /, "", frame) + sub(/\(.*$/, "", frame) + } + next + } + kind != "" && /^\t- / { next } + kind != "" && (/^Native frames/ || /^[VCvjJ] /) { native = 1; next } + kind != "" { flush() } + END { + flush() + for (key in count) printf "%8d %s\n", count[key], key + } +' "$log" | sort -rn | head -n 25) + +echo "-Xcheck:jni: $fatal fatal errors, $warnings warnings (at most $max_warnings allowed)" + +if [ -n "$summary" ]; then + echo "Warnings by unchecked JNI function and native method:" + echo "$summary" +fi + +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + { + echo "### -Xcheck:jni" + echo + echo "$fatal fatal errors, $warnings warnings (at most $max_warnings allowed)." + if [ -n "$summary" ]; then + echo + echo '```' + echo "$summary" + echo '```' + fi + } >> "$GITHUB_STEP_SUMMARY" +fi + +if [ "$fatal" -gt 0 ] || [ "$warnings" -gt "$max_warnings" ]; then + grep -n -A 25 -m 100 -E 'FATAL ERROR in native method|WARNING in native method|WARNING: JNI local refs' "$log" \ + > jni-check-excerpt.txt || true + exit 1 +fi diff --git a/.github/workflows/platforms.yml b/.github/workflows/platforms.yml index 259cb3ddd..2e18a9a75 100644 --- a/.github/workflows/platforms.yml +++ b/.github/workflows/platforms.yml @@ -157,3 +157,27 @@ jobs: java-distribution: ${{ matrix.platform.java-distribution }} java-architecture: ${{ matrix.platform.java-architecture }} version: ${{ inputs.version }} + + # The tests once more under -Xcheck:jni, on one platform only: the JNI code + # is the same on all of them, and its exception checks are what this is + # about. It fails on any JNI error or warning, see the test-natives action. + jni-check: + name: jni-check (linux_x86-64) + needs: build + timeout-minutes: 30 + runs-on: ubuntu-22.04 + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + + - name: Test natives under -Xcheck:jni + uses: ./.github/actions/test-natives + with: + platform-name: linux_x86-64 + classifier: linux-x86_64 + profile: linux-x86_64 + java-distribution: temurin + version: ${{ inputs.version }} + jni-check: 'true' diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaEnum.h b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaEnum.h index 76dccb091..96f651912 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaEnum.h +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaEnum.h @@ -46,6 +46,7 @@ namespace jni jmethodID enumValues = GetStaticMethod(env, enumClass, "values", valuesSig.c_str()); jobject val = env->CallStaticObjectMethod(enumClass, enumValues); + ExceptionCheck(env); values = JavaGlobalRef(env, static_cast(val)); valuesLength = env->GetArrayLength(values.get()); diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaPrimitive.h b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaPrimitive.h index d7d0393e1..055a496b3 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaPrimitive.h +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaPrimitive.h @@ -57,7 +57,9 @@ class className \ static retType getValue(JNIEnv * env, jobject obj) \ { \ const auto javaClass = JavaClasses::get(env); \ - return env->mCall(obj, javaClass->value); \ + const retType value = env->mCall(obj, javaClass->value); \ + ExceptionCheck(env); \ + return value; \ } \ \ private: \ diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaArrayList.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaArrayList.cpp index 504dc8f8f..f4e997183 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaArrayList.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaArrayList.cpp @@ -20,17 +20,26 @@ namespace jni bool JavaArrayList::add(const JavaRef & obj) { - return env->CallBooleanMethod(list, classDef->add, obj.get()); + const bool added = env->CallBooleanMethod(list, classDef->add, obj.get()); + ExceptionCheck(env); + + return added; } JavaLocalRef JavaArrayList::get(int index) { - return JavaLocalRef(env, env->CallObjectMethod(list, classDef->get, index)); + JavaLocalRef element(env, env->CallObjectMethod(list, classDef->get, index)); + ExceptionCheck(env); + + return element; } int JavaArrayList::size() { - return env->CallIntMethod(list, classDef->size); + const int size = env->CallIntMethod(list, classDef->size); + ExceptionCheck(env); + + return size; } JavaLocalRef JavaArrayList::listObject() diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp index 0d08303d8..53d07765a 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp @@ -24,6 +24,7 @@ namespace jni jclass cls = env->GetObjectClass(javaRef.get()); jstring clsName = static_cast(env->CallObjectMethod(cls, classUtils->getClassName)); + ExceptionCheck(env); return JavaString::toNative(env, JavaLocalRef(env, clsName)); } diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaHashMap.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaHashMap.cpp index 60c6decb6..8a14777df 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaHashMap.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaHashMap.cpp @@ -41,6 +41,7 @@ namespace jni JavaMapIterator JavaHashMap::begin() { JavaLocalRef entrySet = JavaLocalRef(env, env->CallObjectMethod(jMap, mapClass->entrySet)); + ExceptionCheck(env); return JavaMapIterator(env, entrySet); } diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaIterable.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaIterable.cpp index 3ab5ee0b2..4998890ae 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaIterable.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaIterable.cpp @@ -30,6 +30,7 @@ namespace jni } iterator = JavaLocalRef(env, env->CallObjectMethod(iterable, iterableClass->iterator)); + ExceptionCheck(env); // Start at the first element. ++(*this); @@ -50,6 +51,7 @@ namespace jni } bool hasNext = env->CallBooleanMethod(iterator, iterableClass->iteratorHasNext); + ExceptionCheck(env); if (!hasNext) { iterator = nullptr; @@ -58,6 +60,7 @@ namespace jni } value = JavaLocalRef(env, env->CallObjectMethod(iterator, iterableClass->iteratorNext)); + ExceptionCheck(env); return *this; } diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaMapIterator.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaMapIterator.cpp index 9754cd237..f146008b6 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaMapIterator.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaMapIterator.cpp @@ -29,6 +29,7 @@ namespace jni } iterator = JavaLocalRef(env, env->CallObjectMethod(iterable, mapIteratorClass->iterator)); + ExceptionCheck(env); // Start at the first element. ++(*this); @@ -49,6 +50,7 @@ namespace jni } bool hasNext = env->CallBooleanMethod(iterator, mapIteratorClass->iteratorHasNext); + ExceptionCheck(env); if (!hasNext) { iterator = nullptr; @@ -57,8 +59,11 @@ namespace jni } auto mapEntry = JavaLocalRef(env, env->CallObjectMethod(iterator, mapIteratorClass->iteratorNext)); + ExceptionCheck(env); auto key = JavaLocalRef(env, env->CallObjectMethod(mapEntry, mapIteratorClass->getKey)); + ExceptionCheck(env); auto value = JavaLocalRef(env, env->CallObjectMethod(mapEntry, mapIteratorClass->getValue)); + ExceptionCheck(env); entry = std::make_pair(key, value); diff --git a/webrtc-jni/src/main/cpp/src/WebRTCContext.cpp b/webrtc-jni/src/main/cpp/src/WebRTCContext.cpp index d7917a969..fc9487217 100644 --- a/webrtc-jni/src/main/cpp/src/WebRTCContext.cpp +++ b/webrtc-jni/src/main/cpp/src/WebRTCContext.cpp @@ -145,7 +145,10 @@ namespace jni auto javaGet = GetStaticMethod(env, javaClass, "getClassLoader", "()Ljava/lang/ClassLoader;"); - auto loaderRef = jni::JavaGlobalRef(env, env->CallStaticObjectMethod(javaClass, javaGet)); + jni::JavaLocalRef loader(env, env->CallStaticObjectMethod(javaClass, javaGet)); + ExceptionCheck(env); + + auto loaderRef = jni::JavaGlobalRef(env, loader.get()); InitClassLoader(env, loaderRef); } diff --git a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp index 21748f4f0..b183a14ab 100644 --- a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp +++ b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp @@ -158,17 +158,28 @@ namespace jni return webrtc::scoped_refptr(buffer); } - const jint width = env->CallIntMethod(i420, javaClass->getWidth); - const jint height = env->CallIntMethod(i420, javaClass->getHeight); - const jint strideY = env->CallIntMethod(i420, javaClass->getStrideY); - const jint strideU = env->CallIntMethod(i420, javaClass->getStrideU); - const jint strideV = env->CallIntMethod(i420, javaClass->getStrideV); - ExceptionCheck(env); + // Each call is checked before the next one: a buffer's getter may + // throw, and no JNI call may follow with its exception pending. + auto callInt = [&](jmethodID method) { + const jint value = env->CallIntMethod(i420, method); + ExceptionCheck(env); + return value; + }; + auto callObject = [&](jmethodID method) { + JavaLocalRef value(env, env->CallObjectMethod(i420, method)); + ExceptionCheck(env); + return value; + }; - JavaLocalRef dataY(env, env->CallObjectMethod(i420, javaClass->getDataY)); - JavaLocalRef dataU(env, env->CallObjectMethod(i420, javaClass->getDataU)); - JavaLocalRef dataV(env, env->CallObjectMethod(i420, javaClass->getDataV)); - ExceptionCheck(env); + const jint width = callInt(javaClass->getWidth); + const jint height = callInt(javaClass->getHeight); + const jint strideY = callInt(javaClass->getStrideY); + const jint strideU = callInt(javaClass->getStrideU); + const jint strideV = callInt(javaClass->getStrideV); + + JavaLocalRef dataY = callObject(javaClass->getDataY); + JavaLocalRef dataU = callObject(javaClass->getDataU); + JavaLocalRef dataV = callObject(javaClass->getDataV); if (dataY.get() == nullptr || dataU.get() == nullptr || dataV.get() == nullptr) { return nullptr; diff --git a/webrtc-jni/src/main/cpp/src/api/WebRTCUtils.cpp b/webrtc-jni/src/main/cpp/src/api/WebRTCUtils.cpp index 420e7640f..664a6b81a 100644 --- a/webrtc-jni/src/main/cpp/src/api/WebRTCUtils.cpp +++ b/webrtc-jni/src/main/cpp/src/api/WebRTCUtils.cpp @@ -50,6 +50,11 @@ namespace jni } JavaLocalRef thread(env, env->CallStaticObjectMethod(threadClass.get(), currentThread)); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + return; + } + JavaLocalRef handler(env, env->CallObjectMethod(thread.get(), getHandler)); if (!env->ExceptionCheck() && handler.get()) { env->CallVoidMethod(handler.get(), uncaughtException, thread.get(), exception); diff --git a/webrtc-media/pom.xml b/webrtc-media/pom.xml index cd9f8983f..040c1a3bd 100644 --- a/webrtc-media/pom.xml +++ b/webrtc-media/pom.xml @@ -348,8 +348,10 @@ + mistake into a hard error instead of a crash somewhere later, and + warns about a JNI call made with the previous one's exception left + unchecked. CI's jni-check job fails on either; see the profile of + the same name in webrtc/pom.xml. --> jni-check diff --git a/webrtc-media/src/main/cpp/src/media/JniBoundary.cpp b/webrtc-media/src/main/cpp/src/media/JniBoundary.cpp index e26e7a63c..fe834a1a4 100644 --- a/webrtc-media/src/main/cpp/src/media/JniBoundary.cpp +++ b/webrtc-media/src/main/cpp/src/media/JniBoundary.cpp @@ -233,6 +233,12 @@ namespace ffmpeg } LocalRef thread(env, env->CallStaticObjectMethod(thread_class.get(), current_thread)); + + if (env->ExceptionCheck() == JNI_TRUE) { + env->ExceptionClear(); + return; + } + LocalRef handler(env, env->CallObjectMethod(thread.get(), get_handler)); if (env->ExceptionCheck() == JNI_FALSE && handler.get() != nullptr) { diff --git a/webrtc/pom.xml b/webrtc/pom.xml index 5c6de9328..7af451c02 100644 --- a/webrtc/pom.xml +++ b/webrtc/pom.xml @@ -36,17 +36,17 @@ jni-check diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpTransceiverTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpTransceiverTests.java index 6b1914e5a..aadc5a1ae 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpTransceiverTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpTransceiverTests.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import dev.onvoid.webrtc.media.MediaType; @@ -14,7 +15,10 @@ import dev.onvoid.webrtc.media.video.VideoTrack; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -126,4 +130,39 @@ void stopImmediatelyRejectsInAnswer() throws Exception { } } + @Test + void throwingParametersStopConversion() { + RTCRtpCodecCapability codec = factory.getRtpReceiverCapabilities(MediaType.AUDIO) + .getCodecs().get(0); + + // A codec WebRTC supports, but whose parameters fail to be read. The + // native code used to go on with the exception pending, making more + // JNI calls and handing WebRTC a codec without them. + Map parameters = new HashMap() { + + @Override + public Set> entrySet() { + throw new IllegalStateException("Parameters cannot be read"); + } + }; + + RTCRtpCodecCapability preference = new RTCRtpCodecCapability(codec.getMediaType(), + codec.getName(), codec.getClockRate(), codec.getChannels(), parameters); + + AudioTrackSource audioSource = factory.createAudioSource(new AudioOptions()); + AudioTrack audioTrack = factory.createAudioTrack("audioTrack", audioSource); + + RTCRtpTransceiver transceiver = connection.getPeerConnection().addTransceiver(audioTrack, + new RTCRtpTransceiverInit()); + + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> transceiver.setCodecPreferences(List.of(preference))); + + assertEquals("Parameters cannot be read", e.getMessage()); + List preferences = transceiver.getCodecPreferences(); + + // Still none set, which comes back as null. + assertTrue(preferences == null || preferences.isEmpty(), String.valueOf(preferences)); + } + }