From 0c49ab34be45cb861d3c21b0e61a1442f88ba771 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 15:10:44 +0100 Subject: [PATCH] feat: report native objects that were never disposed With -Dwebrtc.java.leak.detection=true, a NativeObject that owns a native object and becomes unreachable without dispose() or close() is reported as a warning through Logging, with where it was created when -Dwebrtc.java.leak.trace=true is set as well. Objects are watched from the moment native code binds their handle and released when it is taken or cleared; views and reference-counted objects are not watched. Off by default, and then nothing calls into Java for it. --- docs/guide/get-started.md | 16 ++ .../jni-voithos/include/JavaUtils.h | 14 ++ .../jni-voithos/src/JavaUtils.cpp | 17 ++ .../src/main/cpp/include/JNI_LeakDetector.h | 21 ++ .../src/main/cpp/include/LeakDetection.h | 35 +++ .../src/main/cpp/src/JNI_LeakDetector.cpp | 121 +++++++++++ webrtc-jni/src/main/cpp/src/NativeHandle.cpp | 15 +- .../cpp/src/media/MediaStreamTrackView.cpp | 4 + .../onvoid/webrtc/internal/LeakDetector.java | 202 ++++++++++++++++++ .../onvoid/webrtc/internal/NativeObject.java | 38 ++++ .../webrtc/internal/LeakDetectionUse.java | 155 ++++++++++++++ .../webrtc/internal/LeakDetectorTests.java | 156 ++++++++++++++ 12 files changed, 789 insertions(+), 5 deletions(-) create mode 100644 webrtc-jni/src/main/cpp/include/JNI_LeakDetector.h create mode 100644 webrtc-jni/src/main/cpp/include/LeakDetection.h create mode 100644 webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/internal/LeakDetector.java create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectionUse.java create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectorTests.java diff --git a/docs/guide/get-started.md b/docs/guide/get-started.md index 39a7be43f..4e5e868d9 100644 --- a/docs/guide/get-started.md +++ b/docs/guide/get-started.md @@ -481,6 +481,22 @@ factory.dispose(); `dispose()` and `close()` may be called from any thread and more than once: only the first call frees anything, later ones do nothing. Once an object is disposed, its methods throw an `IllegalStateException` (a closed connection still reports its state). A method that another thread is running at that moment keeps the native object until it returns, and what the dispose frees is freed then. +#### Finding Objects That Were Never Disposed + +An object that becomes unreachable without being disposed or closed leaks its native object. To find such objects, start the JVM with `-Dwebrtc.java.leak.detection=true`: each one is then reported, with its class, once the garbage collector finds it unreachable. Add `-Dwebrtc.java.leak.trace=true` to have the report tell where the object was created, at the cost of a stack trace per object. + +```shell +java -Dwebrtc.java.leak.detection=true -Dwebrtc.java.leak.trace=true -jar app.jar +``` + +The reports are warnings through `Logging`, which writes nothing unless the application asks for it: + +```java +Logging.logToDebug(Logging.Severity.WARNING); +``` + +Only objects that own a native object and have a `dispose()` or `close()` method are watched: not views such as the track of `RTCRtpSender.getTrack()`, which own nothing, and not reference-counted objects such as video frame buffers. The detector only reports; it never frees anything itself, since a native object may still be in use on a WebRTC thread. While it is off, which is the default, nothing is watched. + ## Next Steps Now that you have a basic understanding of webrtc-java, you can explore more advanced features: diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaUtils.h b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaUtils.h index 72855fb4a..d320c5442 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaUtils.h +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaUtils.h @@ -119,6 +119,14 @@ T * GetHandle(JNIEnv * env, jobject obj) return GetHandle(env, obj, "nativeHandle"); } +// Told about every Java object whose "nativeHandle" field SetHandle() sets: +// bound is whether it is set to a native object or to none. Null, and then +// not called, unless something listens. +using NativeHandleHook = void (*)(JNIEnv * env, jobject obj, bool bound); + +void SetNativeHandleHook(NativeHandleHook hook); +NativeHandleHook GetNativeHandleHook(); + template void SetHandle(JNIEnv * env, jobject obj, const std::string & handleName, T * t, const char * declaringClass = nullptr) @@ -133,6 +141,12 @@ void SetHandle(JNIEnv * env, jobject obj, const std::string & handleName, T * t, jlong handle = reinterpret_cast(t); env->SetLongField(obj, field, handle); + + if (NativeHandleHook hook = GetNativeHandleHook()) { + if (handleName == "nativeHandle") { + hook(env, obj, handle != 0); + } + } } template diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp index 7f089a2af..4c01f0e6e 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp @@ -16,6 +16,8 @@ #include "JavaThreadEnv.h" #include "JavaWrappedException.h" +#include + #include #include #include @@ -154,6 +156,21 @@ jmethodID GetStaticMethod(JNIEnv * env, jclass cls, const char * name, const cha return method; } +namespace +{ + std::atomic nativeHandleHook { nullptr }; +} + +void SetNativeHandleHook(NativeHandleHook hook) +{ + nativeHandleHook.store(hook, std::memory_order_release); +} + +NativeHandleHook GetNativeHandleHook() +{ + return nativeHandleHook.load(std::memory_order_acquire); +} + jfieldID GetHandleField(JNIEnv * env, jobject obj, const std::string & fieldName, const char * declaringClass) { diff --git a/webrtc-jni/src/main/cpp/include/JNI_LeakDetector.h b/webrtc-jni/src/main/cpp/include/JNI_LeakDetector.h new file mode 100644 index 000000000..0e5f5cb93 --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/JNI_LeakDetector.h @@ -0,0 +1,21 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class dev_onvoid_webrtc_internal_LeakDetector */ + +#ifndef _Included_dev_onvoid_webrtc_internal_LeakDetector +#define _Included_dev_onvoid_webrtc_internal_LeakDetector +#ifdef __cplusplus +extern "C" { +#endif + /* + * Class: dev_onvoid_webrtc_internal_LeakDetector + * Method: enableNative + * Signature: ()V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_LeakDetector_enableNative + (JNIEnv *, jclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/webrtc-jni/src/main/cpp/include/LeakDetection.h b/webrtc-jni/src/main/cpp/include/LeakDetection.h new file mode 100644 index 000000000..4f69ae941 --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/LeakDetection.h @@ -0,0 +1,35 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JNI_WEBRTC_LEAK_DETECTION_H_ +#define JNI_WEBRTC_LEAK_DETECTION_H_ + +#include + +namespace jni +{ + // The native side of dev.onvoid.webrtc.internal.LeakDetector. While it is + // off, which is the default, none of this calls into Java. + namespace LeakDetection + { + // Tells the leak detector that the NativeObject no longer owns a native + // object: it has been disposed or closed, or it never owned one, such + // as a view of a track owned elsewhere. Keeps a pending exception. + void Released(JNIEnv * env, jobject object) noexcept; + } +} + +#endif diff --git a/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp b/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp new file mode 100644 index 000000000..7c6254ecb --- /dev/null +++ b/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp @@ -0,0 +1,121 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JNI_LeakDetector.h" +#include "JNI_WebRTC.h" +#include "LeakDetection.h" +#include "JavaUtils.h" + +#include + +namespace +{ + // Set before enabled, which publishes them. + jclass nativeObjectClass = nullptr; + jmethodID boundMethod = nullptr; + jmethodID releasedMethod = nullptr; + + std::atomic enabled { false }; + + void Notify(JNIEnv * env, jobject object, jmethodID method) noexcept + { + if (object == nullptr) { + return; + } + + // The caller's exception, if any, stays: it is not this one's to report. + jthrowable pending = env->ExceptionOccurred(); + + if (pending != nullptr) { + env->ExceptionClear(); + } + + // Some objects with a field of the same name are no NativeObject. + if (env->IsInstanceOf(object, nativeObjectClass)) { + env->CallVoidMethod(object, method); + + // Detection must not break what it watches. + if (env->ExceptionCheck()) { + env->ExceptionClear(); + } + } + + if (pending != nullptr) { + env->Throw(pending); + env->DeleteLocalRef(pending); + } + } + + void OnNativeHandleSet(JNIEnv * env, jobject object, bool bound) + { + Notify(env, object, bound ? boundMethod : releasedMethod); + } +} + +namespace jni +{ + namespace LeakDetection + { + void Released(JNIEnv * env, jobject object) noexcept + { + if (enabled.load(std::memory_order_acquire)) { + Notify(env, object, releasedMethod); + } + } + } +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_LeakDetector_enableNative +(JNIEnv * env, jclass) +{ + if (enabled.load()) { + return; + } + + jclass cls = env->FindClass(PKG_INTERNAL "NativeObject"); + + if (cls == nullptr) { + return; + } + + jmethodID bound = env->GetMethodID(cls, "nativeHandleBound", "()V"); + + if (bound == nullptr) { + env->DeleteLocalRef(cls); + return; + } + + jmethodID released = env->GetMethodID(cls, "nativeHandleReleased", "()V"); + + if (released == nullptr) { + env->DeleteLocalRef(cls); + return; + } + + nativeObjectClass = static_cast(env->NewGlobalRef(cls)); + env->DeleteLocalRef(cls); + + if (nativeObjectClass == nullptr) { + return; + } + + boundMethod = bound; + releasedMethod = released; + + enabled.store(true, std::memory_order_release); + + SetNativeHandleHook(&OnNativeHandleSet); +} diff --git a/webrtc-jni/src/main/cpp/src/NativeHandle.cpp b/webrtc-jni/src/main/cpp/src/NativeHandle.cpp index b06ee9663..0df803467 100644 --- a/webrtc-jni/src/main/cpp/src/NativeHandle.cpp +++ b/webrtc-jni/src/main/cpp/src/NativeHandle.cpp @@ -19,6 +19,7 @@ #include "JavaRef.h" #include "JavaUtils.h" #include "JNI_WebRTC.h" +#include "LeakDetection.h" #include "rtc_base/logging.h" @@ -216,14 +217,18 @@ namespace jni return 0; } - Stripe & stripe = StripeOf(handle); - std::lock_guard lock(stripe.mutex); + { + Stripe & stripe = StripeOf(handle); + std::lock_guard lock(stripe.mutex); - if (env->GetLongField(object, field) != handle) { - return 0; + if (env->GetLongField(object, field) != handle) { + return 0; + } + + env->SetLongField(object, field, 0); } - env->SetLongField(object, field, 0); + LeakDetection::Released(env, object); return handle; } diff --git a/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackView.cpp b/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackView.cpp index 263522afe..8e0d16417 100644 --- a/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackView.cpp +++ b/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackView.cpp @@ -18,6 +18,7 @@ #include "JavaClasses.h" #include "JavaUtils.h" #include "JNI_WebRTC.h" +#include "LeakDetection.h" #include @@ -41,6 +42,9 @@ namespace jni env->SetBooleanField(javaTrack, javaClass->view, JNI_TRUE); + // Owns nothing, so there is nothing to forget to dispose. + LeakDetection::Released(env, javaTrack); + return std::move(javaTrack); } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/internal/LeakDetector.java b/webrtc/src/main/java/dev/onvoid/webrtc/internal/LeakDetector.java new file mode 100644 index 000000000..9144b2c5e --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/internal/LeakDetector.java @@ -0,0 +1,202 @@ +/* + * Copyright 2019 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.internal; + +import dev.onvoid.webrtc.logging.Logging; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.ref.Cleaner; +import java.util.function.Consumer; + +/** + * Reports native objects whose Java object became unreachable without having + * been disposed or closed, which leaks the native object and whatever it + * holds. Off by default; turned on with the system property {@value + * #PROPERTY} set to {@code true} before the library is loaded. With {@value + * #TRACE_PROPERTY} set to {@code true} as well, a report also tells where the + * object was created. + *

