当前位置:   article > 正文

Android10.0 日志系统分析(三)-logd、logcat读写日志源码分析-[Android取经之路]_android logd代码移植

android logd代码移植

摘要:本节主要来讲解Android10.0 logd、logcat读写日志源码内容

阅读本文大约需要花费20分钟。

文章首发微信公众号:IngresGe

专注于Android系统级源码分析,Android的平台设计,欢迎关注我,谢谢!

欢迎关注我的公众号!

[Android取经之路] 的源码都基于Android-Q(10.0) 进行分析

[Android取经之路]系列文章:

《系统启动篇》

  1. Android系统架构
  2. Android是怎么启动的
  3. Android 10.0系统启动之init进程
  4. Android10.0系统启动之Zygote进程
  5. Android 10.0 系统启动之SystemServer进程
  6. Android 10.0 系统服务之ActivityMnagerService
  7. Android10.0系统启动之Launcher(桌面)启动流程
  8. Android10.0应用进程创建过程以及Zygote的fork流程
  9. Android 10.0 PackageManagerService(一)工作原理及启动流程
  10. Android 10.0 PackageManagerService(二)权限扫描
  11. Android 10.0 PackageManagerService(三)APK扫描
  12. Android 10.0 PackageManagerService(四)APK安装流程

《日志系统篇》

  1. Android10.0 日志系统分析(一)-logd、logcat 指令说明、分类和属性
  2. Android10.0 日志系统分析(二)-logd、logcat架构分析及日志系统初始化
  3. Android10.0 日志系统分析(三)-logd、logcat读写日志源码分析
  4. Android10.0 日志系统分析(四)-selinux、kernel日志在logd中的实现​

《Binder通信原理》

  1. Android10.0 Binder通信原理(一)Binder、HwBinder、VndBinder概要
  2. Android10.0 Binder通信原理(二)-Binder入门篇
  3. Android10.0 Binder通信原理(三)-ServiceManager篇
  4. Android10.0 Binder通信原理(四)-Native-C\C++实例分析
  5. Android10.0 Binder通信原理(五)-Binder驱动分析
  6. Android10.0 Binder通信原理(六)-Binder数据如何完成定向打击
  7. Android10.0 Binder通信原理(七)-Framework binder示例
  8. Android10.0 Binder通信原理(八)-Framework层分析
  9. Android10.0 Binder通信原理(九)-AIDL Binder示例
  10. Android10.0 Binder通信原理(十)-AIDL原理分析-Proxy-Stub设计模式
  11. Android10.0 Binder通信原理(十一)-Binder总结

  《HwBinder通信原理》

  1. HwBinder入门篇-Android10.0 HwBinder通信原理(一)
  2.  HIDL详解-Android10.0 HwBinder通信原理(二)
  3. HIDL示例-C++服务创建Client验证-Android10.0 HwBinder通信原理(三)
  4. HIDL示例-JAVA服务创建-Client验证-Android10.0 HwBinder通信原理(四)
  5. HwServiceManager篇-Android10.0 HwBinder通信原理(五)
  6. Native层HIDL服务的注册原理-Android10.0 HwBinder通信原理(六)
  7. Native层HIDL服务的获取原理-Android10.0 HwBinder通信原理(七)
  8. JAVA层HIDL服务的注册原理-Android10.0 HwBinder通信原理(八)
  9. JAVA层HIDL服务的获取原理-Android10.0 HwBinder通信原理(九)
  10. HwBinder驱动篇-Android10.0 HwBinder通信原理(十)
  11. HwBinder原理总结-Android10.0 HwBinder通信原理(十一)

《编译原理》

  1. 编译系统入门篇-Android10.0编译系统(一)
  2. 编译环境初始化-Android10.0编译系统(二)
  3. make编译过程-Android10.0编译系统(三)
  4. Image打包流程-Android10.0编译系统(四)
  5. Kati详解-Android10.0编译系统(五)

上一节我们看了Android日志系统的架构分析以及logd、logcat的初始化操作,这一节我们来看看日志系统的读写操作

7.3 写日志

    写日志的过程,主要是通过liblog,把日志写入到/dev/socket/logdw, 守护进程logd监控logdw的写入信息,一旦发现有日志写入后,会把日志存入到LogListener的LogBuffer中。

日志写入调用栈如下

7.3.1  [logger_write.cpp] __android_log_buf_write()

说明:JAVA层通过jni最终调用到liblog的 __android_log_buf_write(),组装结构体iovec,调用write_to_log()进行日志写入

源码:

 

  1. int __android_log_buf_write(int bufID, int prio, const char* tag, const char* msg) {
  2. if (!tag) tag = "";
  3. ...
  4. //组装结构体,包括tag、msg
  5. struct iovec vec[3];
  6. vec[0].iov_base = (unsigned char*)&prio;
  7. vec[0].iov_len = 1;
  8. vec[1].iov_base = (void*)tag;
  9. vec[1].iov_len = strlen(tag) + 1;
  10. vec[2].iov_base = (void*)msg;
  11. vec[2].iov_len = strlen(msg) + 1;
  12. //进一步调用,进行日志的写入
  13. return write_to_log(static_cast<log_id_t>(bufID), vec, 3);
  14. }

7.3.2 [logger_write.cpp] write_to_log()

write_to_log为一个函数指针,默认指向__write_to_log_init()

static int (*write_to_log)(log_id_t, struct iovec* vec, size_t nr) = __write_to_log_init;

7.3.3 [logger_write.cpp] __write_to_log_init()

说明:write_to_log 开始指向__write_to_log_init(),首先调用__write_to_log_initialize()进行日志配置初始化,再把write_to_log 指向__write_to_log_daemon(),调用__write_to_log_daemon()进行日志写入。

