fix(#794): serialize disconnectAllDevices against the GATT callbacks

The onDetachedFromEngine and adapter-off paths mutated the connection
maps and closed handles without mMethodCallMutex, racing
onConnectionStateChange (double-close, unsynchronized clear). Fix:
disconnectAllDevices takes callerHoldsMutex and self-acquires on those
two paths; flutterRestart, which runs inside onMethodCall and already
holds the non-reentrant Semaphore, passes true (the naive always-acquire
fix would deadlock Hot Restart). The connection-state handling is
hoisted to a class-level locked core, handleConnectionStateChangeLocked,
which the public callback wraps with the mutex and the adapterTurnOff
branch calls directly instead of re-entering through the callback.
Behavior under the lock is unchanged. Vendored version 8.2.2+offband.2.

Found by the #694 pre-PR review, tracked as #794; APK build green with
the restructured plugin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
pull/1354/head
diffwireauto 2 months ago
parent ce8da46764
commit 1572e9c92b

@ -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,51 +1826,67 @@ public class FlutterBluePlusPlugin implements
}
}
private void disconnectAllDevices(String func)
// #794: this method mutates the connection maps and must be serialized
// against the GATT callbacks, which 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.
private void disconnectAllDevices(String func, boolean callerHoldsMutex)
{
log(LogLevel.DEBUG, "disconnectAllDevices("+func+")");
if (!callerHoldsMutex) {
acquireMutex(mMethodCallMutex);
}
try {
log(LogLevel.DEBUG, "disconnectAllDevices("+func+")");
// merge connected & autoconnected
Map<String, BluetoothGatt> allDevices = new HashMap<>();
allDevices.putAll(mConnectedDevices);
allDevices.putAll(mAutoConnected);
// merge connected & autoconnected
Map<String, BluetoothGatt> allDevices = new HashMap<>();
allDevices.putAll(mConnectedDevices);
allDevices.putAll(mAutoConnected);
// request disconnections
for (BluetoothGatt gatt : allDevices.values()) {
// request disconnections
for (BluetoothGatt gatt : allDevices.values()) {
if (func == "adapterTurnOff") {
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);
// 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.
// #794: call the locked core directly; the public callback
// would try to re-acquire the mutex this method holds.
handleConnectionStateChangeLocked(gatt, 0, BluetoothProfile.STATE_DISCONNECTED);
} else {
} else {
String remoteId = gatt.getDevice().getAddress();
String remoteId = gatt.getDevice().getAddress();
// disconnect
log(LogLevel.DEBUG, "calling disconnect: " + remoteId);
gatt.disconnect();
// disconnect
log(LogLevel.DEBUG, "calling disconnect: " + remoteId);
gatt.disconnect();
// 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();
// 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();
}
}
}
mConnectedDevices.clear();
mCurrentlyConnectingDevices.clear();
mBondingDevices.clear();
mBondingPins.clear();
mMtu.clear();
mWriteChr.clear();
mWriteDesc.clear();
mAutoConnected.clear();
mConnectedDevices.clear();
mCurrentlyConnectingDevices.clear();
mBondingDevices.clear();
mBondingPins.clear();
mMtu.clear();
mWriteChr.clear();
mWriteDesc.clear();
mAutoConnected.clear();
} finally {
if (!callerHoldsMutex) {
mMethodCallMutex.release();
}
}
}
int getAppearanceFromScanRecord(ScanRecord adv) {
@ -2017,7 +2034,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 +2241,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 +2321,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 +2377,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.