Skip to content

Commit 9e450ec

Browse files
authored
fix: turn every C++ exception of a JNI entry point into a Java one (#530)
* fix: free the local class references of the JNI helpers GetFieldID on an object and the class name lookup of JavaContext left the class of GetObjectClass behind. On a native thread attached for a callback, nothing frees local references until the thread detaches. The class loader no longer creates a global reference while an exception is pending. * fix: test under -Xcheck:jni on macOS and Windows as well The jni-check job also runs on macOS arm64 and Windows x86_64, whose device modules, capturers and codecs reach Java on code paths of their own. Ahead of that, the paths only real devices take check their JNI calls: an AudioSource that throws on the playout thread is reported instead of leaving the exception pending, and a device whose Java constructor threw is not filled in. * fix: turn every C++ exception of a JNI entry point into a Java one A C++ exception that reaches the VM ends the process. jni::CallFromJava runs the body of an entry point and turns any into a Java exception, the way the entry points with a try block of their own do. It now guards those that had none, or that called a throwing helper before their try block.
1 parent 18bf090 commit 9e450ec

37 files changed

Lines changed: 1360 additions & 919 deletions

‎.github/actions/test-natives/jni-check-report.sh‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ fatal=$(grep -c 'FATAL ERROR in native method' "$log" || true)
2222
warnings=$(grep -cE 'WARNING in native method|WARNING: JNI local refs' "$log" || true)
2323

2424
summary=$(awk '
25+
# The JVM on Windows ends some lines with CRLF.
26+
{ sub(/\r$/, "") }
2527
function flush() {
2628
if (kind != "") {
2729
key = kind " | " (frame != "" ? frame : (native ? "<thread without Java frames>" : "<no stack>"))

‎.github/workflows/platforms.yml‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -158,14 +158,29 @@ jobs:
158158
java-architecture: ${{ matrix.platform.java-architecture }}
159159
version: ${{ inputs.version }}
160160

161-
# The tests once more under -Xcheck:jni, on one platform only: the JNI code
162-
# is the same on all of them, and its exception checks are what this is
163-
# about. It fails on any JNI error or warning, see the test-natives action.
161+
# The tests once more under -Xcheck:jni, once per OS: the JNI glue is shared,
162+
# but the device modules, capturers and hardware codecs that call back into
163+
# Java are not, so each OS has JNI code of its own. One architecture each is
164+
# enough, since that code is the same across them. It fails on any JNI error
165+
# or warning, see the test-natives action.
164166
jni-check:
165-
name: jni-check (linux_x86-64)
167+
name: jni-check (${{ matrix.platform.name }})
166168
needs: build
167169
timeout-minutes: 30
168-
runs-on: ubuntu-22.04
170+
strategy:
171+
fail-fast: false
172+
matrix:
173+
platform:
174+
- name: linux_x86-64
175+
runs-on: ubuntu-22.04
176+
classifier: linux-x86_64
177+
- name: macos_arm64
178+
runs-on: macos-15
179+
classifier: macos-aarch64
180+
- name: windows_x86_64
181+
runs-on: windows-2022
182+
classifier: windows-x86_64
183+
runs-on: ${{ matrix.platform.runs-on }}
169184
steps:
170185
- name: Checkout code
171186
uses: actions/checkout@v7
@@ -175,9 +190,9 @@ jobs:
175190
- name: Test natives under -Xcheck:jni
176191
uses: ./.github/actions/test-natives
177192
with:
178-
platform-name: linux_x86-64
179-
classifier: linux-x86_64
180-
profile: linux-x86_64
193+
platform-name: ${{ matrix.platform.name }}
194+
classifier: ${{ matrix.platform.classifier }}
195+
profile: ${{ matrix.platform.classifier }}
181196
java-distribution: temurin
182197
version: ${{ inputs.version }}
183198
jni-check: 'true'

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ target_sources(${PROJECT_NAME}
1010
include/JavaArray.h
1111
include/JavaArrayList.h
1212
include/JavaBigInteger.h
13+
include/JavaBoundary.h
1314
include/JavaClasses.h
1415
include/JavaClass.h
1516
include/JavaClassLoader.h
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
* Copyright (c) 2026, Alex Andres. All rights reserved.
3+
*
4+
* Use of this source code is governed by the 3-Clause BSD license that can be
5+
* found in the LICENSE file in the root of the source tree.
6+
*/
7+
8+
#ifndef JNI_JAVA_BOUNDARY_H_
9+
#define JNI_JAVA_BOUNDARY_H_
10+
11+
#include "JavaUtils.h"
12+
13+
#include <jni.h>
14+
15+
namespace jni
16+
{
17+
namespace detail
18+
{
19+
// What a native method returns when its body failed: null, zero or
20+
// false, which Java never sees, since an exception is pending then.
21+
template <typename R>
22+
struct FailedReturn
23+
{
24+
static R value()
25+
{
26+
return R();
27+
}
28+
};
29+
30+
template <>
31+
struct FailedReturn<void>
32+
{
33+
static void value()
34+
{
35+
}
36+
};
37+
}
38+
39+
// Runs the body of a JNI entry point. A C++ exception that reaches the VM
40+
// ends the process, and the helpers of this library throw them: a Java
41+
// exception they ran into as JavaWrappedException, a failed allocation as
42+
// std::bad_alloc. Here every C++ exception becomes a Java one, with
43+
// ThrowCxxJavaException(), and the entry point returns null, zero or
44+
// false. What the body holds is released before that, so a destructor may
45+
// still call into Java. The body's own returns, also those of
46+
// CHECK_HANDLE, return from the entry point as before:
47+
//
48+
// JNIEXPORT jobject JNICALL Java_..._getFoo(JNIEnv * env, jobject caller)
49+
// {
50+
// return jni::CallFromJava(env, [&]() -> jobject {
51+
// ...
52+
// });
53+
// }
54+
//
55+
// A body that catches its own exceptions, such as one with a try block of
56+
// its own around everything that may throw, needs none of this.
57+
template <typename Body>
58+
auto CallFromJava(JNIEnv * env, Body && body) noexcept -> decltype(body())
59+
{
60+
try {
61+
return body();
62+
}
63+
catch (...) {
64+
ThrowCxxJavaException(env);
65+
}
66+
67+
return detail::FailedReturn<decltype(body())>::value();
68+
}
69+
}
70+
71+
#endif

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassLoader.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@ namespace jni
1919
explicit JavaClassLoader(JNIEnv * env, const JavaGlobalRef<jobject> & classLoader) :
2020
classLoader(classLoader)
2121
{
22-
classLoaderClass_ = reinterpret_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/ClassLoader")));
22+
JavaLocalRef<jclass> cls(env, env->FindClass("java/lang/ClassLoader"));
2323

2424
if (ExceptionCheck(env)) {
2525
return;
2626
}
2727

28+
classLoaderClass_ = reinterpret_cast<jclass>(env->NewGlobalRef(cls.get()));
29+
2830
loadClass = env->GetMethodID(classLoaderClass_, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
2931

3032
ExceptionCheck(env);

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,17 @@ namespace jni
1313
{
1414
JavaClassUtils::JavaClassUtils(JNIEnv * env)
1515
{
16-
jclass cls = env->FindClass("java/lang/Class");
16+
JavaLocalRef<jclass> cls(env, env->FindClass("java/lang/Class"));
1717

18-
getClassName = GetMethod(env, cls, "getName", "()Ljava/lang/String;");
18+
getClassName = GetMethod(env, cls.get(), "getName", "()Ljava/lang/String;");
1919
}
2020

2121
std::string JavaClassUtils::toNativeClassName(JNIEnv * env, const JavaLocalRef<jobject> & javaRef)
2222
{
2323
const auto classUtils = JavaClasses::get<JavaClassUtils>(env);
2424

25-
jclass cls = env->GetObjectClass(javaRef.get());
26-
jstring clsName = static_cast<jstring>(env->CallObjectMethod(cls, classUtils->getClassName));
25+
JavaLocalRef<jclass> cls(env, env->GetObjectClass(javaRef.get()));
26+
jstring clsName = static_cast<jstring>(env->CallObjectMethod(cls.get(), classUtils->getClassName));
2727
ExceptionCheck(env);
2828

2929
return JavaString::toNative(env, JavaLocalRef<jstring>(env, clsName));

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,14 +190,16 @@ jfieldID GetHandleField(JNIEnv * env, jobject obj, const std::string & fieldName
190190

191191
jfieldID GetFieldID(JNIEnv * env, jobject obj, const std::string & fieldName, const char * type)
192192
{
193-
jclass cls = env->GetObjectClass(obj);
193+
// Deleted on return: on a native thread attached for a callback, nothing
194+
// else frees local references until the thread detaches.
195+
jni::JavaLocalRef<jclass> cls(env, env->GetObjectClass(obj));
194196

195-
if (cls == nullptr) {
197+
if (cls.get() == nullptr) {
196198
ExceptionCheck(env);
197199
return nullptr;
198200
}
199201

200-
return GetFieldID(env, cls, fieldName, type);
202+
return GetFieldID(env, cls.get(), fieldName, type);
201203
}
202204

203205
jfieldID GetFieldID(JNIEnv * env, jclass cls, const std::string & fieldName, const char * type)

‎webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp‎

Lines changed: 47 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616

1717
#include "JNI_AudioConverter.h"
18+
#include "JavaBoundary.h"
1819
#include "NativeHandle.h"
1920
#include "api/audio/audio_processing.h"
2021
#include "media/audio/AudioConverter.h"
@@ -26,62 +27,66 @@
2627
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_convertInternal
2728
(JNIEnv * env, jobject caller, jbyteArray src, jint nSrcSamples, jbyteArray dst, jint nDstSamples)
2829
{
29-
jni::NativeLease<jni::AudioConverter> converter(env, caller);
30-
CHECK_HANDLE(converter);
30+
jni::CallFromJava(env, [&]() {
31+
jni::NativeLease<jni::AudioConverter> converter(env, caller);
32+
CHECK_HANDLE(converter);
3133

32-
if (src == nullptr || dst == nullptr) {
33-
ThrowJavaException(env, "java/lang/NullPointerException", "Sample arrays must not be null");
34-
return;
35-
}
36-
37-
// The counts are samples over all channels. The converter checks them against its format, this the arrays.
38-
const jlong bytesPerSample = sizeof(int16_t);
39-
40-
if (nSrcSamples < 0 || nDstSamples < 0 ||
41-
env->GetArrayLength(src) < nSrcSamples * bytesPerSample || env->GetArrayLength(dst) < nDstSamples * bytesPerSample) {
42-
ThrowJavaException(env, "java/lang/IllegalArgumentException", "Sample arrays too short for the requested samples");
43-
return;
44-
}
45-
46-
try {
47-
auto releaseSrc = [env, src](jbyte * bytes) {
48-
env->ReleaseByteArrayElements(src, bytes, JNI_ABORT);
49-
};
50-
std::unique_ptr<jbyte, decltype(releaseSrc)> srcPtr(env->GetByteArrayElements(src, nullptr), releaseSrc);
51-
if (!srcPtr) {
34+
if (src == nullptr || dst == nullptr) {
35+
ThrowJavaException(env, "java/lang/NullPointerException", "Sample arrays must not be null");
5236
return;
5337
}
5438

55-
// Mode 0 writes the samples back when the VM handed out a copy.
56-
auto releaseDst = [env, dst](jbyte * bytes) {
57-
env->ReleaseByteArrayElements(dst, bytes, 0);
58-
};
59-
std::unique_ptr<jbyte, decltype(releaseDst)> dstPtr(env->GetByteArrayElements(dst, nullptr), releaseDst);
60-
if (!dstPtr) {
39+
// The counts are samples over all channels. The converter checks them against its format, this the arrays.
40+
const jlong bytesPerSample = sizeof(int16_t);
41+
42+
if (nSrcSamples < 0 || nDstSamples < 0 ||
43+
env->GetArrayLength(src) < nSrcSamples * bytesPerSample || env->GetArrayLength(dst) < nDstSamples * bytesPerSample) {
44+
ThrowJavaException(env, "java/lang/IllegalArgumentException", "Sample arrays too short for the requested samples");
6145
return;
6246
}
6347

64-
converter->convert(reinterpret_cast<const int16_t *>(srcPtr.get()), nSrcSamples, reinterpret_cast<int16_t *>(dstPtr.get()), nDstSamples);
65-
}
66-
catch (const std::invalid_argument & e) {
67-
ThrowJavaException(env, "java/lang/IllegalArgumentException", e.what());
68-
}
69-
catch (...) {
70-
ThrowCxxJavaException(env);
71-
}
48+
try {
49+
auto releaseSrc = [env, src](jbyte * bytes) {
50+
env->ReleaseByteArrayElements(src, bytes, JNI_ABORT);
51+
};
52+
std::unique_ptr<jbyte, decltype(releaseSrc)> srcPtr(env->GetByteArrayElements(src, nullptr), releaseSrc);
53+
if (!srcPtr) {
54+
return;
55+
}
56+
57+
// Mode 0 writes the samples back when the VM handed out a copy.
58+
auto releaseDst = [env, dst](jbyte * bytes) {
59+
env->ReleaseByteArrayElements(dst, bytes, 0);
60+
};
61+
std::unique_ptr<jbyte, decltype(releaseDst)> dstPtr(env->GetByteArrayElements(dst, nullptr), releaseDst);
62+
if (!dstPtr) {
63+
return;
64+
}
65+
66+
converter->convert(reinterpret_cast<const int16_t *>(srcPtr.get()), nSrcSamples, reinterpret_cast<int16_t *>(dstPtr.get()), nDstSamples);
67+
}
68+
catch (const std::invalid_argument & e) {
69+
ThrowJavaException(env, "java/lang/IllegalArgumentException", e.what());
70+
}
71+
catch (...) {
72+
ThrowCxxJavaException(env);
73+
}
74+
});
7275
}
7376

7477
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_dispose
7578
(JNIEnv * env, jobject caller)
7679
{
77-
jni::AudioConverter * converter = jni::TakeHandle<jni::AudioConverter>(env, caller);
80+
jni::CallFromJava(env, [&]() {
81+
jni::AudioConverter * converter = jni::TakeHandle<jni::AudioConverter>(env, caller);
7882

79-
if (converter == nullptr) {
80-
return;
81-
}
83+
if (converter == nullptr) {
84+
return;
85+
}
8286

83-
jni::ReleaseHandle(env, converter, [converter](bool) {
84-
delete converter;
87+
jni::ReleaseHandle(env, converter, [converter](bool) {
88+
delete converter;
89+
});
8590
});
8691
}
8792

0 commit comments

Comments
 (0)