源码:

  1. static int __write_to_log_init(log_id_t log_id, struct iovec* vec, size_t nr) {
  2. int ret, save_errno = errno;
  3. __android_log_lock();
  4. //第一次调用时,write_to_log 指向__write_to_log_init(),此条件满足
  5. if (write_to_log == __write_to_log_init) {
  6. //日志配置初始化,最终调用到logdLoggerWrite来进行日志的配置
  7. ret = __write_to_log_initialize();
  8. if (ret < 0) {
  9. __android_log_unlock(); //解锁log写入进程,避免死锁
  10. if (!list_empty(&__android_log_persist_write)) {
  11. __write_to_log_daemon(log_id, vec, nr);
  12. }
  13. errno = save_errno;
  14. return ret;
  15. }
  16. //write_to_log 指向__write_to_log_daemon
  17. write_to_log = __write_to_log_daemon;
  18. }
  19. __android_log_unlock();
  20. //通过__write_to_log_daemon进行日志写入
  21. ret = write_to_log(log_id, vec, nr);
  22. errno = save_errno;
  23. return ret;
  24. }

 

7.3.4 日志配置

[logger_write.cpp]  __write_to_log_initialize()

说明:首先进行日志的配置,得到logdLoggerWrite 和pmsgLoggerWrite两个日志节点,包含了open、close、write的函数指针

源码:

  1. static int __write_to_log_initialize() {
  2. struct android_log_transport_write* transport;
  3. struct listnode* n;
  4. int i = 0, ret = 0;
  5. //日志的配置
  6. __android_log_config_write();
  7. write_transport_for_each_safe(transport, n, &__android_log_transport_write) {
  8. //检查节点是否可用
  9. __android_log_cache_available(transport);
  10. ...
  11. ++ret;
  12. }
  13. write_transport_for_each_safe(transport, n, &__android_log_persist_write) {
  14. //检查节点是否可用
  15. __android_log_cache_available(transport);
  16. ...
  17. ++i;
  18. }
  19. if (!ret && !i) {
  20. return -ENODEV;
  21. }
  22. return ret;
  23. }

[config_write.cpp] __android_log_config_write()

说明:对 "struct android_log_transport_write logdLoggerWrite" 和 "struct android_log_transport_write pmsgLoggerWrite" 的包装.

他们分别在 "/system/core/liblog/logd_writer.c" 和 "/system/core/liblog/pmsg_writer.c" 中实现

源码:

  1. void __android_log_config_write() {
  2. if ((__android_log_transport == LOGGER_DEFAULT) || (__android_log_transport & LOGGER_LOGD)) {
  3. #if (FAKE_LOG_DEVICE == 0)
  4. extern struct android_log_transport_write logdLoggerWrite;
  5. extern struct android_log_transport_write pmsgLoggerWrite;
  6. __android_log_add_transport(&__android_log_transport_write, &logdLoggerWrite);
  7. __android_log_add_transport(&__android_log_persist_write, &pmsgLoggerWrite);
  8. #else
  9. extern struct android_log_transport_write fakeLoggerWrite;
  10. __android_log_add_transport(&__android_log_transport_write, &fakeLoggerWrite);
  11. #endif
  12. }
  13. if (__android_log_transport & LOGGER_STDERR) {
  14. extern struct android_log_transport_write stderrLoggerWrite;
  15. if (list_empty(&__android_log_transport_write)) {
  16. __android_log_add_transport(&__android_log_transport_write, &stderrLoggerWrite);
  17. } else {
  18. struct android_log_transport_write* transp;
  19. write_transport_for_each(transp, &__android_log_transport_write) {
  20. if (transp == &stderrLoggerWrite) {
  21. return;
  22. }
  23. }
  24. __android_log_add_transport(&__android_log_persist_write, &stderrLoggerWrite);
  25. }
  26. }
  27. }

[logd_writer.c] logdLoggerWrite

说明:配置logdLoggerWrite的节点,有open、close、write操作,

logdOpen()中连接"/dev/socket/logdw",再通过logdWrite()把日志写入到logdw中

  1. struct android_log_transport_write logdLoggerWrite = {
  2. .node = {&logdLoggerWrite.node, &logdLoggerWrite.node},
  3. .context.sock = -EBADF,
  4. .name = "logd",
  5. .available = logdAvailable,
  6. .open = logdOpen,
  7. .close = logdClose,
  8. .write = logdWrite,
  9. };

[logd_writer.c] logdOpen()

说明:连接"/dev/socket/logdw" socket,记录socket句柄到 logdLoggerWrite.context.sock

  1. static int logdOpen() {
  2. int i, ret = 0;
  3. i = atomic_load(&logdLoggerWrite.context.sock);
  4. if (i < 0) {
  5. int sock = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
  6. if (sock < 0) {
  7. ret = -errno;
  8. } else {
  9. struct sockaddr_un un;
  10. memset(&un, 0, sizeof(struct sockaddr_un));
  11. un.sun_family = AF_UNIX;
  12. strcpy(un.sun_path, "/dev/socket/logdw");
  13. if (TEMP_FAILURE_RETRY(connect(sock, (struct sockaddr*)&un, sizeof(struct sockaddr_un))) <
  14. 0) {
  15. ret = -errno;
  16. switch (ret) {
  17. case -ENOTCONN:
  18. case -ECONNREFUSED:
  19. case -ENOENT:
  20. i = atomic_exchange(&logdLoggerWrite.context.sock, ret);
  21. [[fallthrough]];
  22. default:
  23. break;
  24. }
  25. close(sock);
  26. } else {
  27. ret = atomic_exchange(&logdLoggerWrite.context.sock, sock);
  28. if ((ret >= 0) && (ret != sock)) {
  29. close(ret);
  30. }
  31. ret = 0;
  32. }
  33. }
  34. }
  35. return ret;
  36. }