+ * Reports are warnings through {@link Logging}, which writes nothing unless + * the application asks for it, e.g. with {@code + * Logging.logToDebug(Logging.Severity.WARNING)} or a log sink. A report is + * all that happens: freeing the native object on a garbage collector's + * thread could free it under a WebRTC thread that still uses it. + *

+ * Only objects that own a native object and are to be released with a + * {@code dispose()} or {@code close()} method are watched, not views of an + * object owned elsewhere nor reference counted ones. While off, nothing is + * watched and nothing calls into Java for it. + */ +final class LeakDetector { + + /** The system property that turns the detector on. */ + static final String PROPERTY = "webrtc.java.leak.detection"; + + /** The system property that adds where an object was created to its report. */ + static final String TRACE_PROPERTY = "webrtc.java.leak.trace"; + + static final boolean ENABLED = Boolean.getBoolean(PROPERTY); + + private static final boolean TRACE = Boolean.getBoolean(TRACE_PROPERTY); + + /** Whether instances of a class are to be disposed or closed. */ + private static final ClassValue MUST_RELEASE = new ClassValue<>() { + + @Override + protected Boolean computeValue(Class type) { + if (RefCounted.class.isAssignableFrom(type)) { + return false; + } + + return hasMethod(type, "dispose") || hasMethod(type, "close"); + } + }; + + /** Where reports go; tests take them. */ + static volatile Consumer reporter = Logging::warn; + + private static volatile Cleaner cleaner; + + + private LeakDetector() { + + } + + /** + * Turns the native side on when the detector is enabled. Called once the + * library is loaded. + */ + static void initialize() { + if (ENABLED) { + enableNative(); + } + } + + /** + * Starts watching the object, which a native object has just been bound to. + * + * @return the record to mark released, or null if the object needs none. + */ + static Record track(NativeObject object) { + Class type = object.getClass(); + + if (!MUST_RELEASE.get(type)) { + return null; + } + + Record record = new Record(type.getName(), TRACE ? new Throwable("Created here") : null); + + cleaner().register(object, record); + + return record; + } + + private static Cleaner cleaner() { + Cleaner current = cleaner; + + if (current == null) { + synchronized (LeakDetector.class) { + current = cleaner; + + if (current == null) { + current = Cleaner.create(task -> { + Thread thread = new Thread(task, "webrtc-leak-detector"); + thread.setDaemon(true); + return thread; + }); + + cleaner = current; + } + } + } + + return current; + } + + private static boolean hasMethod(Class type, String name) { + try { + type.getMethod(name); + return true; + } + catch (NoSuchMethodException e) { + return false; + } + } + + private static native void enableNative(); + + + + /** + * What is known of a watched object once it is gone. Holds nothing of the + * object itself, which would keep it reachable. + */ + static final class Record implements Runnable { + + final String type; + + final Throwable origin; + + volatile boolean released; + + /** Whether the object is gone and this has been checked. */ + volatile boolean checked; + + + Record(String type, Throwable origin) { + this.type = type; + this.origin = origin; + } + + /** Runs on the cleaner's thread once the object is unreachable. */ + @Override + public void run() { + try { + report(); + } + finally { + checked = true; + } + } + + private void report() { + if (released) { + return; + } + + StringBuilder message = new StringBuilder() + .append(type) + .append(" was not disposed before it became unreachable; its native object leaks"); + + if (origin != null) { + StringWriter stack = new StringWriter(); + origin.printStackTrace(new PrintWriter(stack)); + + message.append(System.lineSeparator()).append(stack); + } + + try { + reporter.accept(message.toString()); + } + catch (RuntimeException | LinkageError e) { + // A report must not end the cleaner's thread. + } + } + } + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java b/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java index 4ecdcd138..918ef8913 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java @@ -41,6 +41,8 @@ public abstract class NativeObject { catch (Exception e) { throw new RuntimeException("Load library 'webrtc-java' failed", e); } + + LeakDetector.initialize(); } /** @@ -51,6 +53,12 @@ public abstract class NativeObject { @SuppressWarnings("unused") private long nativeHandle; + /** + * What the {@link LeakDetector} knows of this object, null unless it is + * on and watches this object. + */ + volatile LeakDetector.Record leakRecord; + /** The hash code of {@link #nativeHashCode()}, or 0 until it is asked for. */ private volatile int nativeHash; @@ -119,4 +127,34 @@ protected final int nativeHashCode() { return hash; } + /** + * Called by native code once a native object is bound to this one, only + * while the {@link LeakDetector} is on. + */ + @SuppressWarnings("unused") + private void nativeHandleBound() { + LeakDetector.Record record = leakRecord; + + if (record == null) { + leakRecord = LeakDetector.track(this); + } + else { + // Bound again after it was released. + record.released = false; + } + } + + /** + * Called by native code once this object no longer owns a native object, + * or never did, only while the {@link LeakDetector} is on. + */ + @SuppressWarnings("unused") + private void nativeHandleReleased() { + LeakDetector.Record record = leakRecord; + + if (record != null) { + record.released = true; + } + } + } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectionUse.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectionUse.java new file mode 100644 index 000000000..50fd50cd5 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectionUse.java @@ -0,0 +1,155 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.internal; + +import dev.onvoid.webrtc.PeerConnectionFactory; +import dev.onvoid.webrtc.RTCConfiguration; +import dev.onvoid.webrtc.RTCPeerConnection; +import dev.onvoid.webrtc.RTCRtpSender; +import dev.onvoid.webrtc.media.MediaStreamTrack; +import dev.onvoid.webrtc.media.audio.AudioConverter; +import dev.onvoid.webrtc.media.audio.AudioDeviceModule; +import dev.onvoid.webrtc.media.audio.AudioLayer; +import dev.onvoid.webrtc.media.audio.AudioOptions; +import dev.onvoid.webrtc.media.audio.AudioResampler; +import dev.onvoid.webrtc.media.audio.AudioTrack; +import dev.onvoid.webrtc.media.audio.AudioTrackSource; +import dev.onvoid.webrtc.media.video.NativeI420Buffer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; + +/** + * Runs in a JVM of its own, with the leak detector on: forgets some objects, + * releases others, waits until the garbage collector has found all of them + * unreachable, and prints the reports. Exits with 0 if exactly the forgotten + * objects were reported. + */ +public final class LeakDetectionUse { + + public static void main(String[] args) { + List reports = Collections.synchronizedList(new ArrayList<>()); + LeakDetector.reporter = reports::add; + + List records = new ArrayList<>(); + List failures = new ArrayList<>(); + + // Forgotten, created in Java. + records.add(forgetResampler()); + + // Released. + AudioConverter converter = new AudioConverter(48000, 1, 16000, 1); + records.add(record(converter)); + converter.dispose(); + converter = null; + + // Reference counted, not watched. + NativeI420Buffer buffer = NativeI420Buffer.allocate(2, 2); + + if (record(buffer) != null) { + failures.add("reference counted buffer watched"); + } + + buffer.release(); + + // Created natively and released, and a view, which needs no dispose. + AudioDeviceModule audioModule = new AudioDeviceModule(AudioLayer.kDummyAudio); + PeerConnectionFactory factory = new PeerConnectionFactory(audioModule); + AudioTrackSource source = factory.createAudioSource(new AudioOptions()); + AudioTrack track = factory.createAudioTrack("audio", source); + RTCPeerConnection peerConnection = factory.createPeerConnection(new RTCConfiguration(), candidate -> { }); + RTCRtpSender sender = peerConnection.addTrack(track, List.of("stream")); + records.add(record(source)); + records.add(record(sender)); + records.add(forgetView(sender)); + + sender.dispose(); + peerConnection.close(); + track.dispose(); + source.dispose(); + factory.dispose(); + audioModule.dispose(); + source = null; + sender = null; + track = null; + peerConnection = null; + + for (LeakDetector.Record record : records) { + if (record == null) { + failures.add("an object to watch is not watched"); + } + } + + if (failures.isEmpty()) { + awaitChecked(records); + } + + reports.forEach(System.out::println); + + if (!failures.isEmpty()) { + failures.forEach(System.out::println); + System.exit(1); + } + if (reports.size() != 1 || !reports.get(0).startsWith(AudioResampler.class.getName() + " was not disposed")) { + System.out.println("Expected one report, of the AudioResampler, got " + reports.size()); + System.exit(1); + } + } + + /** + * The record of the object. A field of NativeObject, which subclasses in + * other packages do not inherit. + */ + static LeakDetector.Record record(NativeObject object) { + return object.leakRecord; + } + + private static LeakDetector.Record forgetResampler() { + return record(new AudioResampler(48000, 16000, 1)); + } + + private static LeakDetector.Record forgetView(RTCRtpSender sender) { + MediaStreamTrack view = sender.getTrack(); + LeakDetector.Record record = record(view); + + if (record != null && !record.released) { + throw new IllegalStateException("view taken for an owner"); + } + + return record; + } + + private static void awaitChecked(List records) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + + while (!records.stream().allMatch(record -> record.checked)) { + if (System.nanoTime() > deadline) { + System.out.println("Not all objects were collected"); + System.exit(1); + } + + System.gc(); + + // Gives the cleaner's thread time to run what the collection found. + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectorTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectorTests.java new file mode 100644 index 000000000..bdec801ca --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/LeakDetectorTests.java @@ -0,0 +1,156 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.onvoid.webrtc.media.audio.AudioResampler; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import org.junit.jupiter.api.Test; + +class LeakDetectorTests { + + private static final long TIMEOUT_SECONDS = 60; + + + @Test + void offWatchesNothing() { + // This JVM runs without the property. + AudioResampler resampler = new AudioResampler(48000, 16000, 1); + + assertNull(LeakDetectionUse.record(resampler)); + + resampler.dispose(); + } + + @Test + void unreleasedIsReported() { + LeakDetector.Record record = new LeakDetector.Record("Example", null); + + List reports = runChecked(record); + + assertEquals(List.of("Example was not disposed before it became unreachable; its native object leaks"), + reports); + assertTrue(record.checked); + } + + @Test + void releasedIsNotReported() { + LeakDetector.Record record = new LeakDetector.Record("Example", null); + record.released = true; + + assertEquals(List.of(), runChecked(record)); + assertTrue(record.checked); + } + + @Test + void reportNamesOrigin() { + LeakDetector.Record record = new LeakDetector.Record("Example", new Throwable("Created here")); + + List reports = runChecked(record); + + assertEquals(1, reports.size()); + assertTrue(reports.get(0).contains("Created here"), reports.get(0)); + assertTrue(reports.get(0).contains(LeakDetectorTests.class.getName()), reports.get(0)); + } + + @Test + void forgottenObjectsReported() throws Exception { + Result result = run("-D" + LeakDetector.PROPERTY + "=true"); + + assertEquals(0, result.exitValue, result.output); + } + + @Test + void traceNamesWhereCreated() throws Exception { + Result result = run("-D" + LeakDetector.PROPERTY + "=true", "-D" + LeakDetector.TRACE_PROPERTY + "=true"); + + assertEquals(0, result.exitValue, result.output); + assertTrue(result.output.contains("Created here"), result.output); + assertTrue(result.output.contains("LeakDetectionUse.forgetResampler"), result.output); + } + + /** Runs the cleaner's work of the record here, with its reports taken. */ + private static List runChecked(LeakDetector.Record record) { + List reports = new ArrayList<>(); + Consumer reporter = LeakDetector.reporter; + + LeakDetector.reporter = reports::add; + + try { + record.run(); + } + finally { + LeakDetector.reporter = reporter; + } + + return reports; + } + + private static Result run(String... properties) throws Exception { + List command = new ArrayList<>(); + command.add(Paths.get(System.getProperty("java.home"), "bin", "java").toString()); + command.addAll(Arrays.asList(properties)); + command.add("-cp"); + command.add(StandaloneLoadingTests.classPath()); + command.add(LeakDetectionUse.class.getName()); + + Process process = new ProcessBuilder(command) + .redirectErrorStream(true) + .start(); + + // Read while it runs, so that a full pipe cannot stall it. + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Thread reader = new Thread(() -> StandaloneLoadingTests.copy(process.getInputStream(), output)); + reader.start(); + + assertTrue(process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS), () -> { + process.destroyForcibly(); + return "did not finish within " + TIMEOUT_SECONDS + " s"; + }); + reader.join(); + + return new Result(process.exitValue(), output.toString(StandardCharsets.UTF_8)); + } + + + + private static class Result { + + final int exitValue; + + final String output; + + + Result(int exitValue, String output) { + this.exitValue = exitValue; + this.output = output; + } + } + +}