Problem Description
klogd worked fine on Android 9 or 10, but no longer works on Android 12. I am working on project with klogd version 1.5.0. This version of klogd has some file descriptor related issues. fdsan documentation refers that from API 30 fdsan has set default value to ANDROID_FDSAN_ERROR_LEVEL_FATAL Due to which klogd is getting killed immediately after some descriptor issue of klogd.
Error message:
logcat logs
libc : fdsan: attempted to close file descriptor 3, expected to be unowned, actually owned by FILE* 0x70fde09018
libc : Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 6539 (klogd), pid 6539 (klogd)
crash_dump64: obtaining output fd from tombstoned, type: kDebuggerdTombstoneProto
tombstoned: received crash request for pid 6539
crash_dump64: performing dump of process 6539 (target tid = 6539)
signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr --------
Abort message: 'fdsan: attempted to close file descriptor 3, expected to be unowned, actually owned by FILE* 0x70fde09018'
x0 0000000000000000 x1 000000000000198b x2 0000000000000006 x3 0000007fe1acfa30
x4 0080808080808080 x5 0080808080808080 x6 0080808080808080 x7 8080808080808080
x8 00000000000000f0 x9 5b25f7251ae4d21f x10 0000000000000001 x11 0000000000000000
x12 0101010101010101 x13 00000003f6f09532 x14 0016da37cf86e56c x15 0000000000000010
x16 00000070fe36ed20 x17 00000070fe348d80 x18 00000071028d4000 x19 000000000000198b
x20 000000000000198b x21 0000007101ddf010 x22 0000000000000003 x23 0000007fe1acf828
x24 0000007fe1acfb20 x25 0000007fe1acf7a0 x26 0000007fe1acf760 x27 ffffff80ffffffc8
x28 000000579164fc4e x29 0000007fe1acfac0
lr 00000070fe2fe6d0 sp 0000007fe1acf6e0 pc 00000070fe2fe6f4 pst 0000000000000000
backtrace:
#00 pc 000000000008d6f4 /apex/com.android.runtime/lib64/bionic/libc.so (fdsan_error(char const*, ...)+564)
#01 pc 000000000008d3f8 /apex/com.android.runtime/lib64/bionic/libc.so (android_fdsan_close_with_tag+752)
#02 pc 000000000008db78 /apex/com.android.runtime/lib64/bionic/libc.so (close+16)
#03 pc 00000000000037e0 /vendor/bin/klogd (write_pid+176)
#04 pc 0000000000003eb4 /vendor/bin/klogd (main+628)
#05 pc 0000000000082180 /apex/com.android.runtime/lib64/bionic/libc.so (__libc_init+96)
How to resolve this issue without changing fdsan default level and without reverting API level?
Fixes tried klogd works after setting fdsan default_level in libc/bionic/fdsan.cpp to ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE. But this might reduce chances of catching file descriptor bugs. This is not feasible approach.
Found fix for this: As per backtrace, there is issue in klogd's write_pid() function. close(fd) is called instead of fclose(f). close() does not clear buffer. Use fclose() instead.