[logd_writer.c] logdWrite()

说明:logdWrite() 通过调用writev,把log非阻塞地写入到socket .

  1. static int logdWrite(log_id_t logId, struct timespec* ts, struct iovec* vec, size_t nr) {
  2. ssize_t ret;
  3. int sock;
  4. static const unsigned headerLength = 1;
  5. struct iovec newVec[nr + headerLength];
  6. android_log_header_t header;
  7. size_t i, payloadSize;
  8. static atomic_int dropped;
  9. static atomic_int droppedSecurity;
  10. //原子操作,load logdLoggerWrite.context.sock
  11. sock = atomic_load(&logdLoggerWrite.context.sock);
  12. if (sock < 0) switch (sock) {
  13. case -ENOTCONN:
  14. case -ECONNREFUSED:
  15. case -ENOENT:
  16. break;
  17. default:
  18. return -EBADF;
  19. }
  20. /* logd, after initialization and priv drop */
  21. if (__android_log_uid() == AID_LOGD) {
  22. return 0;
  23. }
  24. header.tid = gettid();
  25. header.realtime.tv_sec = ts->tv_sec;
  26. header.realtime.tv_nsec = ts->tv_nsec;
  27. newVec[0].iov_base = (unsigned char*)&header;
  28. newVec[0].iov_len = sizeof(header);
  29. if (sock >= 0) {
  30. int32_t snapshot = atomic_exchange_explicit(&droppedSecurity, 0, memory_order_relaxed);
  31. if (snapshot) {
  32. android_log_event_int_t buffer;
  33. header.id = LOG_ID_SECURITY;
  34. buffer.header.tag = htole32(LIBLOG_LOG_TAG);
  35. buffer.payload.type = EVENT_TYPE_INT;
  36. buffer.payload.data = htole32(snapshot);
  37. newVec[headerLength].iov_base = &buffer;
  38. newVec[headerLength].iov_len = sizeof(buffer);
  39. //调用writev,把日志写入logdw
  40. ret = TEMP_FAILURE_RETRY(writev(sock, newVec, 2));
  41. if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
  42. atomic_fetch_add_explicit(&droppedSecurity, snapshot, memory_order_relaxed);
  43. }
  44. }
  45. snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed);
  46. if (snapshot && __android_log_is_loggable_len(ANDROID_LOG_INFO, "liblog", strlen("liblog"),
  47. ANDROID_LOG_VERBOSE)) {
  48. android_log_event_int_t buffer;
  49. header.id = LOG_ID_EVENTS;
  50. buffer.header.tag = htole32(LIBLOG_LOG_TAG);
  51. buffer.payload.type = EVENT_TYPE_INT;
  52. buffer.payload.data = htole32(snapshot);
  53. newVec[headerLength].iov_base = &buffer;
  54. newVec[headerLength].iov_len = sizeof(buffer);
  55. ret = TEMP_FAILURE_RETRY(writev(sock, newVec, 2));
  56. if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
  57. atomic_fetch_add_explicit(&dropped, snapshot, memory_order_relaxed);
  58. }
  59. }
  60. }
  61. header.id = logId;
  62. for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
  63. newVec[i].iov_base = vec[i - headerLength].iov_base;
  64. payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
  65. if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
  66. newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
  67. if (newVec[i].iov_len) {
  68. ++i;
  69. }
  70. break;
  71. }
  72. }
  73. /*
  74. * The write below could be lost, but will never block.
  75. *
  76. * ENOTCONN occurs if logd has died.
  77. * ENOENT occurs if logd is not running and socket is missing.
  78. * ECONNREFUSED occurs if we can not reconnect to logd.
  79. * EAGAIN occurs if logd is overloaded.
  80. */
  81. if (sock < 0) {
  82. ret = sock;
  83. } else {
  84. ret = TEMP_FAILURE_RETRY(writev(sock, newVec, i));
  85. if (ret < 0) {
  86. ret = -errno;
  87. }
  88. }
  89. switch (ret) {
  90. case -ENOTCONN:
  91. case -ECONNREFUSED:
  92. case -ENOENT:
  93. if (__android_log_trylock()) {
  94. return ret; /* in a signal handler? try again when less stressed */
  95. }
  96. __logdClose(ret);
  97. ret = logdOpen();
  98. __android_log_unlock();
  99. if (ret < 0) {
  100. return ret;
  101. }
  102. ret = TEMP_FAILURE_RETRY(writev(atomic_load(&logdLoggerWrite.context.sock), newVec, i));
  103. if (ret < 0) {
  104. ret = -errno;
  105. }
  106. [[fallthrough]];
  107. default:
  108. break;
  109. }
  110. if (ret > (ssize_t)sizeof(header)) {
  111. ret -= sizeof(header);
  112. } else if (ret == -EAGAIN) {
  113. atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed);
  114. if (logId == LOG_ID_SECURITY) {
  115. atomic_fetch_add_explicit(&droppedSecurity, 1, memory_order_relaxed);
  116. }
  117. }
  118. return ret;
  119. }

[pmsg_writer.c] pmsgLoggerWrite

说明:配置pmsgLoggerWrite的节点,pmsgOpen()打开"/dev/pmsg0",在通过pmsgWrite()把日志写入到"/dev/pmsg0"中

  1. struct android_log_transport_write pmsgLoggerWrite = {
  2. .node = {&pmsgLoggerWrite.node, &pmsgLoggerWrite.node},
  3. .context.fd = -1,
  4. .name = "pmsg",
  5. .available = pmsgAvailable,
  6. .open = pmsgOpen,
  7. .close = pmsgClose,
  8. .write = pmsgWrite,
  9. };

[pmsg_writer.c] pmsgOpen()

