Merge pull request #1354 from OffbandMesh/fix/794-disconnect-race-dev

fix(#794): serialize disconnectAllDevices against the GATT callbacks
pull/1359/head
Strycher 6 days ago committed by GitHub
commit cad4af3b41
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -230,7 +230,7 @@ public class FlutterBluePlusPlugin implements
}
}
disconnectAllDevices("onDetachedFromEngine");
disconnectAllDevices("onDetachedFromEngine", false);
context.unregisterReceiver(mBluetoothBondStateReceiver);
context.unregisterReceiver(mBluetoothPairRequestReceiver);
@ -338,7 +338,8 @@ public class FlutterBluePlusPlugin implements
// all dart state is reset after flutter restart
// (i.e. Hot Restart) so also reset native state
disconnectAllDevices("flutterRestart");
// #794: onMethodCall already holds mMethodCallMutex.
disconnectAllDevices("flutterRestart", true);
log(LogLevel.DEBUG, "connectedPeripherals: " + mConnectedDevices.size());
@ -1825,43 +1826,80 @@ public class FlutterBluePlusPlugin implements
}
}
private void disconnectAllDevices(String func)
// #794: this method mutates the connection maps, which must be serialized
// against the GATT callbacks that take mMethodCallMutex. A caller that
// already holds the (non-reentrant) mutex passes callerHoldsMutex=true:
// flutterRestart runs inside onMethodCall, which holds it, and acquiring
// again there would deadlock Hot Restart.
//
// The critical section is kept short (pre-PR review, #794): under the lock
// we only snapshot the handles and clear the maps. The blocking
// gatt.disconnect()/close() IPC runs OUTSIDE the lock, so a teardown on the
// main thread (onDetachedFromEngine) can't stall behind a binder-thread
// callback holding the mutex while the Bluetooth stack works.
private void disconnectAllDevices(String func, boolean callerHoldsMutex)
{
log(LogLevel.DEBUG, "disconnectAllDevices("+func+")");
// merge connected & autoconnected
Map<String, BluetoothGatt> allDevices = new HashMap<>();
allDevices.putAll(mConnectedDevices);
allDevices.putAll(mAutoConnected);
// request disconnections
for (BluetoothGatt gatt : allDevices.values()) {
if (func == "adapterTurnOff") {
// Note:
// - calling `disconnect` and `close` after the adapter
// is turned off is not necessary. It is implied.
// Calling them leads to a `DeadObjectException`.
// - But, we must make sure the disconnect callback is called.
// It's surprising but android does not invoke this callback itself.
mGattCallback.onConnectionStateChange(gatt, 0, BluetoothProfile.STATE_DISCONNECTED);
} else {
String remoteId = gatt.getDevice().getAddress();
// disconnect
log(LogLevel.DEBUG, "calling disconnect: " + remoteId);
gatt.disconnect();
if (func == "adapterTurnOff") {
// Adapter is off: no real IPC is possible (disconnect/close would
// throw DeadObjectException), but Android does NOT deliver the
// disconnect callbacks itself, so we synthesize them. That work
// mutates the maps and emits events, so it stays under the lock;
// it does no blocking IPC, so the section is bounded. Snapshot
// first because the locked core mutates the maps it iterates.
if (!callerHoldsMutex) {
acquireMutex(mMethodCallMutex);
}
try {
Map<String, BluetoothGatt> allDevices = new HashMap<>();
allDevices.putAll(mConnectedDevices);
allDevices.putAll(mAutoConnected);
for (BluetoothGatt gatt : allDevices.values()) {
handleConnectionStateChangeLocked(gatt, 0, BluetoothProfile.STATE_DISCONNECTED);
}
clearAllConnectionMaps();
} finally {
if (!callerHoldsMutex) {
mMethodCallMutex.release();
}
}
return;
}
// it is important to close after disconnection, otherwise we will
// quickly run out of bluetooth resources, preventing new connections
log(LogLevel.DEBUG, "calling close: " + remoteId);
gatt.close();
// Other paths (onDetachedFromEngine, flutterRestart): snapshot the
// handles and clear the maps under the lock, then disconnect/close
// them outside it.
List<BluetoothGatt> toClose = new ArrayList<>();
if (!callerHoldsMutex) {
acquireMutex(mMethodCallMutex);
}
try {
toClose.addAll(mConnectedDevices.values());
toClose.addAll(mAutoConnected.values());
clearAllConnectionMaps();
} finally {
if (!callerHoldsMutex) {
mMethodCallMutex.release();
}
}
// Blocking IPC, outside the critical section. Per-device try/catch so
// one DeadObjectException doesn't strand the remaining handles.
for (BluetoothGatt gatt : toClose) {
String remoteId = gatt.getDevice().getAddress();
log(LogLevel.DEBUG, "calling disconnect: " + remoteId);
try { gatt.disconnect(); } catch (Exception e) { /* best effort */ }
// it is important to close after disconnection, otherwise we will
// quickly run out of bluetooth resources, preventing new connections
log(LogLevel.DEBUG, "calling close: " + remoteId);
try { gatt.close(); } catch (Exception e) { /* best effort */ }
}
}
// #794: caller MUST hold mMethodCallMutex.
private void clearAllConnectionMaps()
{
mConnectedDevices.clear();
mCurrentlyConnectingDevices.clear();
mBondingDevices.clear();
@ -2017,7 +2055,7 @@ public class FlutterBluePlusPlugin implements
// disconnect all devices
if (adapterState == BluetoothAdapter.STATE_TURNING_OFF ||
adapterState == BluetoothAdapter.STATE_OFF) {
disconnectAllDevices("adapterTurnOff");
disconnectAllDevices("adapterTurnOff", false);
}
}
};
@ -2224,16 +2262,13 @@ public class FlutterBluePlusPlugin implements
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
// ██████ ██ ██ ███████ ███████ ██████ ██ ██ ██████ ██ ██
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback()
// #794: the locked core of onConnectionStateChange. Callers MUST hold
// mMethodCallMutex: the public callback acquires it, and
// disconnectAllDevices, which already holds it, calls this directly
// (going through the public callback from there would deadlock on the
// non-reentrant Semaphore).
private void handleConnectionStateChangeLocked(BluetoothGatt gatt, int status, int newState)
{
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
try {
// Prevent callback thread & method call thread from writing to
// mConnectedDevices & mCurrentlyConnectingDevices concurrently.
acquireMutex(mMethodCallMutex);
log(LogLevel.DEBUG, "onConnectionStateChange:" + connectionStateString(newState));
log(LogLevel.DEBUG, " status: " + hciStatusString(status));
@ -2307,16 +2342,15 @@ public class FlutterBluePlusPlugin implements
response.put("disconnect_reason_string", hciStatusString(status));
invokeMethodUIThread("OnConnectionStateChanged", response);
} finally {
mMethodCallMutex.release();
}
}
}
// Android has an annoying edge case. If disconnect is called right as the connection is being
// established, Android sometimes ignores the request to disconnect and completes the connection
// anyway. To handle this case, we make sure the device is still in our currently connecting
// devices map, otherwise kill the connection since the user was not expecting it to connect.
private boolean handleUnexpectedConnectionEvents(BluetoothGatt gatt, int newState, String remoteId)
// Android has an annoying edge case. If disconnect is called right as the connection is being
// established, Android sometimes ignores the request to disconnect and completes the connection
// anyway. To handle this case, we make sure the device is still in our currently connecting
// devices map, otherwise kill the connection since the user was not expecting it to connect.
// (Hoisted out of the anonymous callback so handleConnectionStateChangeLocked can live at
// class level, #794.)
private boolean handleUnexpectedConnectionEvents(BluetoothGatt gatt, int newState, String remoteId)
{
boolean unexpectedEvent = false;
if (newState == BluetoothProfile.STATE_CONNECTED) {
@ -2364,6 +2398,21 @@ public class FlutterBluePlusPlugin implements
return unexpectedEvent;
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback()
{
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
try {
// Prevent callback thread & method call thread from writing to
// mConnectedDevices & mCurrentlyConnectingDevices concurrently.
acquireMutex(mMethodCallMutex);
handleConnectionStateChangeLocked(gatt, status, newState);
} finally {
mMethodCallMutex.release();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{

@ -1,6 +1,6 @@
name: flutter_blue_plus_android
description: Android implementation of the flutter_blue_plus plugin.
version: 8.2.2+offband.1
version: 8.2.2+offband.2
homepage: https://github.com/chipweinberger/flutter_blue_plus
environment:

Loading…
Cancel
Save

Powered by TurnKey Linux.