fix(#910): four defects from the pre-PR review

1. The export shipped only the active log, and FileLogWriter._rotated was private, so offband.1.log and .2.log were unreachable by anything. An exit-record pointer line written at startup rotates out after a couple of MiB of ordinary logging, handing over a trace file with its metadata gone. FileLogWriter now exposes the files that exist, keeping the rotation naming where it belongs, and the mobile export attaches all of them.

2. dispose() called ioExecutor.shutdownNow() while a read could be holding a MethodChannel.Result. Interrupting it left the Result neither succeeded nor errored, so the Dart future never completed. Now shutdown(), with a disposed flag and a RejectedExecutionException path that always replies.

3. The trace read was skipped for REASON_CRASH_NATIVE on the assumption that its stream is always a protobuf. AOSP says a trace from an earlier ANR stays attached even when the process later died for another reason, so gating on the reason loses real text traces. The read is now attempted on every record and a printable-bytes check decides whether the content is usable.

4. The test-only main-thread block used a single Thread.sleep, which an interrupt could cut short: no ANR, no record, and a wasted trip to the hardware. It now sleeps to a deadline and ignores interrupts, which guarantees the duration without a busy-wait's CPU burn.

Review also flagged that FileLogWriter can exceed maxBytes for a single oversized entry. That is pre-existing writer semantics, already pinned by a test in this branch, and deliberately not changed here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
fix/754-discovery-per-radio
diffwireauto 1 month ago committed by Benjamin Wiechel
parent 35e71a9eef
commit d2e9358f4d

@ -14,6 +14,7 @@ import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
/**
* Reads the system's record of why this app's processes died, so an ANR that
@ -44,6 +45,8 @@ class AppExitInfoFunctions(
private val mainHandler = Handler(Looper.getMainLooper())
private val ioExecutor: ExecutorService = Executors.newSingleThreadExecutor()
@Volatile private var disposed = false
fun configureFlutterEngine(flutterEngine: FlutterEngine) {
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
.setMethodCallHandler { call, result ->
@ -56,10 +59,19 @@ class AppExitInfoFunctions(
}
fun dispose() {
ioExecutor.shutdownNow()
disposed = true
// shutdown(), NOT shutdownNow(): an in-flight read is holding a
// MethodChannel.Result, and interrupting it would leave that Result
// neither succeeded nor errored, so the Dart future would never
// complete. Letting the task finish is cheap; a hung future is not.
ioExecutor.shutdown()
}
private fun handleGetExitRecords(result: MethodChannel.Result) {
if (disposed) {
result.error("exit_info_disposed", "activity is being destroyed", null)
return
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
result.success(
mapOf(
@ -72,29 +84,35 @@ class AppExitInfoFunctions(
return
}
ioExecutor.execute {
try {
val records = collectExitRecords()
mainHandler.post {
result.success(
mapOf(
"supported" to true,
"sdkInt" to Build.VERSION.SDK_INT,
"records" to records,
),
)
}
} catch (error: Exception) {
// Surfaced, never swallowed: Dart logs this and leaves the
// watermark untouched so the next launch retries.
mainHandler.post {
result.error(
"exit_info_query_failed",
error.message ?: error.javaClass.simpleName,
error.stackTraceToString().take(2000),
)
try {
ioExecutor.execute {
try {
val records = collectExitRecords()
mainHandler.post {
result.success(
mapOf(
"supported" to true,
"sdkInt" to Build.VERSION.SDK_INT,
"records" to records,
),
)
}
} catch (error: Exception) {
// Surfaced, never swallowed: Dart logs this and leaves the
// watermark untouched so the next launch retries.
mainHandler.post {
result.error(
"exit_info_query_failed",
error.message ?: error.javaClass.simpleName,
error.stackTraceToString().take(2000),
)
}
}
}
} catch (error: RejectedExecutionException) {
// The executor shut down between the disposed check and here. Reply
// rather than returning silently, so the Dart future completes.
result.error("exit_info_rejected", error.message ?: "executor shut down", null)
}
}
@ -123,18 +141,29 @@ class AppExitInfoFunctions(
"status" to info.status,
)
if (info.reason == ApplicationExitInfo.REASON_CRASH_NATIVE) {
// From API 31 this stream is a protobuf tombstone, not text. Writing
// it into a text log would corrupt the log, so v1 records that it
// existed and leaves the bytes alone (#906).
record["traceUnavailable"] = "native_tombstone_not_text"
return record
}
readTrace(info, record)
return record
}
/**
* A text ANR trace is printable ASCII; a native tombstone protobuf is not.
*
* Content, not reason code, decides whether the bytes are usable. Gating on
* [ApplicationExitInfo.REASON_CRASH_NATIVE] instead would lose a real text
* trace, because AOSP says a trace from an earlier ANR stays attached to the
* record even when the process later died for a different reason.
*/
private fun looksLikeText(bytes: ByteArray): Boolean {
val sample = minOf(bytes.size, 256)
if (sample == 0) return false
var printable = 0
for (i in 0 until sample) {
val b = bytes[i].toInt() and 0xFF
if (b == 0x09 || b == 0x0A || b == 0x0D || (b in 0x20..0x7E)) printable++
}
return printable * 10 >= sample * 9
}
/**
* A trace is NOT guaranteed, even for [ApplicationExitInfo.REASON_ANR]: the
* system keeps traces in a circular buffer shared across all applications,
@ -167,8 +196,16 @@ class AppExitInfoFunctions(
record["traceUnavailable"] = "empty_stream"
return
}
record["traceBytes"] = sink.toByteArray()
if (sink.size() >= maxTraceBytes) {
val bytes = sink.toByteArray()
if (!looksLikeText(bytes)) {
// Almost certainly a native tombstone protobuf (API 31+).
// Recorded rather than written, because concatenating binary
// into a text log would corrupt it (#906).
record["traceUnavailable"] = "binary_tombstone_not_text"
return
}
record["traceBytes"] = bytes
if (bytes.size >= maxTraceBytes) {
record["traceTruncated"] = true
}
}
@ -210,10 +247,20 @@ class AppExitInfoFunctions(
val millis = (call.argument<Int>("millis") ?: 20000).coerceIn(1000, 120000)
result.success(millis)
mainHandler.post {
try {
Thread.sleep(millis.toLong())
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
// Sleeps to a deadline and swallows interrupts rather than a single
// Thread.sleep. An interrupt cutting the block short would mean no
// ANR, no record, and a wasted trip to the hardware. Looping on
// short sleeps keeps the duration guaranteed without the CPU burn
// (and thermal throttling) of a busy-wait.
val deadline = System.nanoTime() + millis * 1_000_000L
while (true) {
val remainingMs = (deadline - System.nanoTime()) / 1_000_000L
if (remainingMs <= 0) break
try {
Thread.sleep(minOf(remainingMs, 250L))
} catch (_: InterruptedException) {
// Deliberately ignored; the deadline is what ends this.
}
}
}
}

@ -73,6 +73,20 @@ class FileLogService {
return _writer?.activeFile;
}
/// Flush pending lines and return every log file on disk, newest first.
///
/// The export needs all of them, not just the active one: a line written once
/// at startup, such as an exit-record pointer, can rotate into `.1.log` after
/// a couple of MiB of ordinary logging, and the rotated files were previously
/// unreachable so that context was simply lost (#906). Empty when file logging
/// is unavailable.
Future<List<File>> flushAndGetAllFiles() async {
await _flush();
final w = _writer;
if (w == null) return const [];
return w.existingFiles();
}
/// Cancel the periodic flush and flush once more. The singleton normally lives
/// for the app's lifetime; this is for a clean shutdown / tests.
Future<void> dispose() async {

@ -24,6 +24,23 @@ class FileLogWriter {
File get activeFile => File('${dir.path}/$baseName.log');
File _rotated(int n) => File('${dir.path}/$baseName.$n.log');
/// Every log file that exists, newest first: the active file then the rotated
/// ones.
///
/// The rotation naming lives here rather than in callers, so an exporter does
/// not have to duplicate the scheme. Needed because a line written once, at
/// startup, can rotate out of the active file long before the user exports,
/// and until now nothing could reach the rotated files at all (#906).
Future<List<File>> existingFiles() async {
final files = <File>[];
if (await activeFile.exists()) files.add(activeFile);
for (var n = 1; n < maxFiles; n++) {
final f = _rotated(n);
if (await f.exists()) files.add(f);
}
return files;
}
/// Append [line] (a trailing newline is added), rotating first if it would
/// push the active file past [maxBytes].
Future<void> writeLine(String line) async {

@ -67,16 +67,26 @@ class LogExport {
// possibly-deactivated widget after the await.
final messenger = ScaffoldMessenger.of(context);
final l10n = context.l10n;
final file = await FileLogService.instance.flushAndGetActiveFile();
// ANR traces live beside the log rather than inside it, so they have to be
// attached explicitly or they never reach anyone (#906). Mobile only: the
// records are Android-only, and the desktop path saves a single file.
final extras = _isMobile
? await AppExitInfoService.traceFiles()
: const <File>[];
// On mobile, take every log file rather than just the active one, and the
// ANR traces with them (#906). Two reasons: a trace lives beside the log
// rather than inside it, and a pointer line written once at startup can
// rotate into `.1.log` before the user exports, which would hand over a
// trace with its metadata line missing. Desktop keeps its single-file Save
// As: there are no exit records off Android.
final List<File> logs;
if (_isMobile) {
logs = await FileLogService.instance.flushAndGetAllFiles();
} else {
final active = await FileLogService.instance.flushAndGetActiveFile();
logs = active == null ? const <File>[] : <File>[active];
}
final extras = <File>[
...logs.skip(1),
if (_isMobile) ...await AppExitInfoService.traceFiles(),
];
await _exportFile(
messenger,
file: file,
file: logs.isEmpty ? null : logs.first,
fileName: _defaultFileName,
subject: l10n.debugLog_shareSubject,
unavailableMessage: l10n.debugLog_logUnavailable,

@ -76,6 +76,57 @@ void main() {
expect(File('${dir.path}/t.1.log').existsSync(), isTrue);
});
// #906: the export used to ship only the active file, so a line written
// once at startup was lost as soon as the log rotated. These pin the
// accessor the export now relies on.
group('existingFiles (#906)', () {
test('is empty before anything is written', () async {
final w = FileLogWriter(dir: dir, baseName: 't', maxBytes: 1 << 20);
expect(await w.existingFiles(), isEmpty);
});
test('returns just the active file before any rotation', () async {
final w = FileLogWriter(dir: dir, baseName: 't', maxBytes: 1 << 20);
await w.writeLine('only');
final files = await w.existingFiles();
expect(files.map((f) => f.uri.pathSegments.last), ['t.log']);
});
test('returns the rotated files too, newest first', () async {
final w = FileLogWriter(
dir: dir,
baseName: 't',
maxBytes: 100,
maxFiles: 3,
);
for (var i = 0; i < 60; i++) {
await w.writeLine('line $i ${'x' * 20}');
}
final names = (await w.existingFiles())
.map((f) => f.uri.pathSegments.last)
.toList();
expect(names, ['t.log', 't.1.log', 't.2.log']);
});
test('never reports more than maxFiles', () async {
final w = FileLogWriter(
dir: dir,
baseName: 't',
maxBytes: 60,
maxFiles: 2,
);
for (var i = 0; i < 80; i++) {
await w.writeLine('line $i ${'y' * 20}');
}
final files = await w.existingFiles();
expect(files.length, lessThanOrEqualTo(2));
expect(
files.map((f) => f.uri.pathSegments.last),
isNot(contains('t.2.log')),
);
});
});
// #906: exit-record capture puts a pointer line in offband.log and the
// trace itself in a sibling file, partly because a trace is tens of KB.
// These pin down what a large entry actually does to rotation, so the

Loading…
Cancel
Save

Powered by TurnKey Linux.