说明:打开"/dev/pmsg0"

  1. static int pmsgOpen() {
  2. int fd = atomic_load(&pmsgLoggerWrite.context.fd);
  3. if (fd < 0) {
  4. int i;
  5. fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY | O_CLOEXEC));
  6. i = atomic_exchange(&pmsgLoggerWrite.context.fd, fd);
  7. if ((i >= 0) && (i != fd)) {
  8. close(i);
  9. }
  10. }
  11. return fd;
  12. }

[pmsg_writer.c] pmsgWrite()

说明:日志写入到"/dev/pmsg0"

  1. static int pmsgWrite(log_id_t logId, struct timespec* ts, struct iovec* vec, size_t nr) {
  2. static const unsigned headerLength = 2;
  3. struct iovec newVec[nr + headerLength];
  4. android_log_header_t header;
  5. android_pmsg_log_header_t pmsgHeader;
  6. size_t i, payloadSize;
  7. ssize_t ret;
  8. if ((logId == LOG_ID_EVENTS) && !__android_log_is_debuggable()) {
  9. if (vec[0].iov_len < 4) {
  10. return -EINVAL;
  11. }
  12. if (SNET_EVENT_LOG_TAG != get4LE(static_cast<uint8_t*>(vec[0].iov_base))) {
  13. return -EPERM;
  14. }
  15. }
  16. if (atomic_load(&pmsgLoggerWrite.context.fd) < 0) {
  17. return -EBADF;
  18. }
  19. pmsgHeader.magic = LOGGER_MAGIC;
  20. pmsgHeader.len = sizeof(pmsgHeader) + sizeof(header);
  21. pmsgHeader.uid = __android_log_uid();
  22. pmsgHeader.pid = getpid();
  23. header.id = logId;
  24. header.tid = gettid();
  25. header.realtime.tv_sec = ts->tv_sec;
  26. header.realtime.tv_nsec = ts->tv_nsec;
  27. newVec[0].iov_base = (unsigned char*)&pmsgHeader;
  28. newVec[0].iov_len = sizeof(pmsgHeader);
  29. newVec[1].iov_base = (unsigned char*)&header;
  30. newVec[1].iov_len = sizeof(header);
  31. for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
  32. newVec[i].iov_base = vec[i - headerLength].iov_base;
  33. payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
  34. if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
  35. newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
  36. if (newVec[i].iov_len) {
  37. ++i;
  38. }
  39. payloadSize = LOGGER_ENTRY_MAX_PAYLOAD;
  40. break;
  41. }
  42. }
  43. pmsgHeader.len += payloadSize;
  44. ret = TEMP_FAILURE_RETRY(writev(atomic_load(&pmsgLoggerWrite.context.fd), newVec, i));
  45. if (ret < 0) {
  46. ret = errno ? -errno : -ENOTCONN;
  47. }
  48. if (ret > (ssize_t)(sizeof(header) + sizeof(pmsgHeader))) {
  49. ret -= sizeof(header) - sizeof(pmsgHeader);
  50. }
  51. return ret;
  52. }

7.3.4 日志写入 /dev/socket/logdw

    在前面,日志配置已经完成,那么接下来调用__write_to_log_daemon()进行日志的真正写入

[logger_write.cpp] __write_to_log_daemon()

说明:最终通过获取logdLoggerWrite 和 pmsgLoggerWrite的write操作,即 调用logdWrite()\pmsgWrite()进行日志的写入

