Fix USB buffer leak on dispose and guard fl_free against orphaned close
dispose() no longer relies on FlSerial.closePort() to free the I/O buffers: it checks the buffers' first byte instead of their address, so it usually leaked both. Close via fl_close and always free by address. A native close still running in a helper isolate is invisible to a fresh isolate after hot restart, so connect() could fl_free() a slot mid-close. Track the in-flight close with a per-process temp marker and wait for it (bounded to 45s) before resetting the slot table.
This commit is contained in:
1 parent
8b8715cfda
commit
d74c280ea3
1 file changed
+60
-20
@@ -39,6 +39,14 @@ class UsbSerialService {
|
|||||||
/// Non-null while a disconnect teardown (native close in a helper isolate,
|
/// Non-null while a disconnect teardown (native close in a helper isolate,
|
||||||
/// then subscription cancel) is running.
|
/// then subscription cancel) is running.
|
||||||
Future<void>? _activeDisconnect;
|
Future<void>? _activeDisconnect;
|
||||||
|
|
||||||
|
/// Exists while a native close runs in a helper isolate. flserial's slot
|
||||||
|
/// table is process-global and survives a hot restart, but
|
||||||
|
/// [_activeDisconnect] does not, so a fresh isolate checks this marker
|
||||||
|
/// before fl_free() tears down a slot that is still inside close().
|
||||||
|
static final String _pendingClosePath =
|
||||||
|
'${Directory.systemTemp.path}/meshcore_open_usb_close_$pid';
|
||||||
|
static const Duration _maxPendingClose = Duration(seconds: 45);
|
||||||
AppDebugLogService? _debugLogService;
|
AppDebugLogService? _debugLogService;
|
||||||
Object? _lastError;
|
Object? _lastError;
|
||||||
|
|
||||||
@@ -192,6 +200,7 @@ class UsbSerialService {
|
|||||||
// This must happen before we register any new NativeCallable, so it must
|
// This must happen before we register any new NativeCallable, so it must
|
||||||
// be the very first thing we do in the desktop branch.
|
// be the very first thing we do in the desktop branch.
|
||||||
// (the previous teardown was already awaited above)
|
// (the previous teardown was already awaited above)
|
||||||
|
await _waitForOrphanedNativeClose();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
bindings.fl_free();
|
bindings.fl_free();
|
||||||
@@ -428,15 +437,23 @@ class UsbSerialService {
|
|||||||
Future<void> _closePortOffUiIsolate(FlSerial serial) async {
|
Future<void> _closePortOffUiIsolate(FlSerial serial) async {
|
||||||
final flh = serial.flh;
|
final flh = serial.flh;
|
||||||
if (flh < 0) {
|
if (flh < 0) {
|
||||||
// Already closed synchronously by dispose(); `closePort()` freed the
|
// Already closed synchronously by dispose(), which also closed the
|
||||||
// native slot, the stream and both I/O buffers. Touching them again
|
// stream and freed both I/O buffers.
|
||||||
// would double-free the calloc'd buffers.
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
serial.flh = -1;
|
serial.flh = -1;
|
||||||
final startedAt = DateTime.now();
|
final startedAt = DateTime.now();
|
||||||
|
final markerPath = _pendingClosePath;
|
||||||
try {
|
try {
|
||||||
await Isolate.run(() => bindings.fl_close(flh));
|
File(markerPath).writeAsStringSync('');
|
||||||
|
} catch (_) {}
|
||||||
|
try {
|
||||||
|
await Isolate.run(() {
|
||||||
|
bindings.fl_close(flh);
|
||||||
|
try {
|
||||||
|
File(markerPath).deleteSync();
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Spawning the helper failed, so the native slot and its SerialThread
|
// Spawning the helper failed, so the native slot and its SerialThread
|
||||||
// are still alive with no reachable handle. Close it inline instead —
|
// are still alive with no reachable handle. Close it inline instead —
|
||||||
@@ -451,6 +468,9 @@ class UsbSerialService {
|
|||||||
// Ignore errors while closing.
|
// Ignore errors while closing.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
File(markerPath).deleteSync();
|
||||||
|
} catch (_) {}
|
||||||
final elapsed = DateTime.now().difference(startedAt);
|
final elapsed = DateTime.now().difference(startedAt);
|
||||||
if (elapsed > const Duration(seconds: 1)) {
|
if (elapsed > const Duration(seconds: 1)) {
|
||||||
_debugLogService?.warn(
|
_debugLogService?.warn(
|
||||||
@@ -467,19 +487,37 @@ class UsbSerialService {
|
|||||||
_releaseSerialBuffers(serial);
|
_releaseSerialBuffers(serial);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the
|
/// Waits for a native close left running by a previous isolate (hot
|
||||||
/// pointer fields.
|
/// restart during a slow close). Bounded by the marker's age so a stale
|
||||||
///
|
/// marker — its helper isolate killed before deleting it — cannot block
|
||||||
/// [alreadyFreed] is set when `FlSerial.closePort()` ran: it frees both
|
/// forever.
|
||||||
/// buffers itself but leaves the pointer fields dangling, so they must only
|
Future<void> _waitForOrphanedNativeClose() async {
|
||||||
/// be cleared, never freed again.
|
final marker = File(_pendingClosePath);
|
||||||
void _releaseSerialBuffers(FlSerial serial, {bool alreadyFreed = false}) {
|
|
||||||
try {
|
try {
|
||||||
if (!alreadyFreed && serial.serialReadBuff.address != 0) {
|
if (!marker.existsSync()) return;
|
||||||
|
_debugLogService?.info(
|
||||||
|
'Waiting for a USB port close left over from a previous isolate',
|
||||||
|
tag: 'USB Serial',
|
||||||
|
);
|
||||||
|
final deadline = marker.lastModifiedSync().add(_maxPendingClose);
|
||||||
|
while (marker.existsSync() && DateTime.now().isBefore(deadline)) {
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 250));
|
||||||
|
}
|
||||||
|
if (marker.existsSync()) marker.deleteSync();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the
|
||||||
|
/// pointer fields. `FlSerial.closePort()` is never used for this: it tests
|
||||||
|
/// the buffers' first byte (`.value`) instead of their address, so it
|
||||||
|
/// usually leaks them.
|
||||||
|
void _releaseSerialBuffers(FlSerial serial) {
|
||||||
|
try {
|
||||||
|
if (serial.serialReadBuff.address != 0) {
|
||||||
calloc.free(serial.serialReadBuff);
|
calloc.free(serial.serialReadBuff);
|
||||||
}
|
}
|
||||||
serial.serialReadBuff = Pointer.fromAddress(0);
|
serial.serialReadBuff = Pointer.fromAddress(0);
|
||||||
if (!alreadyFreed && serial.serialWriteBuff.address != 0) {
|
if (serial.serialWriteBuff.address != 0) {
|
||||||
calloc.free(serial.serialWriteBuff);
|
calloc.free(serial.serialWriteBuff);
|
||||||
}
|
}
|
||||||
serial.serialWriteBuff = Pointer.fromAddress(0);
|
serial.serialWriteBuff = Pointer.fromAddress(0);
|
||||||
@@ -510,22 +548,24 @@ class UsbSerialService {
|
|||||||
// Close on any live handle, not only when isOpen() reports `open`:
|
// Close on any live handle, not only when isOpen() reports `open`:
|
||||||
// flserial keeps a valid slot (and a running SerialThread) when the
|
// flserial keeps a valid slot (and a running SerialThread) when the
|
||||||
// port is in an I/O error state, and _serial is already unreachable.
|
// port is in an I/O error state, and _serial is already unreachable.
|
||||||
var closed = false;
|
final flh = serial.flh;
|
||||||
if (serial.flh >= 0) {
|
if (flh >= 0) {
|
||||||
try {
|
try {
|
||||||
serial.setDTR(false);
|
serial.setDTR(false);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
// Line-control failure must not skip the close below.
|
// Line-control failure must not skip the close below.
|
||||||
}
|
}
|
||||||
|
serial.flh = -1;
|
||||||
try {
|
try {
|
||||||
serial.closePort(); // synchronous C call — kills the SerialThread
|
bindings.fl_close(
|
||||||
closed = true;
|
flh,
|
||||||
|
); // synchronous C call — kills the SerialThread
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
|
unawaited(serial.onSerialData.close());
|
||||||
}
|
}
|
||||||
// _serial is gone, so the disconnect() below can no longer reach the
|
// _serial is gone, so the disconnect() below can no longer reach the
|
||||||
// buffers: release them here, or just clear the dangling pointers if
|
// buffers: release them here.
|
||||||
// closePort() already freed them.
|
_releaseSerialBuffers(serial);
|
||||||
_releaseSerialBuffers(serial, alreadyFreed: closed);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Kick off the full async teardown for anything else (subscription cancel,
|
// Kick off the full async teardown for anything else (subscription cancel,
|
||||||
|
|||||||
Reference in new issue
Block a user