Skip to content

Commit 7bbf69b

Browse files
authored
fix: close races in MediaReader.getInfo and WebRtc.createPeer (#406)
MediaReader.getInfo now holds the same monitor as close, which may run on any thread; before, it could use a reader close had just freed (SIGSEGV). createPeer registers the peer before checking the runtime again, so a closing runtime either closes it before freeing the factory or is seen. open skips creating the connection once the peer is closed, and ends its wait when the runtime has stopped its threads and dropped the task.
1 parent 89df84d commit 7bbf69b

6 files changed

Lines changed: 133 additions & 8 deletions

File tree

‎webrtc-java-media/src/main/java/dev/onvoid/webrtc/media/player/MediaReader.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,9 @@ public MediaReader(String source, Duration timeout) throws IOException {
111111
*
112112
* @throws IllegalStateException if this reader has been closed.
113113
*/
114-
public MediaInfo getInfo() {
114+
public synchronized MediaInfo getInfo() {
115+
// Synchronized like close, which may run on any thread: otherwise the
116+
// handle read here could be freed while the native side still uses it.
115117
return info(handle);
116118
}
117119

‎webrtc-java-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
import java.net.URL;
2626
import java.nio.file.Path;
2727
import java.nio.file.Paths;
28+
import java.util.concurrent.CompletableFuture;
29+
import java.util.concurrent.CountDownLatch;
30+
import java.util.concurrent.TimeUnit;
2831

2932
import org.junit.jupiter.api.Test;
3033

@@ -130,6 +133,33 @@ void infoAfterCloseFails() throws Exception {
130133
assertThrows(IllegalStateException.class, reader::getInfo);
131134
}
132135

136+
@Test
137+
void infoRacingClose() throws Exception {
138+
// Close may run on any thread, so a getInfo on another one either gets
139+
// the info or finds the reader closed, never a reader being freed.
140+
for (int round = 0; round < 200; round++) {
141+
MediaReader reader = new MediaReader(asset());
142+
CountDownLatch started = new CountDownLatch(1);
143+
144+
CompletableFuture<Void> reading = CompletableFuture.runAsync(() -> {
145+
started.countDown();
146+
147+
try {
148+
while (true) {
149+
assertNotNull(reader.getInfo());
150+
}
151+
}
152+
catch (IllegalStateException e) {
153+
// Closed, which is how the loop ends.
154+
}
155+
});
156+
157+
started.await();
158+
reader.close();
159+
reading.get(10, TimeUnit.SECONDS);
160+
}
161+
}
162+
133163
private static Path asset() throws Exception {
134164
return asset(ASSET);
135165
}

‎webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,13 @@ void open() {
188188
CompletableFuture<Void> opened = new CompletableFuture<>();
189189

190190
control.execute(() -> {
191+
if (closed) {
192+
// The runtime closed the peer before this ran, and may already
193+
// be freeing the factory.
194+
opened.completeExceptionally(closedError());
195+
return;
196+
}
197+
191198
try {
192199
connection = rtc.factory.createPeerConnection(options.toConfiguration(), new Observer());
193200

@@ -219,6 +226,11 @@ void open() {
219226
}
220227
});
221228

229+
// A runtime that stops its threads drops the task if it has not run,
230+
// and then nothing else would end the wait.
231+
rtc.whenShutDown().thenRun(() -> opened.completeExceptionally(
232+
new PeerClosedException("The runtime closed before " + name + " was created")));
233+
222234
try {
223235
opened.get();
224236
}

‎webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ private void schedule() {
126126
executor.execute(this::drain);
127127
}
128128
catch (RejectedExecutionException e) {
129+
// The pool rejects only once the runtime has stopped it. A caller
130+
// that waits on a dropped task ends its wait with the runtime's
131+
// end, as PeerImpl.open does.
129132
synchronized (tasks) {
130133
scheduled = false;
131134
tasks.clear();

‎webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -230,24 +230,29 @@ public Peer createPeer(PeerOptions options) {
230230
String name = options.name != null ? options.name : "peer-" + number;
231231

232232
PeerImpl peer = new PeerImpl(this, options, name);
233+
234+
// Registered before the runtime is checked again: a runtime that
235+
// begins to close either finds the peer among those it closes and
236+
// waits for it before freeing the factory, or is seen closing here.
233237
peers.add(peer);
234238

239+
if (closing.get()) {
240+
peers.remove(peer);
241+
throw new PeerClosedException("The runtime is closed");
242+
}
243+
235244
try {
236245
peer.open();
237246
}
238247
catch (RuntimeException e) {
239248
// Closed before the error goes out, so that nothing of the failed
240249
// peer still runs when the runtime closes and frees WebRTC's threads.
241-
peers.remove(peer);
242-
peer.closeInternal().join();
250+
// Closing removes the peer. Once the runtime has stopped its threads
251+
// the close cannot run any more, and there is nothing left to wait for.
252+
CompletableFuture.anyOf(peer.closeInternal(), closed).join();
243253
throw e;
244254
}
245255

246-
if (closing.get()) {
247-
// The runtime began to close meanwhile and may have missed it.
248-
peer.closeInternal();
249-
}
250-
251256
return peer;
252257
}
253258

@@ -336,6 +341,14 @@ boolean isClosing() {
336341
return closing.get();
337342
}
338343

344+
/**
345+
* @return a future that completes once the runtime has closed and stopped
346+
* its threads, after which no task given to them runs.
347+
*/
348+
CompletableFuture<Void> whenShutDown() {
349+
return closed;
350+
}
351+
339352
private void shutdown() {
340353
try {
341354
// Peers and tracks created while the runtime closes are closed as

‎webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import static org.junit.jupiter.api.Assertions.assertFalse;
2121
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
2222
import static org.junit.jupiter.api.Assertions.assertThrows;
23+
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
2324
import static org.junit.jupiter.api.Assertions.assertTrue;
2425

2526
import java.time.Duration;
@@ -372,6 +373,70 @@ void runtimeCloseClosesPeers() throws Exception {
372373
assertThrows(PeerClosedException.class, this::pair);
373374
}
374375

376+
@Test
377+
void openAfterShutdownFails() {
378+
// A createPeer that passed its check just before the runtime closed:
379+
// the runtime's threads are gone and drop the task that would create
380+
// the connection, so opening has to fail rather than wait forever.
381+
PeerImpl peer = new PeerImpl(rtc, manualOptions(), "late");
382+
383+
rtc.close();
384+
385+
assertThrows(PeerClosedException.class, () -> assertTimeoutPreemptively(
386+
Duration.ofSeconds(TIMEOUT_SECONDS), peer::open));
387+
}
388+
389+
@Test
390+
void openAfterCloseFails() throws Exception {
391+
// The closing runtime found the peer before its connection was created.
392+
// It may free the factory once the peer is closed, so the connection
393+
// must not be created after that.
394+
PeerImpl peer = new PeerImpl(rtc, manualOptions(), "closed-first");
395+
396+
await(peer.closeInternal());
397+
398+
assertThrows(PeerClosedException.class, peer::open);
399+
}
400+
401+
@Test
402+
void createPeerRacingClose() throws Exception {
403+
// A peer created while its runtime closes is either refused or closed
404+
// with the runtime, and creating it never waits forever.
405+
for (int round = 0; round < 50; round++) {
406+
WebRtc runtime = WebRtc.builder()
407+
.audio(AudioMode.HEADLESS)
408+
.errorHandler(errors::add)
409+
.build();
410+
CountDownLatch started = new CountDownLatch(1);
411+
412+
CompletableFuture<List<Peer>> created = CompletableFuture.supplyAsync(() -> {
413+
List<Peer> peers = new ArrayList<>();
414+
415+
try {
416+
while (true) {
417+
peers.add(runtime.createPeer(manualOptions()));
418+
started.countDown();
419+
}
420+
}
421+
catch (PeerClosedException e) {
422+
return peers;
423+
}
424+
});
425+
426+
// Closed while peers are being created, not before the first.
427+
started.await();
428+
runtime.closeAsync().get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
429+
430+
for (Peer peer : created.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
431+
assertEquals(PeerState.CLOSED, peer.state());
432+
}
433+
}
434+
}
435+
436+
private static PeerOptions manualOptions() {
437+
return PeerOptions.builder().negotiation(Negotiation.MANUAL).build();
438+
}
439+
375440
@Test
376441
void statsAfterConnecting() throws Exception {
377442
Peer[] peers = pair();

0 commit comments

Comments
 (0)