源码:

  1. static int __write_to_log_daemon(log_id_t log_id, struct iovec* vec, size_t nr) {
  2. struct android_log_transport_write* node;
  3. int ret, save_errno;
  4. struct timespec ts;
  5. size_t len, i;
  6. for (len = i = 0; i < nr; ++i) {
  7. len += vec[i].iov_len;
  8. }
  9. if (!len) {
  10. return -EINVAL;
  11. }
  12. save_errno = errno;
  13. #if defined(__ANDROID__)
  14. clock_gettime(android_log_clockid(), &ts);
  15. if (log_id == LOG_ID_SECURITY) {
  16. if (vec[0].iov_len < 4) {
  17. errno = save_errno;
  18. return -EINVAL;
  19. }
  20. ret = check_log_uid_permissions();
  21. if (ret < 0) {
  22. errno = save_errno;
  23. return ret;
  24. }
  25. if (!__android_log_security()) {
  26. /* If only we could reset downstream logd counter */
  27. errno = save_errno;
  28. return -EPERM;
  29. }
  30. } else if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS) {
  31. const char* tag;
  32. size_t len;
  33. EventTagMap *m, *f;
  34. if (vec[0].iov_len < 4) {
  35. errno = save_errno;
  36. return -EINVAL;
  37. }
  38. tag = NULL;
  39. len = 0;
  40. f = NULL;
  41. m = (EventTagMap*)atomic_load(&tagMap);
  42. if (!m) {
  43. ret = __android_log_trylock();
  44. m = (EventTagMap*)atomic_load(&tagMap); /* trylock flush cache */
  45. if (!m) {
  46. m = android_openEventTagMap(NULL);
  47. if (ret) { /* trylock failed, use local copy, mark for close */
  48. f = m;
  49. } else {
  50. if (!m) { /* One chance to open map file */
  51. m = (EventTagMap*)(uintptr_t)-1LL;
  52. }
  53. atomic_store(&tagMap, (uintptr_t)m);
  54. }
  55. }
  56. if (!ret) { /* trylock succeeded, unlock */
  57. __android_log_unlock();
  58. }
  59. }
  60. if (m && (m != (EventTagMap*)(uintptr_t)-1LL)) {
  61. tag = android_lookupEventTag_len(m, &len, get4LE(static_cast<uint8_t*>(vec[0].iov_base)));
  62. }
  63. ret = __android_log_is_loggable_len(ANDROID_LOG_INFO, tag, len, ANDROID_LOG_VERBOSE);
  64. if (f) { /* local copy marked for close */
  65. android_closeEventTagMap(f);
  66. }
  67. if (!ret) {
  68. errno = save_errno;
  69. return -EPERM;
  70. }
  71. } else {
  72. /* Validate the incoming tag, tag content can not split across iovec */
  73. char prio = ANDROID_LOG_VERBOSE;
  74. const char* tag = static_cast<const char*>(vec[0].iov_base);
  75. size_t len = vec[0].iov_len;
  76. if (!tag) {
  77. len = 0;
  78. }
  79. if (len > 0) {
  80. prio = *tag;
  81. if (len > 1) {
  82. --len;
  83. ++tag;
  84. } else {
  85. len = vec[1].iov_len;
  86. tag = ((const char*)vec[1].iov_base);
  87. if (!tag) {
  88. len = 0;
  89. }
  90. }
  91. }
  92. /* tag must be nul terminated */
  93. if (tag && strnlen(tag, len) >= len) {
  94. tag = NULL;
  95. }
  96. if (!__android_log_is_loggable_len(prio, tag, len - 1, ANDROID_LOG_VERBOSE)) {
  97. errno = save_errno;
  98. return -EPERM;
  99. }
  100. }
  101. #else
  102. /* simulate clock_gettime(CLOCK_REALTIME, &ts); */
  103. {
  104. struct timeval tv;
  105. gettimeofday(&tv, NULL);
  106. ts.tv_sec = tv.tv_sec;
  107. ts.tv_nsec = tv.tv_usec * 1000;
  108. }
  109. #endif
  110. ret = 0;
  111. i = 1 << log_id;
  112. write_transport_for_each(node, &__android_log_transport_write) {
  113. if (node->logMask & i) {
  114. ssize_t retval;
  115. //从logdLoggerWrite中拿到write操作,即logdWrite()进行日志的写入
  116. retval = (*node->write)(log_id, &ts, vec, nr);
  117. if (ret >= 0) {
  118. ret = retval;
  119. }
  120. }
  121. }
  122. write_transport_for_each(node, &__android_log_persist_write) {
  123. if (node->logMask & i) {
  124. //从pmsgLoggerWrite中拿到write操作,即pmsgWrite()进行日志的写入
  125. (void)(*node->write)(log_id, &ts, vec, nr);
  126. }
  127. }
  128. errno = save_errno;
  129. return ret;
  130. }

7.3.5 日志写入LogListener的LogBuffer

在前面logd初始化时,我们能够看到LogListener中会先创建一个LogBuffer,LogBuffer在初始化init()中会初始化各个log的域的大小(如main、crash、system等默认为256k),接着会启动一个SocketListener,对/dev/socket/logdw进行监听,

  [/system/core/logd/main.cpp]

  1. int main(int argc, char* argv[]) {
  2. ...
  3. LogListener* swl = new LogListener(logBuf, reader);
  4. if (swl->startListener(600)) {
  5. return EXIT_FAILURE;
  6. }
  7. ...
  8. }

LogListene的对象创建时,会先调用 getLogSocket(),对logdw进行监听。

  1. int LogListener::getLogSocket() {
  2. static const char socketName[] = "logdw";
  3. int sock = android_get_control_socket(socketName);
  4. if (sock < 0) { // logd started up in init.sh
  5. sock = socket_local_server(
  6. socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_DGRAM);
  7. int on = 1;
  8. if (setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) {
  9. return -1;
  10. }
  11. }
  12. return sock;
  13. }

在startListener函数中创建线程,线程注册函数为SocketListener::threadStart;

执行runListener函数,如果socket监听到数据,则执行onDataAvailable函数进行处理;

调用logbuf->log(LogBuffer::log),这个函数很重要,新建一个LogBufferElement对象(用于保存log),调用mLogElements.insert将LogBufferElement加入list容器,实现log的保存。

源码:

  1. bool LogListener::onDataAvailable(SocketClient* cli) {
  2. static bool name_set;
  3. if (!name_set) {
  4. prctl(PR_SET_NAME, "logd.writer");
  5. name_set = true;
  6. }
  7. // + 1 to ensure null terminator if MAX_PAYLOAD buffer is received
  8. char buffer[sizeof_log_id_t + sizeof(uint16_t) + sizeof(log_time) +
  9. LOGGER_ENTRY_MAX_PAYLOAD + 1];
  10. struct iovec iov = { buffer, sizeof(buffer) - 1 };
  11. //将日志写入list容器
  12. int res = logbuf->log(logId, header->realtime, cred->uid, cred->pid, header->tid, msg,
  13. ((size_t)n <= UINT16_MAX) ? (uint16_t)n : UINT16_MAX);
  14. if (res > 0) {
  15. reader->notifyNewLog(static_cast<log_mask_t>(1 << logId));
  16. }
  17. return true;
  18. }

7.4 读取日志

    读取日志时,主要通过logcat工具来抓取。

    Logcat是通过liblog 连接 "/dev/socket/logdr" 来获取日志。logcat通过调用liblog 的函数android_logger_list_read()进行日志的读取,最终是连接"/dev/socket/logdr",并读取其中的日志。

    logdr的日志由 logd的LogReader 进行写入。

    日志读取调用栈如下:

  logcat启动后,会调用android_logcat_run_command(),最终进入__logcat()来解析command,并读取日志,我们就从__logcat()来进行分析

7.4.1 [logcat.cpp] __logcat()

说明:__logcat()首先解析传入的command,然后进行日志的读取,如果出现日志读取失败,则退出logcat进程,否则手动启动的logcat进行一直处于运行状态

