1 /*
2  * Copyright (C) 2008 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 "bootchart.h"
18 
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/utsname.h>
26 #include <time.h>
27 #include <unistd.h>
28 
29 #include <chrono>
30 #include <condition_variable>
31 #include <memory>
32 #include <mutex>
33 #include <thread>
34 
35 #include <android-base/chrono_utils.h>
36 #include <android-base/file.h>
37 #include <android-base/logging.h>
38 #include <android-base/properties.h>
39 #include <android-base/stringprintf.h>
40 
41 using android::base::StringPrintf;
42 using android::base::boot_clock;
43 using namespace std::chrono_literals;
44 
45 namespace android {
46 namespace init {
47 
48 static std::thread* g_bootcharting_thread;
49 
50 static std::mutex g_bootcharting_finished_mutex;
51 static std::condition_variable g_bootcharting_finished_cv;
52 static bool g_bootcharting_finished;
53 
get_uptime_jiffies()54 static long long get_uptime_jiffies() {
55     constexpr int64_t kNanosecondsPerJiffy = 10000000;
56     boot_clock::time_point uptime = boot_clock::now();
57     return uptime.time_since_epoch().count() / kNanosecondsPerJiffy;
58 }
59 
fopen_unique(const char * filename,const char * mode)60 static std::unique_ptr<FILE, decltype(&fclose)> fopen_unique(const char* filename,
61                                                              const char* mode) {
62   std::unique_ptr<FILE, decltype(&fclose)> result(fopen(filename, mode), fclose);
63   if (!result) PLOG(ERROR) << "bootchart: failed to open " << filename;
64   return result;
65 }
66 
log_header()67 static void log_header() {
68   char date[32];
69   time_t now_t = time(NULL);
70   struct tm now = *localtime(&now_t);
71   strftime(date, sizeof(date), "%F %T", &now);
72 
73   utsname uts;
74   if (uname(&uts) == -1) return;
75 
76   std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "");
77   if (fingerprint.empty()) return;
78 
79   std::string kernel_cmdline;
80   android::base::ReadFileToString("/proc/cmdline", &kernel_cmdline);
81 
82   auto fp = fopen_unique("/data/bootchart/header", "we");
83   if (!fp) return;
84   fprintf(&*fp, "version = Android init 0.8\n");
85   fprintf(&*fp, "title = Boot chart for Android (%s)\n", date);
86   fprintf(&*fp, "system.uname = %s %s %s %s\n", uts.sysname, uts.release, uts.version, uts.machine);
87   fprintf(&*fp, "system.release = %s\n", fingerprint.c_str());
88   // TODO: use /proc/cpuinfo "model name" line for x86, "Processor" line for arm.
89   fprintf(&*fp, "system.cpu = %s\n", uts.machine);
90   fprintf(&*fp, "system.kernel.options = %s\n", kernel_cmdline.c_str());
91 }
92 
log_uptime(FILE * log)93 static void log_uptime(FILE* log) {
94   fprintf(log, "%lld\n", get_uptime_jiffies());
95 }
96 
log_file(FILE * log,const char * procfile)97 static void log_file(FILE* log, const char* procfile) {
98   log_uptime(log);
99 
100   std::string content;
101   if (android::base::ReadFileToString(procfile, &content)) {
102     fprintf(log, "%s\n", content.c_str());
103   }
104 }
105 
log_processes(FILE * log)106 static void log_processes(FILE* log) {
107   log_uptime(log);
108 
109   std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir("/proc"), closedir);
110   struct dirent* entry;
111   while ((entry = readdir(dir.get())) != NULL) {
112     // Only match numeric values.
113     int pid = atoi(entry->d_name);
114     if (pid == 0) continue;
115 
116     // /proc/<pid>/stat only has truncated task names, so get the full
117     // name from /proc/<pid>/cmdline.
118     std::string cmdline;
119     android::base::ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &cmdline);
120     const char* full_name = cmdline.c_str(); // So we stop at the first NUL.
121 
122     // Read process stat line.
123     std::string stat;
124     if (android::base::ReadFileToString(StringPrintf("/proc/%d/stat", pid), &stat)) {
125       if (!cmdline.empty()) {
126         // Substitute the process name with its real name.
127         size_t open = stat.find('(');
128         size_t close = stat.find_last_of(')');
129         if (open != std::string::npos && close != std::string::npos) {
130           stat.replace(open + 1, close - open - 1, full_name);
131         }
132       }
133       fputs(stat.c_str(), log);
134     }
135   }
136 
137   fputc('\n', log);
138 }
139 
bootchart_thread_main()140 static void bootchart_thread_main() {
141   LOG(INFO) << "Bootcharting started";
142 
143   // Open log files.
144   auto stat_log = fopen_unique("/data/bootchart/proc_stat.log", "we");
145   if (!stat_log) return;
146   auto proc_log = fopen_unique("/data/bootchart/proc_ps.log", "we");
147   if (!proc_log) return;
148   auto disk_log = fopen_unique("/data/bootchart/proc_diskstats.log", "we");
149   if (!disk_log) return;
150 
151   log_header();
152 
153   while (true) {
154     {
155       std::unique_lock<std::mutex> lock(g_bootcharting_finished_mutex);
156       g_bootcharting_finished_cv.wait_for(lock, 200ms);
157       if (g_bootcharting_finished) break;
158     }
159 
160     log_file(&*stat_log, "/proc/stat");
161     log_file(&*disk_log, "/proc/diskstats");
162     log_processes(&*proc_log);
163   }
164 
165   LOG(INFO) << "Bootcharting finished";
166 }
167 
do_bootchart_start()168 static Result<void> do_bootchart_start() {
169     // We don't care about the content, but we do care that /data/bootchart/enabled actually exists.
170     std::string start;
171     if (!android::base::ReadFileToString("/data/bootchart/enabled", &start)) {
172         LOG(VERBOSE) << "Not bootcharting";
173         return {};
174     }
175 
176     g_bootcharting_thread = new std::thread(bootchart_thread_main);
177     return {};
178 }
179 
do_bootchart_stop()180 static Result<void> do_bootchart_stop() {
181     if (!g_bootcharting_thread) return {};
182 
183     // Tell the worker thread it's time to quit.
184     {
185         std::lock_guard<std::mutex> lock(g_bootcharting_finished_mutex);
186         g_bootcharting_finished = true;
187         g_bootcharting_finished_cv.notify_one();
188     }
189 
190     g_bootcharting_thread->join();
191     delete g_bootcharting_thread;
192     g_bootcharting_thread = nullptr;
193     return {};
194 }
195 
do_bootchart(const BuiltinArguments & args)196 Result<void> do_bootchart(const BuiltinArguments& args) {
197     if (args[1] == "start") return do_bootchart_start();
198     return do_bootchart_stop();
199 }
200 
201 }  // namespace init
202 }  // namespace android
203