Skip to content

Commit 8b53877

Browse files
committed
Fix memory leak on failed client activation
1 parent 06c7362 commit 8b53877

3 files changed

Lines changed: 115 additions & 20 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
- Failed client activation now closes the client and frees both callback handlers instead of
6+
leaking them ([#232](https://github.com/RustAudio/rust-jack/issues/232)).
57
- `Error` is now `#[non_exhaustive]`. `match`es on it outside of this crate need a wildcard arm.
68
- Added `Error::PortUnregistrationError`.
79
- `Client::unregister_port` now returns `Err(Error::PortUnregistrationError)` on failure instead

‎src/client/async_client.rs‎

Lines changed: 111 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use jack_sys as j;
22
use std::fmt;
33
use std::fmt::Debug;
4-
use std::mem;
54
use std::sync::atomic::AtomicBool;
65

76
use super::callbacks::clear_callbacks;
@@ -49,33 +48,47 @@ where
4948
/// methods specified by the `NotificationHandler` and `ProcessHandler` objects.
5049
///
5150
/// On failure, either `Err(Error::CallbackRegistrationError)` or
52-
/// `Err(Error::ClientActivationError)` is returned.
51+
/// `Err(Error::ClientActivationError)` is returned. The client is closed and both handlers
52+
/// are dropped.
5353
///
5454
/// `notification_handler` and `process_handler` are consumed, but they are returned when
5555
/// `Client::deactivate` is called.
5656
pub fn new(client: Client, notification_handler: N, process_handler: P) -> Result<Self, Error> {
57+
Self::new_with_activation(
58+
client,
59+
notification_handler,
60+
process_handler,
61+
|client| unsafe { j::jack_activate(client.raw()) },
62+
)
63+
}
64+
65+
// Inject activation so tests can exercise failures independently of the JACK implementation.
66+
fn new_with_activation(
67+
client: Client,
68+
notification_handler: N,
69+
process_handler: P,
70+
activate: impl FnOnce(&Client) -> libc::c_int,
71+
) -> Result<Self, Error> {
72+
let mut callback_context = Box::new(CallbackContext {
73+
client,
74+
notification: notification_handler,
75+
process: process_handler,
76+
is_valid_for_callback: AtomicBool::new(true),
77+
has_panic: AtomicBool::new(false),
78+
callback_lock: std::sync::Mutex::new(()),
79+
});
80+
// Declare the guard after the context so it is released before error cleanup:
81+
// Client::drop also acquires this mutex.
5782
let _m = CREATE_OR_DESTROY_CLIENT_MUTEX.lock().ok();
5883
unsafe {
59-
let mut callback_context = Box::new(CallbackContext {
60-
client,
61-
notification: notification_handler,
62-
process: process_handler,
63-
is_valid_for_callback: AtomicBool::new(true),
64-
has_panic: AtomicBool::new(false),
65-
callback_lock: std::sync::Mutex::new(()),
66-
});
6784
CallbackContext::register_callbacks(&mut callback_context)?;
68-
let res = j::jack_activate(callback_context.client.raw());
69-
match res {
70-
0 => Ok(AsyncClient {
71-
callback: Some(callback_context),
72-
}),
73-
_ => {
74-
mem::forget(callback_context);
75-
Err(Error::ClientActivationError)
76-
}
77-
}
7885
}
86+
if activate(&callback_context.client) != 0 {
87+
return Err(Error::ClientActivationError);
88+
}
89+
Ok(AsyncClient {
90+
callback: Some(callback_context),
91+
})
7992
}
8093
}
8194

@@ -151,3 +164,81 @@ impl<N, P> AsRef<Client> for AsyncClient<N, P> {
151164
self.as_client()
152165
}
153166
}
167+
168+
#[cfg(test)]
169+
mod tests {
170+
use super::*;
171+
use crate::{AudioIn, ClientOptions, Control, Port, ProcessScope, Unowned};
172+
use std::sync::{
173+
atomic::{AtomicUsize, Ordering},
174+
mpsc::{sync_channel, SyncSender},
175+
Arc,
176+
};
177+
178+
struct Handler {
179+
drops: Arc<AtomicUsize>,
180+
port: Port<Unowned>,
181+
processed: Option<SyncSender<()>>,
182+
}
183+
184+
impl NotificationHandler for Handler {}
185+
186+
impl ProcessHandler for Handler {
187+
fn process(&mut self, _: &Client, _: &ProcessScope) -> Control {
188+
assert_eq!(self.drops.load(Ordering::SeqCst), 0);
189+
if let Some(sender) = &self.processed {
190+
sender.try_send(()).ok();
191+
}
192+
Control::Continue
193+
}
194+
}
195+
196+
impl Drop for Handler {
197+
fn drop(&mut self) {
198+
// The client must be closed before either handler is destroyed.
199+
assert_eq!(self.port.name(), Err(Error::ClientIsNoLongerAlive));
200+
self.drops.fetch_add(1, Ordering::SeqCst);
201+
}
202+
}
203+
204+
fn check_activation_failure(start_processing: bool) {
205+
let (client, _) = Client::new("", ClientOptions::default()).unwrap();
206+
let port = client.register_port("input", AudioIn::default()).unwrap();
207+
let notification_drops = Arc::new(AtomicUsize::new(0));
208+
let process_drops = Arc::new(AtomicUsize::new(0));
209+
let (send, recv) = sync_channel(1);
210+
let notification = Handler {
211+
drops: notification_drops.clone(),
212+
port: port.clone_unowned(),
213+
processed: None,
214+
};
215+
let process = Handler {
216+
drops: process_drops.clone(),
217+
port: port.clone_unowned(),
218+
processed: Some(send),
219+
};
220+
let result = AsyncClient::new_with_activation(client, notification, process, |client| {
221+
if start_processing {
222+
// Model a failure after JACK has started using the registered callback pointers.
223+
assert_eq!(unsafe { j::jack_activate(client.raw()) }, 0);
224+
recv.recv_timeout(std::time::Duration::from_secs(2))
225+
.unwrap();
226+
}
227+
-1
228+
});
229+
assert_eq!(result.err(), Some(Error::ClientActivationError));
230+
assert_eq!(notification_drops.load(Ordering::SeqCst), 1);
231+
assert_eq!(process_drops.load(Ordering::SeqCst), 1);
232+
assert_eq!(port.name(), Err(Error::ClientIsNoLongerAlive));
233+
}
234+
235+
#[test]
236+
fn activation_failure_closes_client_and_drops_handlers() {
237+
check_activation_failure(false);
238+
}
239+
240+
#[test]
241+
fn activation_failure_after_start_closes_client_and_drops_handlers() {
242+
check_activation_failure(true);
243+
}
244+
}

‎src/client/callbacks.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,8 @@ pub unsafe fn clear_callbacks(client: *mut j::jack_client_t) -> Result<(), Error
518518
/// The information used by JACK to process data.
519519
pub struct CallbackContext<N, P> {
520520
/// The underlying JACK client.
521+
/// Keep this field first so the client is closed, stopping callbacks, before the handlers
522+
/// and the rest of the context are dropped.
521523
pub client: Client,
522524
/// The handler for notifications.
523525
pub notification: N,

0 commit comments

Comments
 (0)