1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "logging.h"
18 
19 #include <iostream>
20 #include <limits>
21 #include <sstream>
22 
23 #include "aborting.h"
24 #include "os.h"
25 #include "unix_file/fd_file.h"
26 
27 // Headers for LogMessage::LogLine.
28 #ifdef ART_TARGET_ANDROID
29 #include <log/log.h>
30 #else
31 #include <sys/types.h>
32 #include <unistd.h>
33 #endif
34 
35 namespace art {
36 
37 LogVerbosity gLogVerbosity;
38 
39 std::atomic<unsigned int> gAborting(0);
40 
41 static std::unique_ptr<std::string> gCmdLine;
42 static std::unique_ptr<std::string> gProgramInvocationName;
43 static std::unique_ptr<std::string> gProgramInvocationShortName;
44 
GetCmdLine()45 const char* GetCmdLine() {
46   return (gCmdLine.get() != nullptr) ? gCmdLine->c_str() : nullptr;
47 }
48 
ProgramInvocationName()49 const char* ProgramInvocationName() {
50   return (gProgramInvocationName.get() != nullptr) ? gProgramInvocationName->c_str() : "art";
51 }
52 
ProgramInvocationShortName()53 const char* ProgramInvocationShortName() {
54   return (gProgramInvocationShortName.get() != nullptr) ? gProgramInvocationShortName->c_str()
55                                                         : "art";
56 }
57 
InitLogging(char * argv[],AbortFunction & abort_function)58 void InitLogging(char* argv[], AbortFunction& abort_function) {
59   if (gCmdLine.get() != nullptr) {
60     return;
61   }
62 
63   // Stash the command line for later use. We can use /proc/self/cmdline on Linux to recover this,
64   // but we don't have that luxury on the Mac, and there are a couple of argv[0] variants that are
65   // commonly used.
66   if (argv != nullptr) {
67     gCmdLine.reset(new std::string(argv[0]));
68     for (size_t i = 1; argv[i] != nullptr; ++i) {
69       gCmdLine->append(" ");
70       gCmdLine->append(argv[i]);
71     }
72     gProgramInvocationName.reset(new std::string(argv[0]));
73     const char* last_slash = strrchr(argv[0], '/');
74     gProgramInvocationShortName.reset(new std::string((last_slash != nullptr) ? last_slash + 1
75                                                                            : argv[0]));
76   } else {
77     // TODO: fall back to /proc/self/cmdline when argv is null on Linux.
78     gCmdLine.reset(new std::string("<unset>"));
79   }
80 
81 #ifdef ART_TARGET_ANDROID
82 #define INIT_LOGGING_DEFAULT_LOGGER android::base::LogdLogger()
83 #else
84 #define INIT_LOGGING_DEFAULT_LOGGER android::base::StderrLogger
85 #endif
86   android::base::InitLogging(argv, INIT_LOGGING_DEFAULT_LOGGER,
87                              std::move<AbortFunction>(abort_function));
88 #undef INIT_LOGGING_DEFAULT_LOGGER
89 }
90 
91 #ifdef ART_TARGET_ANDROID
92 static const android_LogPriority kLogSeverityToAndroidLogPriority[] = {
93   ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN,
94   ANDROID_LOG_ERROR, ANDROID_LOG_FATAL, ANDROID_LOG_FATAL
95 };
96 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == ::android::base::FATAL + 1,
97               "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
98 #endif
99 
LogLineLowStack(const char * file,unsigned int line,LogSeverity log_severity,const char * message)100 void LogHelper::LogLineLowStack(const char* file,
101                                 unsigned int line,
102                                 LogSeverity log_severity,
103                                 const char* message) {
104 #ifdef ART_TARGET_ANDROID
105   // Use android_writeLog() to avoid stack-based buffers used by android_printLog().
106   const char* tag = ProgramInvocationShortName();
107   int priority = kLogSeverityToAndroidLogPriority[static_cast<size_t>(log_severity)];
108   char* buf = nullptr;
109   size_t buf_size = 0u;
110   if (priority == ANDROID_LOG_FATAL) {
111     // Allocate buffer for snprintf(buf, buf_size, "%s:%u] %s", file, line, message) below.
112     // If allocation fails, fall back to printing only the message.
113     buf_size = strlen(file) + 1 /* ':' */ + std::numeric_limits<decltype(line)>::max_digits10 +
114         2 /* "] " */ + strlen(message) + 1 /* terminating 0 */;
115     buf = reinterpret_cast<char*>(malloc(buf_size));
116   }
117   if (buf != nullptr) {
118     snprintf(buf, buf_size, "%s:%u] %s", file, line, message);
119     android_writeLog(priority, tag, buf);
120     free(buf);
121   } else {
122     android_writeLog(priority, tag, message);
123   }
124 #else
125   static constexpr char kLogCharacters[] = { 'V', 'D', 'I', 'W', 'E', 'F', 'F' };
126   static_assert(
127       arraysize(kLogCharacters) == static_cast<size_t>(::android::base::FATAL) + 1,
128       "Wrong character array size");
129 
130   const char* program_name = ProgramInvocationShortName();
131   TEMP_FAILURE_RETRY(write(STDERR_FILENO, program_name, strlen(program_name)));
132   TEMP_FAILURE_RETRY(write(STDERR_FILENO, " ", 1));
133   TEMP_FAILURE_RETRY(write(STDERR_FILENO, &kLogCharacters[static_cast<size_t>(log_severity)], 1));
134   TEMP_FAILURE_RETRY(write(STDERR_FILENO, " ", 1));
135   // TODO: pid and tid.
136   TEMP_FAILURE_RETRY(write(STDERR_FILENO, file, strlen(file)));
137   // TODO: line.
138   UNUSED(line);
139   TEMP_FAILURE_RETRY(write(STDERR_FILENO, "] ", 2));
140   TEMP_FAILURE_RETRY(write(STDERR_FILENO, message, strlen(message)));
141   TEMP_FAILURE_RETRY(write(STDERR_FILENO, "\n", 1));
142 #endif  // ART_TARGET_ANDROID
143 }
144 
PrintFileToLog(const std::string & file_name,android::base::LogSeverity level)145 bool PrintFileToLog(const std::string& file_name, android::base::LogSeverity level) {
146   File file(file_name, O_RDONLY, false);
147   if (!file.IsOpened()) {
148     return false;
149   }
150 
151   constexpr size_t kBufSize = 256;  // Small buffer. Avoid stack overflow and stack size warnings.
152   char buf[kBufSize + 1];           // +1 for terminator.
153   size_t filled_to = 0;
154   while (true) {
155     DCHECK_LT(filled_to, kBufSize);
156     int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
157     if (n <= 0) {
158       // Print the rest of the buffer, if it exists.
159       if (filled_to > 0) {
160         buf[filled_to] = 0;
161         LOG(level) << buf;
162       }
163       return n == 0;
164     }
165     // Scan for '\n'.
166     size_t i = filled_to;
167     bool found_newline = false;
168     for (; i < filled_to + n; ++i) {
169       if (buf[i] == '\n') {
170         // Found a line break, that's something to print now.
171         buf[i] = 0;
172         LOG(level) << buf;
173         // Copy the rest to the front.
174         if (i + 1 < filled_to + n) {
175           memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
176           filled_to = filled_to + n - i - 1;
177         } else {
178           filled_to = 0;
179         }
180         found_newline = true;
181         break;
182       }
183     }
184     if (found_newline) {
185       continue;
186     } else {
187       filled_to += n;
188       // Check if we must flush now.
189       if (filled_to == kBufSize) {
190         buf[kBufSize] = 0;
191         LOG(level) << buf;
192         filled_to = 0;
193       }
194     }
195   }
196 }
197 
198 }  // namespace art
199