xref: /aosp_15_r20/system/libbase/logging_splitters.h (revision 8f0ba417480079999ba552f1087ae592091b9d02)
1*8f0ba417SAndroid Build Coastguard Worker /*
2*8f0ba417SAndroid Build Coastguard Worker  * Copyright (C) 2020 The Android Open Source Project
3*8f0ba417SAndroid Build Coastguard Worker  *
4*8f0ba417SAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*8f0ba417SAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*8f0ba417SAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*8f0ba417SAndroid Build Coastguard Worker  *
8*8f0ba417SAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*8f0ba417SAndroid Build Coastguard Worker  *
10*8f0ba417SAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*8f0ba417SAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*8f0ba417SAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*8f0ba417SAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*8f0ba417SAndroid Build Coastguard Worker  * limitations under the License.
15*8f0ba417SAndroid Build Coastguard Worker  */
16*8f0ba417SAndroid Build Coastguard Worker 
17*8f0ba417SAndroid Build Coastguard Worker #pragma once
18*8f0ba417SAndroid Build Coastguard Worker 
19*8f0ba417SAndroid Build Coastguard Worker #include <inttypes.h>
20*8f0ba417SAndroid Build Coastguard Worker #include <time.h>
21*8f0ba417SAndroid Build Coastguard Worker 
22*8f0ba417SAndroid Build Coastguard Worker #include <android-base/logging.h>
23*8f0ba417SAndroid Build Coastguard Worker #include <android-base/stringprintf.h>
24*8f0ba417SAndroid Build Coastguard Worker 
25*8f0ba417SAndroid Build Coastguard Worker #define LOGGER_ENTRY_MAX_PAYLOAD 4068  // This constant is not in the NDK.
26*8f0ba417SAndroid Build Coastguard Worker 
27*8f0ba417SAndroid Build Coastguard Worker namespace android {
28*8f0ba417SAndroid Build Coastguard Worker namespace base {
29*8f0ba417SAndroid Build Coastguard Worker 
30*8f0ba417SAndroid Build Coastguard Worker // This splits the message up line by line, by calling log_function with a pointer to the start of
31*8f0ba417SAndroid Build Coastguard Worker // each line and the size up to the newline character.  It sends size = -1 for the final line.
32*8f0ba417SAndroid Build Coastguard Worker template <typename F, typename... Args>
SplitByLines(const char * msg,const F & log_function,Args &&...args)33*8f0ba417SAndroid Build Coastguard Worker static void SplitByLines(const char* msg, const F& log_function, Args&&... args) {
34*8f0ba417SAndroid Build Coastguard Worker   const char* newline = strchr(msg, '\n');
35*8f0ba417SAndroid Build Coastguard Worker   while (newline != nullptr) {
36*8f0ba417SAndroid Build Coastguard Worker     log_function(msg, newline - msg, args...);
37*8f0ba417SAndroid Build Coastguard Worker     msg = newline + 1;
38*8f0ba417SAndroid Build Coastguard Worker     newline = strchr(msg, '\n');
39*8f0ba417SAndroid Build Coastguard Worker   }
40*8f0ba417SAndroid Build Coastguard Worker 
41*8f0ba417SAndroid Build Coastguard Worker   log_function(msg, -1, args...);
42*8f0ba417SAndroid Build Coastguard Worker }
43*8f0ba417SAndroid Build Coastguard Worker 
44*8f0ba417SAndroid Build Coastguard Worker // This splits the message up into chunks that logs can process delimited by new lines.  It calls
45*8f0ba417SAndroid Build Coastguard Worker // log_function with the exact null terminated message that should be sent to logd.
46*8f0ba417SAndroid Build Coastguard Worker // Note, despite the loops and snprintf's, if severity is not fatal and there are no new lines,
47*8f0ba417SAndroid Build Coastguard Worker // this function simply calls log_function with msg without any extra overhead.
48*8f0ba417SAndroid Build Coastguard Worker template <typename F>
SplitByLogdChunks(LogId log_id,LogSeverity severity,const char * tag,const char * file,unsigned int line,const char * msg,const F & log_function)49*8f0ba417SAndroid Build Coastguard Worker static void SplitByLogdChunks(LogId log_id, LogSeverity severity, const char* tag, const char* file,
50*8f0ba417SAndroid Build Coastguard Worker                               unsigned int line, const char* msg, const F& log_function) {
51*8f0ba417SAndroid Build Coastguard Worker   // The maximum size of a payload, after the log header that logd will accept is
52*8f0ba417SAndroid Build Coastguard Worker   // LOGGER_ENTRY_MAX_PAYLOAD, so subtract the other elements in the payload to find the size of
53*8f0ba417SAndroid Build Coastguard Worker   // the string that we can log in each pass.
54*8f0ba417SAndroid Build Coastguard Worker   // The protocol is documented in liblog/README.protocol.md.
55*8f0ba417SAndroid Build Coastguard Worker   // Specifically we subtract a byte for the priority, the length of the tag + its null terminator,
56*8f0ba417SAndroid Build Coastguard Worker   // and an additional byte for the null terminator on the payload.  We subtract an additional 32
57*8f0ba417SAndroid Build Coastguard Worker   // bytes for slack, similar to java/android/util/Log.java.
58*8f0ba417SAndroid Build Coastguard Worker   ptrdiff_t max_size = LOGGER_ENTRY_MAX_PAYLOAD - strlen(tag) - 35;
59*8f0ba417SAndroid Build Coastguard Worker   if (max_size <= 0) {
60*8f0ba417SAndroid Build Coastguard Worker     abort();
61*8f0ba417SAndroid Build Coastguard Worker   }
62*8f0ba417SAndroid Build Coastguard Worker   // If we're logging a fatal message, we'll append the file and line numbers.
63*8f0ba417SAndroid Build Coastguard Worker   bool add_file = file != nullptr && (severity == FATAL || severity == FATAL_WITHOUT_ABORT);
64*8f0ba417SAndroid Build Coastguard Worker 
65*8f0ba417SAndroid Build Coastguard Worker   std::string file_header;
66*8f0ba417SAndroid Build Coastguard Worker   if (add_file) {
67*8f0ba417SAndroid Build Coastguard Worker     file_header = StringPrintf("%s:%u] ", file, line);
68*8f0ba417SAndroid Build Coastguard Worker   }
69*8f0ba417SAndroid Build Coastguard Worker   int file_header_size = file_header.size();
70*8f0ba417SAndroid Build Coastguard Worker 
71*8f0ba417SAndroid Build Coastguard Worker   __attribute__((uninitialized)) char logd_chunk[max_size + 1];
72*8f0ba417SAndroid Build Coastguard Worker   ptrdiff_t chunk_position = 0;
73*8f0ba417SAndroid Build Coastguard Worker 
74*8f0ba417SAndroid Build Coastguard Worker   auto call_log_function = [&]() {
75*8f0ba417SAndroid Build Coastguard Worker     log_function(log_id, severity, tag, logd_chunk);
76*8f0ba417SAndroid Build Coastguard Worker     chunk_position = 0;
77*8f0ba417SAndroid Build Coastguard Worker   };
78*8f0ba417SAndroid Build Coastguard Worker 
79*8f0ba417SAndroid Build Coastguard Worker   auto write_to_logd_chunk = [&](const char* message, int length) {
80*8f0ba417SAndroid Build Coastguard Worker     int size_written = 0;
81*8f0ba417SAndroid Build Coastguard Worker     const char* new_line = chunk_position > 0 ? "\n" : "";
82*8f0ba417SAndroid Build Coastguard Worker     if (add_file) {
83*8f0ba417SAndroid Build Coastguard Worker       size_written = snprintf(logd_chunk + chunk_position, sizeof(logd_chunk) - chunk_position,
84*8f0ba417SAndroid Build Coastguard Worker                               "%s%s%.*s", new_line, file_header.c_str(), length, message);
85*8f0ba417SAndroid Build Coastguard Worker     } else {
86*8f0ba417SAndroid Build Coastguard Worker       size_written = snprintf(logd_chunk + chunk_position, sizeof(logd_chunk) - chunk_position,
87*8f0ba417SAndroid Build Coastguard Worker                               "%s%.*s", new_line, length, message);
88*8f0ba417SAndroid Build Coastguard Worker     }
89*8f0ba417SAndroid Build Coastguard Worker 
90*8f0ba417SAndroid Build Coastguard Worker     // This should never fail, if it does and we set size_written to 0, which will skip this line
91*8f0ba417SAndroid Build Coastguard Worker     // and move to the next one.
92*8f0ba417SAndroid Build Coastguard Worker     if (size_written < 0) {
93*8f0ba417SAndroid Build Coastguard Worker       size_written = 0;
94*8f0ba417SAndroid Build Coastguard Worker     }
95*8f0ba417SAndroid Build Coastguard Worker     chunk_position += size_written;
96*8f0ba417SAndroid Build Coastguard Worker   };
97*8f0ba417SAndroid Build Coastguard Worker 
98*8f0ba417SAndroid Build Coastguard Worker   const char* newline = strchr(msg, '\n');
99*8f0ba417SAndroid Build Coastguard Worker   while (newline != nullptr) {
100*8f0ba417SAndroid Build Coastguard Worker     // If we have data in the buffer and this next line doesn't fit, write the buffer.
101*8f0ba417SAndroid Build Coastguard Worker     if (chunk_position != 0 && chunk_position + (newline - msg) + 1 + file_header_size > max_size) {
102*8f0ba417SAndroid Build Coastguard Worker       call_log_function();
103*8f0ba417SAndroid Build Coastguard Worker     }
104*8f0ba417SAndroid Build Coastguard Worker 
105*8f0ba417SAndroid Build Coastguard Worker     // Otherwise, either the next line fits or we have any empty buffer and too large of a line to
106*8f0ba417SAndroid Build Coastguard Worker     // ever fit, in both cases, we add it to the buffer and continue.
107*8f0ba417SAndroid Build Coastguard Worker     write_to_logd_chunk(msg, newline - msg);
108*8f0ba417SAndroid Build Coastguard Worker 
109*8f0ba417SAndroid Build Coastguard Worker     msg = newline + 1;
110*8f0ba417SAndroid Build Coastguard Worker     newline = strchr(msg, '\n');
111*8f0ba417SAndroid Build Coastguard Worker   }
112*8f0ba417SAndroid Build Coastguard Worker 
113*8f0ba417SAndroid Build Coastguard Worker   // If we have left over data in the buffer and we can fit the rest of msg, add it to the buffer
114*8f0ba417SAndroid Build Coastguard Worker   // then write the buffer.
115*8f0ba417SAndroid Build Coastguard Worker   if (chunk_position != 0 &&
116*8f0ba417SAndroid Build Coastguard Worker       chunk_position + static_cast<int>(strlen(msg)) + 1 + file_header_size <= max_size) {
117*8f0ba417SAndroid Build Coastguard Worker     write_to_logd_chunk(msg, -1);
118*8f0ba417SAndroid Build Coastguard Worker     call_log_function();
119*8f0ba417SAndroid Build Coastguard Worker   } else {
120*8f0ba417SAndroid Build Coastguard Worker     // If the buffer is not empty and we can't fit the rest of msg into it, write its contents.
121*8f0ba417SAndroid Build Coastguard Worker     if (chunk_position != 0) {
122*8f0ba417SAndroid Build Coastguard Worker       call_log_function();
123*8f0ba417SAndroid Build Coastguard Worker     }
124*8f0ba417SAndroid Build Coastguard Worker     // Then write the rest of the msg.
125*8f0ba417SAndroid Build Coastguard Worker     if (add_file) {
126*8f0ba417SAndroid Build Coastguard Worker       snprintf(logd_chunk, sizeof(logd_chunk), "%s%s", file_header.c_str(), msg);
127*8f0ba417SAndroid Build Coastguard Worker       log_function(log_id, severity, tag, logd_chunk);
128*8f0ba417SAndroid Build Coastguard Worker     } else {
129*8f0ba417SAndroid Build Coastguard Worker       log_function(log_id, severity, tag, msg);
130*8f0ba417SAndroid Build Coastguard Worker     }
131*8f0ba417SAndroid Build Coastguard Worker   }
132*8f0ba417SAndroid Build Coastguard Worker }
133*8f0ba417SAndroid Build Coastguard Worker 
CountSizeAndNewLines(const char * message)134*8f0ba417SAndroid Build Coastguard Worker static std::pair<int, int> CountSizeAndNewLines(const char* message) {
135*8f0ba417SAndroid Build Coastguard Worker   int size = 0;
136*8f0ba417SAndroid Build Coastguard Worker   int new_lines = 0;
137*8f0ba417SAndroid Build Coastguard Worker   while (*message != '\0') {
138*8f0ba417SAndroid Build Coastguard Worker     size++;
139*8f0ba417SAndroid Build Coastguard Worker     if (*message == '\n') {
140*8f0ba417SAndroid Build Coastguard Worker       ++new_lines;
141*8f0ba417SAndroid Build Coastguard Worker     }
142*8f0ba417SAndroid Build Coastguard Worker     ++message;
143*8f0ba417SAndroid Build Coastguard Worker   }
144*8f0ba417SAndroid Build Coastguard Worker   return {size, new_lines};
145*8f0ba417SAndroid Build Coastguard Worker }
146*8f0ba417SAndroid Build Coastguard Worker 
147*8f0ba417SAndroid Build Coastguard Worker // This adds the log header to each line of message and returns it as a string intended to be
148*8f0ba417SAndroid Build Coastguard Worker // written to stderr.
StderrOutputGenerator(const struct timespec & ts,int pid,uint64_t tid,LogSeverity severity,const char * tag,const char * file,unsigned int line,const char * message)149*8f0ba417SAndroid Build Coastguard Worker static std::string StderrOutputGenerator(const struct timespec& ts, int pid, uint64_t tid,
150*8f0ba417SAndroid Build Coastguard Worker                                          LogSeverity severity, const char* tag, const char* file,
151*8f0ba417SAndroid Build Coastguard Worker                                          unsigned int line, const char* message) {
152*8f0ba417SAndroid Build Coastguard Worker   struct tm now;
153*8f0ba417SAndroid Build Coastguard Worker   localtime_r(&ts.tv_sec, &now);
154*8f0ba417SAndroid Build Coastguard Worker   char timestamp[sizeof("mm-DD HH:MM:SS.mmm\0")];
155*8f0ba417SAndroid Build Coastguard Worker   size_t n = strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
156*8f0ba417SAndroid Build Coastguard Worker   snprintf(timestamp + n, sizeof(timestamp) - n, ".%03ld", ts.tv_nsec / (1000 * 1000));
157*8f0ba417SAndroid Build Coastguard Worker 
158*8f0ba417SAndroid Build Coastguard Worker   static const char log_characters[] = "VDIWEFF";
159*8f0ba417SAndroid Build Coastguard Worker   static_assert(arraysize(log_characters) - 1 == FATAL + 1,
160*8f0ba417SAndroid Build Coastguard Worker                 "Mismatch in size of log_characters and values in LogSeverity");
161*8f0ba417SAndroid Build Coastguard Worker   char severity_char = log_characters[severity];
162*8f0ba417SAndroid Build Coastguard Worker   std::string line_prefix;
163*8f0ba417SAndroid Build Coastguard Worker   const char* real_tag = tag ? tag : "nullptr";
164*8f0ba417SAndroid Build Coastguard Worker   if (file != nullptr) {
165*8f0ba417SAndroid Build Coastguard Worker     line_prefix = StringPrintf("%s %5d %5" PRIu64 " %c %-8s: %s:%u ", timestamp, pid, tid,
166*8f0ba417SAndroid Build Coastguard Worker                                severity_char, real_tag, file, line);
167*8f0ba417SAndroid Build Coastguard Worker   } else {
168*8f0ba417SAndroid Build Coastguard Worker     line_prefix =
169*8f0ba417SAndroid Build Coastguard Worker         StringPrintf("%s %5d %5" PRIu64 " %c %-8s: ", timestamp, pid, tid, severity_char, real_tag);
170*8f0ba417SAndroid Build Coastguard Worker   }
171*8f0ba417SAndroid Build Coastguard Worker 
172*8f0ba417SAndroid Build Coastguard Worker   auto [size, new_lines] = CountSizeAndNewLines(message);
173*8f0ba417SAndroid Build Coastguard Worker   std::string output_string;
174*8f0ba417SAndroid Build Coastguard Worker   output_string.reserve(size + new_lines * line_prefix.size() + 1);
175*8f0ba417SAndroid Build Coastguard Worker 
176*8f0ba417SAndroid Build Coastguard Worker   auto concat_lines = [&](const char* message, int size) {
177*8f0ba417SAndroid Build Coastguard Worker     output_string.append(line_prefix);
178*8f0ba417SAndroid Build Coastguard Worker     if (size == -1) {
179*8f0ba417SAndroid Build Coastguard Worker       output_string.append(message);
180*8f0ba417SAndroid Build Coastguard Worker     } else {
181*8f0ba417SAndroid Build Coastguard Worker       output_string.append(message, size);
182*8f0ba417SAndroid Build Coastguard Worker     }
183*8f0ba417SAndroid Build Coastguard Worker     output_string.append("\n");
184*8f0ba417SAndroid Build Coastguard Worker   };
185*8f0ba417SAndroid Build Coastguard Worker   SplitByLines(message, concat_lines);
186*8f0ba417SAndroid Build Coastguard Worker   return output_string;
187*8f0ba417SAndroid Build Coastguard Worker }
188*8f0ba417SAndroid Build Coastguard Worker 
189*8f0ba417SAndroid Build Coastguard Worker }  // namespace base
190*8f0ba417SAndroid Build Coastguard Worker }  // namespace android
191