源码:

  1. static int __logcat(android_logcat_context_internal* context) {
  2. ...
  3. struct logger_list* logger_list;
  4. ...
  5. //logcat command的解析
  6. while (true) {
  7. int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
  8. &option_index);
  9. switch (c) {
  10. ...
  11. case 'g':
  12. if (!optarg) {
  13. getLogSize = true;
  14. break;
  15. }
  16. FALLTHROUGH_INTENDED;
  17. case 'b': {
  18. std::unique_ptr<char, void (*)(void*)> buffers(strdup(optarg), free);
  19. char* arg = buffers.get();
  20. unsigned idMask = 0;
  21. char* sv = nullptr; // protect against -ENOMEM above
  22. while (!!(arg = strtok_r(arg, delimiters, &sv))) {
  23. if (!strcmp(arg, "default")) {
  24. idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
  25. (1 << LOG_ID_CRASH);
  26. } else if (!strcmp(arg, "all")) {
  27. allSelected = true;
  28. idMask = (unsigned)-1;
  29. } else {
  30. log_id_t log_id = android_name_to_log_id(arg);
  31. const char* name = android_log_id_to_name(log_id);
  32. if (!!strcmp(name, arg)) {
  33. logcat_panic(context, HELP_TRUE,
  34. "unknown buffer %s\n", arg);
  35. goto exit;
  36. }
  37. if (log_id == LOG_ID_SECURITY) allSelected = false;
  38. idMask |= (1 << log_id);
  39. }
  40. arg = nullptr;
  41. }
  42. for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
  43. const char* name = android_log_id_to_name((log_id_t)i);
  44. log_id_t log_id = android_name_to_log_id(name);
  45. if (log_id != (log_id_t)i) continue;
  46. if (!(idMask & (1 << i))) continue;
  47. bool found = false;
  48. for (dev = context->devices; dev; dev = dev->next) {
  49. if (!strcmp(name, dev->device)) {
  50. found = true;
  51. break;
  52. }
  53. if (!dev->next) break;
  54. }
  55. if (found) continue;
  56. bool binary = !strcmp(name, "events") ||
  57. !strcmp(name, "security") ||
  58. !strcmp(name, "stats");
  59. log_device_t* d = new log_device_t(name, binary);
  60. if (dev) {
  61. dev->next = d;
  62. dev = d;
  63. } else {
  64. context->devices = dev = d;
  65. }
  66. context->devCount++;
  67. }
  68. }
  69. ...
  70. case 'h':
  71. show_help(context);
  72. show_format_help(context);
  73. goto exit;
  74. default:
  75. logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n", optopt);
  76. goto exit;
  77. }
  78. }
  79. ...
  80. while (!context->stop &&
  81. (!context->maxCount || (context->printCount < context->maxCount))) {
  82. struct log_msg log_msg;
  83. //调用liblog的接口,读取"/dev/socket/logdr"来读取日志
  84. int ret = android_logger_list_read(logger_list, &log_msg);
  85. if (!ret) {
  86. logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
  87. break;
  88. }
  89. ...
  90. }
  91. close:
  92. // Short and sweet. Implemented generic version in android_logcat_destroy.
  93. while (!!(dev = context->devices)) {
  94. context->devices = dev->next;
  95. delete dev;
  96. }
  97. android_logger_list_free(logger_list);
  98. exit:
  99. // close write end of pipe to help things along
  100. if (context->output_fd == context->fds[1]) {
  101. android::close_output(context);
  102. }
  103. if (context->error_fd == context->fds[1]) {
  104. android::close_error(context);
  105. }
  106. if (context->fds[1] >= 0) {
  107. // NB: should be closed by the above
  108. int save_errno = errno;
  109. close(context->fds[1]);
  110. errno = save_errno;
  111. context->fds[1] = -1;
  112. }
  113. context->thread_stopped = true;
  114. return context->retval;
  115. }

 

下面进入liblog的android_logger_list_read()来进一步分析:

 

7.4.2 [logger_read.cpp] android_logger_list_read()

说明:先初始化logger_list,获得logdLoggerRead的节点,在进行transport_context的赋值操作,最终调用logdLoggerRead中的logdRead()进行日志读取

源码:

  1. int android_logger_list_read(struct logger_list* logger_list, struct log_msg* log_msg) {
  2. struct android_log_logger_list* logger_list_internal =
  3. (struct android_log_logger_list*)logger_list;
  4. //1. 初始化logger_list,把logdLoggerRead 和 pmsgLoggerRead 两个节点按需传给transoprt,我们一般使用 logdLoggerRead
  5. int ret = init_transport_context(logger_list_internal);
  6. if (ret < 0) {
  7. return ret;
  8. }
  9. //2. transoport的赋值
  10. android_log_transport_context* transport_context = &logger_list_internal->transport_context;
  11. //3.通过调用 logger_list中read方法,即logdLoggerRead中的logdRead()进行日志读取
  12. return android_transport_read(logger_list_internal, transport_context, log_msg);
  13. }

7.4.3 [logger_read.cpp] init_transport_context()

说明:根据logger_list->mode来决定使用哪种日志读取节点,我们大部分情况下使用logdLoggerRead,并进行赋值,主要内容就是得到 logdLoggerRead的节点,为后续日志读取提供服务

源码:

  1. static int init_transport_context(struct android_log_logger_list* logger_list) {
  2. if (!logger_list) {
  3. return -EINVAL;
  4. }
  5. if (list_empty(&logger_list->logger)) {
  6. return -EINVAL;
  7. }
  8. if (logger_list->transport_initialized) {
  9. return 0;
  10. }
  11. #if (FAKE_LOG_DEVICE == 0)
  12. extern struct android_log_transport_read logdLoggerRead;
  13. extern struct android_log_transport_read pmsgLoggerRead;
  14. struct android_log_transport_read* transport;
  15. //根据logger_list->mode来决定使用哪种日志读取节点,我们大部分情况下使用logdLoggerRead
  16. transport = (logger_list->mode & ANDROID_LOG_PSTORE) ? &pmsgLoggerRead : &logdLoggerRead;
  17. struct android_log_logger* logger;
  18. unsigned logMask = 0;
  19. //logger的校验
  20. logger_for_each(logger, logger_list) {
  21. log_id_t logId = logger->logId;
  22. if (logId == LOG_ID_SECURITY && __android_log_uid() != AID_SYSTEM) {
  23. continue;
  24. }
  25. if (transport->read && (!transport->available || transport->available(logId) >= 0)) {
  26. logMask |= 1 << logId;
  27. }
  28. }
  29. if (!logMask) {
  30. return -ENODEV;
  31. }
  32. //节点赋值
  33. logger_list->transport_context.transport = transport;
  34. logger_list->transport_context.logMask = logMask;
  35. logger_list->transport_context.ret = 1;
  36. #endif
  37. return 0;
  38. }

logdLoggerRead  中提供了 read、poll、close等操作:

  1. struct android_log_transport_read logdLoggerRead = {
  2. .node = {&logdLoggerRead.node, &logdLoggerRead.node},
  3. .name = "logd",
  4. .available = logdAvailable,
  5. .version = logdVersion,
  6. .read = logdRead,
  7. .poll = logdPoll,
  8. .close = logdClose,
  9. .clear = logdClear,
  10. .getSize = logdGetSize,
  11. .setSize = logdSetSize,
  12. .getReadableSize = logdGetReadableSize,
  13. .getPrune = logdGetPrune,
  14. .setPrune = logdSetPrune,
  15. .getStats = logdGetStats,
  16. };

 

7.4.4 [logger_read.cpp] android_transport_read()

说明: 调用的logdRead()来读取日志,并组装日志 msg,供logcat进行展示

源码:

  1. static int android_transport_read(struct android_log_logger_list* logger_list,
  2. struct android_log_transport_context* transp,
  3. struct log_msg* log_msg) {
  4. // 根据7.4.3 克制最终调用的是logdRead()来读取日志
  5. int ret = (*transp->transport->read)(logger_list, transp, log_msg);
  6. if (ret > (int)sizeof(*log_msg)) {
  7. ret = sizeof(*log_msg);
  8. }
  9. transp->ret = ret;
  10. /* propagate errors, or make sure len & hdr_size members visible */
  11. if (ret < (int)(sizeof(log_msg->entry.len) + sizeof(log_msg->entry.hdr_size))) {
  12. if (ret >= (int)sizeof(log_msg->entry.len)) {
  13. log_msg->entry.len = 0;
  14. }
  15. return ret;
  16. }
  17. /* hdr_size correction (logger_entry -> logger_entry_v2+ conversion) */
  18. if (log_msg->entry_v2.hdr_size == 0) {
  19. log_msg->entry_v2.hdr_size = sizeof(struct logger_entry);
  20. }
  21. if ((log_msg->entry_v2.hdr_size < sizeof(log_msg->entry_v1)) ||
  22. (log_msg->entry_v2.hdr_size > sizeof(log_msg->entry))) {
  23. return -EINVAL;
  24. }
  25. /* len validation */
  26. if (ret <= log_msg->entry_v2.hdr_size) {
  27. log_msg->entry.len = 0;
  28. } else {
  29. log_msg->entry.len = ret - log_msg->entry_v2.hdr_size;
  30. }
  31. return ret;
  32. }

7.4.5 [logd_reader.cpp] logdRead()

说明:连接socket "/dev/socket/lodgr",读取logdr 的日志

源码:

  1. static int logdRead(struct android_log_logger_list* logger_list,
  2. struct android_log_transport_context* transp, struct log_msg* log_msg) {
  3. int ret, e;
  4. struct sigaction ignore;
  5. struct sigaction old_sigaction;
  6. unsigned int old_alarm = 0;
  7. //连接socket "/dev/socket/lodgr"
  8. ret = logdOpen(logger_list, transp);
  9. if (ret < 0) {
  10. return ret;
  11. }
  12. memset(log_msg, 0, sizeof(*log_msg));
  13. unsigned int new_alarm = 0;
  14. if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
  15. if ((logger_list->mode & ANDROID_LOG_WRAP) &&
  16. (logger_list->start.tv_sec || logger_list->start.tv_nsec)) {
  17. /* b/64143705 */
  18. new_alarm = (ANDROID_LOG_WRAP_DEFAULT_TIMEOUT * 11) / 10 + 10;
  19. logger_list->mode &= ~ANDROID_LOG_WRAP;
  20. } else {
  21. new_alarm = 30;
  22. }
  23. memset(&ignore, 0, sizeof(ignore));
  24. ignore.sa_handler = caught_signal;
  25. sigemptyset(&ignore.sa_mask);
  26. /* particularily useful if tombstone is reporting for logd */
  27. sigaction(SIGALRM, &ignore, &old_sigaction);
  28. old_alarm = alarm(new_alarm);
  29. }
  30. //读取logdr 的日志
  31. ret = recv(ret, log_msg, LOGGER_ENTRY_MAX_LEN, 0);
  32. e = errno;
  33. if (new_alarm) {
  34. if ((ret == 0) || (e == EINTR)) {
  35. e = EAGAIN;
  36. ret = -1;
  37. }
  38. alarm(old_alarm);
  39. sigaction(SIGALRM, &old_sigaction, NULL);
  40. }
  41. if ((ret == -1) && e) {
  42. return -e;
  43. }
  44. return ret;
  45. }

  至此,我们知道了logcat读取日志的流程,但是logdr的日志是由谁写入的呢,让我们接下来继续分析。在前面logd的初始化时,我们注意到创建了一个LogReader对象,其中存储了一个LogBuffer.

    

7.4.6 logd  LogReader

LogReader被创建后,会调用getLogSocket()来连接。"/dev/socket/logdr"这个socket。

  1. int LogReader::getLogSocket() {
  2. static const char socketName[] = "logdr";
  3. int sock = android_get_control_socket(socketName);
  4. if (sock < 0) {
  5. sock = socket_local_server(
  6. socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET);
  7. }
  8. return sock;
  9. }

   在 [7.3.5] 中,当有日志写入logdw时,LogListener()的onDataAvailable生效,先把日志写入LogBufer后,再LogReader的notifyNewLog()来通知有新的日志写入。

    当收到一个新的日志条目可用时,通知正在监视此条目的日志id的侦听socket,即我们可以进行读日志了。

  1. void LogReader::notifyNewLog(log_mask_t logMask) {
  2. // 创建一个FlushCommand 对象,传入LogReader的对象和logmask
  3. FlushCommand command(*this, logMask);
  4. //调用socket接口,最终进入 logd的runSocketCommand()
  5. runOnEachSocket(&command);
  6. }
  7. 运行FlushCommand 的runSocketCommand()
  8. void SocketListener::runOnEachSocket(SocketClientCommand *command) {
  9. SocketClientCollection safeList;
  10. ...
  11. while (!safeList.empty()) {
  12. ...
  13. command->runSocketCommand(c);
  14. ...
  15. }
  16. }

[FlushCommand.cpp] runSocketCommand()

说明:对日志读取器套接字上的每个打开的客户端调用一次runSocketCommand。主要有三个command:LogListener、LogAudit、LogKlog。

对日志reader socket上的每个打开一次客户端就调用一次runSocketCommand。

在这里,我们管理并关联reader-client的跟踪和日志区域,锁定logtimeentry的LastLogTimes列表,并产生一个临时的客户端线程来讲数据归档到socket。

全局LogTimeEntry::wrlock()用于保护访问,引用计数用于确保在不受保护时管理单个LogTimeEntry生存期。

源码:

  1. void FlushCommand::runSocketCommand(SocketClient* client) {
  2. LogTimeEntry* entry = nullptr;
  3. LastLogTimes& times = mReader.logbuf().mTimes;
  4. LogTimeEntry::wrlock();
  5. LastLogTimes::iterator it = times.begin();
  6. while (it != times.end()) {
  7. entry = it->get();
  8. if (entry->mClient == client) {
  9. if (!entry->isWatchingMultiple(mLogMask)) {
  10. LogTimeEntry::unlock();
  11. return;
  12. }
  13. if (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec) {
  14. if (mReader.logbuf().isMonotonic()) {
  15. LogTimeEntry::unlock();
  16. return;
  17. }
  18. // If the user changes the time in a gross manner that
  19. // invalidates the timeout, fall through and trigger.
  20. log_time now(CLOCK_REALTIME);
  21. if (((entry->mEnd + entry->mTimeout) > now) &&
  22. (now > entry->mEnd)) {
  23. LogTimeEntry::unlock();
  24. return;
  25. }
  26. }
  27. entry->triggerReader_Locked();
  28. LogTimeEntry::unlock();
  29. return;
  30. }
  31. it++;
  32. }
  33. LogTimeEntry::unlock();
  34. }

如果socket监听到数据,则执行onDataAvailable(),进入LogReader的onDataAvailable()

[LogReader.cpp] onDataAvailable()

说明:相应日志读操作,先读入logdr中传入的客户端参数,然后把之前LogBuffer中的日志通过flushto,最终通过socket的sendDatav()写给client,比如logcat,所以我们可以开启多个logcat来获取日志。

源码:

  1. bool LogReader::onDataAvailable(SocketClient* cli) {
  2. static bool name_set;
  3. //响应日志读操作
  4. if (!name_set) {
  5. prctl(PR_SET_NAME, "logd.reader");
  6. name_set = true;
  7. }
  8. char buffer[255];
  9. //读取客户端传入参数
  10. int len = read(cli->getSocket(), buffer, sizeof(buffer) - 1);
  11. if (len <= 0) {
  12. doSocketDelete(cli);
  13. return false;
  14. }
  15. buffer[len] = '\0';
  16. // Clients are only allowed to send one command, disconnect them if they
  17. // send another.
  18. //客户端只允许发送一个命令,如果它们发送另一个命令,则断开它们的连接
  19. LogTimeEntry::wrlock();
  20. for (const auto& entry : mLogbuf.mTimes) {
  21. if (entry->mClient == cli) {
  22. entry->release_Locked();
  23. LogTimeEntry::unlock();
  24. return false;
  25. }
  26. }
  27. LogTimeEntry::unlock();
  28. ...
  29. log_time sequence = start;
  30. ...
  31. if (nonBlock && (sequence != log_time::EPOCH) && timeout) {
  32. ..
  33. //LogBuffer中的日志写入传入的client,即写入logcat
  34. logbuf().flushTo(cli, sequence, nullptr, FlushCommand::hasReadLogs(cli),
  35. FlushCommand::hasSecurityLogs(cli),
  36. logFindStart.callback, &logFindStart);
  37. if (!logFindStart.found()) {
  38. doSocketDelete(cli);
  39. return false;
  40. }
  41. }
  42. ...
  43. LogTimeEntry::wrlock();
  44. ...
  45. setsockopt(cli->getSocket(), SOL_SOCKET, SO_SNDTIMEO, (const char*)&t,
  46. sizeof(t));
  47. LogTimeEntry::unlock();
  48. return true;
  49. }

至此日志的读取操作完成。下一节我们一起来看看<logd中如何进行selinux、kernel日志的读写>

微信公众号:IngresGe

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/621169
推荐阅读
相关标签
  

闽ICP备14008679号