• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 // The bootstat command provides options to persist boot events with the current
18 // timestamp, dump the persisted events, and log all events to EventLog to be
19 // uploaded to Android log storage via Tron.
20 
21 #include <getopt.h>
22 #include <sys/klog.h>
23 #include <unistd.h>
24 
25 #include <chrono>
26 #include <cmath>
27 #include <cstddef>
28 #include <cstdio>
29 #include <ctime>
30 #include <iterator>
31 #include <map>
32 #include <memory>
33 #include <regex>
34 #include <string>
35 #include <string_view>
36 #include <unordered_map>
37 #include <utility>
38 #include <vector>
39 
40 #include <android-base/chrono_utils.h>
41 #include <android-base/file.h>
42 #include <android-base/logging.h>
43 #include <android-base/parseint.h>
44 #include <android-base/properties.h>
45 #include <android-base/strings.h>
46 #include <android/log.h>
47 #include <cutils/android_reboot.h>
48 #include <cutils/properties.h>
49 #include <statslog.h>
50 
51 #include "boot_event_record_store.h"
52 
53 namespace {
54 
55 struct AtomInfo {
56   int32_t atom;
57   int32_t event;
58 };
59 
60 // Maps BootEvent used inside bootstat into statsd atom defined in
61 // frameworks/base/cmds/statsd/src/atoms.proto.
62 const std::unordered_map<std::string_view, AtomInfo> kBootEventToAtomInfo = {
63     // ELAPSED_TIME
64     {"ro.boottime.init",
65      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
66       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ANDROID_INIT_STAGE_1}},
67     {"boot_complete",
68      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
69       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE}},
70     {"boot_decryption_complete",
71      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
72       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_ENCRYPTION}},
73     {"boot_complete_no_encryption",
74      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
75       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_NO_ENCRYPTION}},
76     {"boot_complete_post_decrypt",
77      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
78       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_POST_DECRYPT}},
79     {"factory_reset_boot_complete",
80      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
81       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE}},
82     {"factory_reset_boot_complete_no_encryption",
83      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
84       android::util::
85           BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE_NO_ENCRYPTION}},
86     {"factory_reset_boot_complete_post_decrypt",
87      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
88       android::util::
89           BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE_POST_DECRYPT}},
90     {"ota_boot_complete",
91      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
92       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE}},
93     {"ota_boot_complete_no_encryption",
94      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
95       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE_NO_ENCRYPTION}},
96     {"ota_boot_complete_post_decrypt",
97      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
98       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE_POST_DECRYPT}},
99     {"post_decrypt_time_elapsed",
100      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
101       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__POST_DECRYPT}},
102     // DURATION
103     {"absolute_boot_time",
104      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
105       android::util::BOOT_TIME_EVENT_DURATION__EVENT__ABSOLUTE_BOOT_TIME}},
106     {"boottime.bootloader.1BLE",
107      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
108       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_FIRST_STAGE_EXEC}},
109     {"boottime.bootloader.1BLL",
110      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
111       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_FIRST_STAGE_LOAD}},
112     {"boottime.bootloader.KL",
113      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
114       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_KERNEL_LOAD}},
115     {"boottime.bootloader.2BLE",
116      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
117       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_SECOND_STAGE_EXEC}},
118     {"boottime.bootloader.2BLL",
119      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
120       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_SECOND_STAGE_LOAD}},
121     {"boottime.bootloader.SW",
122      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
123       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_UI_WAIT}},
124     {"boottime.bootloader.total",
125      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
126       android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_TOTAL}},
127     {"boottime.init.cold_boot_wait",
128      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
129       android::util::BOOT_TIME_EVENT_DURATION__EVENT__COLDBOOT_WAIT}},
130     {"time_since_factory_reset",
131      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
132       android::util::BOOT_TIME_EVENT_DURATION__EVENT__FACTORY_RESET_TIME_SINCE_RESET}},
133     {"ro.boottime.init.first_stage",
134      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
135       android::util::BOOT_TIME_EVENT_DURATION__EVENT__ANDROID_INIT_STAGE_1}},
136     {"ro.boottime.init.selinux",
137      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
138       android::util::BOOT_TIME_EVENT_DURATION__EVENT__SELINUX_INIT}},
139     // UTC_TIME
140     {"factory_reset",
141      {android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED,
142       android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RESET_TIME}},
143     {"factory_reset_current_time",
144      {android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED,
145       android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_CURRENT_TIME}},
146     {"factory_reset_record_value",
147      {android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED,
148       android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RECORD_VALUE}},
149     // ERROR_CODE
150     {"factory_reset_current_time_failure",
151      {android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED,
152       android::util::BOOT_TIME_EVENT_ERROR_CODE__EVENT__FACTORY_RESET_CURRENT_TIME_FAILURE}},
153 };
154 
155 // Scans the boot event record store for record files and logs each boot event
156 // via EventLog.
LogBootEvents()157 void LogBootEvents() {
158   BootEventRecordStore boot_event_store;
159   auto events = boot_event_store.GetAllBootEvents();
160   std::vector<std::string_view> notSupportedEvents;
161   for (const auto& event : events) {
162     const auto& name = event.first;
163     const auto& info = kBootEventToAtomInfo.find(name);
164     if (info != kBootEventToAtomInfo.end()) {
165       if (info->second.atom == android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED) {
166         android::util::stats_write(static_cast<int32_t>(info->second.atom),
167                                    static_cast<int32_t>(info->second.event),
168                                    static_cast<int32_t>(event.second));
169       } else {
170         android::util::stats_write(static_cast<int32_t>(info->second.atom),
171                                    static_cast<int32_t>(info->second.event),
172                                    static_cast<int64_t>(event.second));
173       }
174     } else {
175       notSupportedEvents.push_back(name);
176     }
177   }
178   if (!notSupportedEvents.empty()) {
179     LOG(WARNING) << "LogBootEvents, atomInfo not defined for events:"
180                  << android::base::Join(notSupportedEvents, ',');
181   }
182 }
183 
184 // Records the named boot |event| to the record store. If |value| is non-empty
185 // and is a proper string representation of an integer value, the converted
186 // integer value is associated with the boot event.
RecordBootEventFromCommandLine(const std::string & event,const std::string & value_str)187 void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
188   BootEventRecordStore boot_event_store;
189   if (!value_str.empty()) {
190     int32_t value = 0;
191     if (android::base::ParseInt(value_str, &value)) {
192       boot_event_store.AddBootEventWithValue(event, value);
193     }
194   } else {
195     boot_event_store.AddBootEvent(event);
196   }
197 }
198 
PrintBootEvents()199 void PrintBootEvents() {
200   printf("Boot events:\n");
201   printf("------------\n");
202 
203   BootEventRecordStore boot_event_store;
204   auto events = boot_event_store.GetAllBootEvents();
205   for (auto i = events.cbegin(); i != events.cend(); ++i) {
206     printf("%s\t%d\n", i->first.c_str(), i->second);
207   }
208 }
209 
ShowHelp(const char * cmd)210 void ShowHelp(const char* cmd) {
211   fprintf(stderr, "Usage: %s [options]...\n", cmd);
212   fprintf(stderr,
213           "options include:\n"
214           "  -h, --help              Show this help\n"
215           "  -l, --log               Log all metrics to logstorage\n"
216           "  -p, --print             Dump the boot event records to the console\n"
217           "  -r, --record            Record the timestamp of a named boot event\n"
218           "  --value                 Optional value to associate with the boot event\n"
219           "  --record_boot_complete  Record metrics related to the time for the device boot\n"
220           "  --record_boot_reason    Record the reason why the device booted\n"
221           "  --record_time_since_factory_reset  Record the time since the device was reset\n"
222           "  --boot_reason_enum=<reason>  Report the match to the kBootReasonMap table\n");
223 }
224 
225 // Constructs a readable, printable string from the givencommand line
226 // arguments.
GetCommandLine(int argc,char ** argv)227 std::string GetCommandLine(int argc, char** argv) {
228   std::string cmd;
229   for (int i = 0; i < argc; ++i) {
230     cmd += argv[i];
231     cmd += " ";
232   }
233 
234   return cmd;
235 }
236 
237 constexpr int32_t kEmptyBootReason = 0;
238 constexpr int32_t kUnknownBootReason = 1;
239 
240 // A mapping from boot reason string, as read from the ro.boot.bootreason
241 // system property, to a unique integer ID. Viewers of log data dashboards for
242 // the boot_reason metric may refer to this mapping to discern the histogram
243 // values.  Regex matching, to manage the scale, as a minimum require either
244 // [, \ or * to be present in the string to switch to checking.
245 const std::map<std::string, int32_t> kBootReasonMap = {
246     {"reboot,[empty]", kEmptyBootReason},
247     {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
248     {"normal", 2},
249     {"recovery", 3},
250     {"reboot", 4},
251     {"PowerKey", 5},
252     {"hard_reset", 6},
253     {"kernel_panic", 7},
254     {"rpm_err", 8},
255     {"hw_reset", 9},
256     {"tz_err", 10},
257     {"adsp_err", 11},
258     {"modem_err", 12},
259     {"mba_err", 13},
260     {"Watchdog", 14},
261     {"Panic", 15},
262     {"power_key", 16},  // aliasReasons to cold,powerkey (Mediatek)
263     {"power_on", 17},   // aliasReasons to cold,powerkey
264     {"Reboot", 18},
265     {"rtc", 19},
266     {"edl", 20},
267     {"oem_pon1", 21},
268     {"oem_powerkey", 22},  // aliasReasons to cold,powerkey
269     {"oem_unknown_reset", 23},
270     {"srto: HWWDT reset SC", 24},
271     {"srto: HWWDT reset platform", 25},
272     {"srto: bootloader", 26},
273     {"srto: kernel panic", 27},
274     {"srto: kernel watchdog reset", 28},
275     {"srto: normal", 29},
276     {"srto: reboot", 30},
277     {"srto: reboot-bootloader", 31},
278     {"srto: security watchdog reset", 32},
279     {"srto: wakesrc", 33},
280     {"srto: watchdog", 34},
281     {"srto:1-1", 35},
282     {"srto:omap_hsmm", 36},
283     {"srto:phy0", 37},
284     {"srto:rtc0", 38},
285     {"srto:touchpad", 39},
286     {"watchdog", 40},
287     {"watchdogr", 41},
288     {"wdog_bark", 42},
289     {"wdog_bite", 43},
290     {"wdog_reset", 44},
291     {"shutdown,", 45},  // Trailing comma is intentional. Do NOT use.
292     {"shutdown,userrequested", 46},
293     {"reboot,bootloader", 47},
294     {"reboot,cold", 48},
295     {"reboot,recovery", 49},
296     {"thermal_shutdown", 50},
297     {"s3_wakeup", 51},
298     {"kernel_panic,sysrq", 52},
299     {"kernel_panic,NULL", 53},
300     {"kernel_panic,null", 53},
301     {"kernel_panic,BUG", 54},
302     {"kernel_panic,bug", 54},
303     {"bootloader", 55},
304     {"cold", 56},
305     {"hard", 57},
306     {"warm", 58},
307     {"reboot,kernel_power_off_charging__reboot_system", 59},  // Can not happen
308     {"thermal-shutdown", 60},
309     {"shutdown,thermal", 61},
310     {"shutdown,battery", 62},
311     {"reboot,ota", 63},
312     {"reboot,factory_reset", 64},
313     {"reboot,", 65},
314     {"reboot,shell", 66},
315     {"reboot,adb", 67},
316     {"reboot,userrequested", 68},
317     {"shutdown,container", 69},  // Host OS asking Android Container to shutdown
318     {"cold,powerkey", 70},
319     {"warm,s3_wakeup", 71},
320     {"hard,hw_reset", 72},
321     {"shutdown,suspend", 73},    // Suspend to RAM
322     {"shutdown,hibernate", 74},  // Suspend to DISK
323     {"power_on_key", 75},        // aliasReasons to cold,powerkey
324     {"reboot_by_key", 76},       // translated to reboot,by_key
325     {"wdt_by_pass_pwk", 77},     // Mediatek
326     {"reboot_longkey", 78},      // translated to reboot,longkey
327     {"powerkey", 79},            // aliasReasons to cold,powerkey
328     {"usb", 80},                 // aliasReasons to cold,charger (Mediatek)
329     {"wdt", 81},                 // Mediatek
330     {"tool_by_pass_pwk", 82},    // aliasReasons to reboot,tool (Mediatek)
331     {"2sec_reboot", 83},         // aliasReasons to cold,rtc,2sec (Mediatek)
332     {"reboot,by_key", 84},
333     {"reboot,longkey", 85},
334     {"reboot,2sec", 86},  // Deprecate in two years, replaced with cold,rtc,2sec
335     {"shutdown,thermal,battery", 87},
336     {"reboot,its_just_so_hard", 88},  // produced by boot_reason_test
337     {"reboot,Its Just So Hard", 89},  // produced by boot_reason_test
338     {"reboot,rescueparty", 90},
339     {"charge", 91},
340     {"oem_tz_crash", 92},
341     {"uvlo", 93},  // aliasReasons to reboot,undervoltage
342     {"oem_ps_hold", 94},
343     {"abnormal_reset", 95},
344     {"oemerr_unknown", 96},
345     {"reboot_fastboot_mode", 97},
346     {"watchdog_apps_bite", 98},
347     {"xpu_err", 99},
348     {"power_on_usb", 100},  // aliasReasons to cold,charger
349     {"watchdog_rpm", 101},
350     {"watchdog_nonsec", 102},
351     {"watchdog_apps_bark", 103},
352     {"reboot_dmverity_corrupted", 104},
353     {"reboot_smpl", 105},  // aliasReasons to reboot,powerloss
354     {"watchdog_sdi_apps_reset", 106},
355     {"smpl", 107},  // aliasReasons to reboot,powerloss
356     {"oem_modem_failed_to_powerup", 108},
357     {"reboot_normal", 109},
358     {"oem_lpass_cfg", 110},
359     {"oem_xpu_ns_error", 111},
360     {"power_key_press", 112},  // aliasReasons to cold,powerkey
361     {"hardware_reset", 113},
362     {"reboot_by_powerkey", 114},  // aliasReasons to cold,powerkey (is this correct?)
363     {"reboot_verity", 115},
364     {"oem_rpm_undef_error", 116},
365     {"oem_crash_on_the_lk", 117},
366     {"oem_rpm_reset", 118},
367     {"reboot,powerloss", 119},
368     {"reboot,undervoltage", 120},
369     {"factory_cable", 121},
370     {"oem_ar6320_failed_to_powerup", 122},
371     {"watchdog_rpm_bite", 123},
372     {"power_on_cable", 124},  // aliasReasons to cold,charger
373     {"reboot_unknown", 125},
374     {"wireless_charger", 126},
375     {"0x776655ff", 127},
376     {"oem_thermal_bite_reset", 128},
377     {"charger", 129},
378     {"pon1", 130},
379     {"unknown", 131},
380     {"reboot_rtc", 132},
381     {"cold_boot", 133},
382     {"hard_rst", 134},
383     {"power-on", 135},
384     {"oem_adsp_resetting_the_soc", 136},
385     {"kpdpwr", 137},
386     {"oem_modem_timeout_waiting", 138},
387     {"usb_chg", 139},
388     {"warm_reset_0x02", 140},
389     {"warm_reset_0x80", 141},
390     {"pon_reason_0xb0", 142},
391     {"reboot_download", 143},
392     {"reboot_recovery_mode", 144},
393     {"oem_sdi_err_fatal", 145},
394     {"pmic_watchdog", 146},
395     {"software_master", 147},
396     {"cold,charger", 148},
397     {"cold,rtc", 149},
398     {"cold,rtc,2sec", 150},   // Mediatek
399     {"reboot,tool", 151},     // Mediatek
400     {"reboot,wdt", 152},      // Mediatek
401     {"reboot,unknown", 153},  // Mediatek
402     {"kernel_panic,audit", 154},
403     {"kernel_panic,atomic", 155},
404     {"kernel_panic,hung", 156},
405     {"kernel_panic,hung,rcu", 157},
406     {"kernel_panic,init", 158},
407     {"kernel_panic,oom", 159},
408     {"kernel_panic,stack", 160},
409     {"kernel_panic,sysrq,livelock,alarm", 161},   // llkd
410     {"kernel_panic,sysrq,livelock,driver", 162},  // llkd
411     {"kernel_panic,sysrq,livelock,zombie", 163},  // llkd
412     {"kernel_panic,modem", 164},
413     {"kernel_panic,adsp", 165},
414     {"kernel_panic,dsps", 166},
415     {"kernel_panic,wcnss", 167},
416     {"kernel_panic,_sde_encoder_phys_cmd_handle_ppdone_timeout", 168},
417     {"recovery,quiescent", 169},
418     {"reboot,quiescent", 170},
419     {"reboot,rtc", 171},
420     {"reboot,dm-verity_device_corrupted", 172},
421     {"reboot,dm-verity_enforcing", 173},
422     {"reboot,keys_clear", 174},
423     {"reboot,pmic_off_fault,.*", 175},
424     {"reboot,pmic_off_s3rst,.*", 176},
425     {"reboot,pmic_off_other,.*", 177},
426     {"reboot,userrequested,fastboot", 178},
427     {"reboot,userrequested,recovery", 179},
428     {"reboot,userrequested,recovery,ui", 180},
429     {"shutdown,userrequested,fastboot", 181},
430     {"shutdown,userrequested,recovery", 182},
431     {"reboot,unknown[0-9]*", 183},
432     {"reboot,longkey,.*", 184},
433     {"reboot,boringssl-self-check-failed", 185},
434     {"reboot,userspace_failed,shutdown_aborted", 186},
435     {"reboot,userspace_failed,watchdog_triggered", 187},
436     {"reboot,userspace_failed,watchdog_fork", 188},
437     {"reboot,userspace_failed,*", 189},
438     {"reboot,mount_userdata_failed", 190},
439     {"reboot,forcedsilent", 191},
440     {"reboot,forcednonsilent", 192},
441     {"reboot,thermal,tj", 193},
442 };
443 
444 // Converts a string value representing the reason the system booted to an
445 // integer representation. This is necessary for logging the boot_reason metric
446 // via Tron, which does not accept non-integer buckets in histograms.
BootReasonStrToEnum(const std::string & boot_reason)447 int32_t BootReasonStrToEnum(const std::string& boot_reason) {
448   auto mapping = kBootReasonMap.find(boot_reason);
449   if (mapping != kBootReasonMap.end()) {
450     return mapping->second;
451   }
452 
453   if (boot_reason.empty()) {
454     return kEmptyBootReason;
455   }
456 
457   for (const auto& [match, id] : kBootReasonMap) {
458     // Regex matches as a minimum require either [, \ or * to be present.
459     if (match.find_first_of("[\\*") == match.npos) continue;
460     // enforce match from beginning to end
461     auto exact = match;
462     if (exact[0] != '^') exact = "^" + exact;
463     if (exact[exact.size() - 1] != '$') exact = exact + "$";
464     if (std::regex_search(boot_reason, std::regex(exact))) return id;
465   }
466 
467   LOG(INFO) << "Unknown boot reason: " << boot_reason;
468   return kUnknownBootReason;
469 }
470 
471 // Canonical list of supported primary reboot reasons.
472 const std::vector<const std::string> knownReasons = {
473     // clang-format off
474     // kernel
475     "watchdog",
476     "kernel_panic",
477     // strong
478     "recovery",    // Should not happen from ro.boot.bootreason
479     "bootloader",  // Should not happen from ro.boot.bootreason
480     // blunt
481     "cold",
482     "hard",
483     "warm",
484     // super blunt
485     "shutdown",    // Can not happen from ro.boot.bootreason
486     "reboot",      // Default catch-all for anything unknown
487     // clang-format on
488 };
489 
490 // Returns true if the supplied reason prefix is considered detailed enough.
isStrongRebootReason(const std::string & r)491 bool isStrongRebootReason(const std::string& r) {
492   for (auto& s : knownReasons) {
493     if (s == "cold") break;
494     // Prefix defined as terminated by a nul or comma (,).
495     if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
496       return true;
497     }
498   }
499   return false;
500 }
501 
502 // Returns true if the supplied reason prefix is associated with the kernel.
isKernelRebootReason(const std::string & r)503 bool isKernelRebootReason(const std::string& r) {
504   for (auto& s : knownReasons) {
505     if (s == "recovery") break;
506     // Prefix defined as terminated by a nul or comma (,).
507     if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
508       return true;
509     }
510   }
511   return false;
512 }
513 
514 // Returns true if the supplied reason prefix is considered known.
isKnownRebootReason(const std::string & r)515 bool isKnownRebootReason(const std::string& r) {
516   for (auto& s : knownReasons) {
517     // Prefix defined as terminated by a nul or comma (,).
518     if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
519       return true;
520     }
521   }
522   return false;
523 }
524 
525 // If the reboot reason should be improved, report true if is too blunt.
isBluntRebootReason(const std::string & r)526 bool isBluntRebootReason(const std::string& r) {
527   if (isStrongRebootReason(r)) return false;
528 
529   if (!isKnownRebootReason(r)) return true;  // Can not support unknown as detail
530 
531   size_t pos = 0;
532   while ((pos = r.find(',', pos)) != std::string::npos) {
533     ++pos;
534     std::string next(r.substr(pos));
535     if (next.length() == 0) break;
536     if (next[0] == ',') continue;
537     if (!isKnownRebootReason(next)) return false;  // Unknown subreason is good.
538     if (isStrongRebootReason(next)) return false;  // eg: reboot,reboot
539   }
540   return true;
541 }
542 
readPstoreConsole(std::string & console)543 bool readPstoreConsole(std::string& console) {
544   if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
545     return true;
546   }
547   return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
548 }
549 
550 // Implement a variant of std::string::rfind that is resilient to errors in
551 // the data stream being inspected.
552 class pstoreConsole {
553  private:
554   const size_t kBitErrorRate = 8;  // number of bits per error
555   const std::string& console;
556 
557   // Number of bits that differ between the two arguments l and r.
558   // Returns zero if the values for l and r are identical.
numError(uint8_t l,uint8_t r) const559   size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
560 
561   // A string comparison function, reports the number of errors discovered
562   // in the match to a maximum of the bitLength / kBitErrorRate, at that
563   // point returning npos to indicate match is too poor.
564   //
565   // Since called in rfind which works backwards, expect cache locality will
566   // help if we check in reverse here as well for performance.
567   //
568   // Assumption: l (from console.c_str() + pos) is long enough to house
569   //             _r.length(), checked in rfind caller below.
570   //
numError(size_t pos,const std::string & _r) const571   size_t numError(size_t pos, const std::string& _r) const {
572     const char* l = console.c_str() + pos;
573     const char* r = _r.c_str();
574     size_t n = _r.length();
575     const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
576     const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
577     size_t count = 0;
578     n = 0;
579     do {
580       // individual character bit error rate > threshold + slop
581       size_t num = numError(*--le, *--re);
582       if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
583       // total bit error rate > threshold + slop
584       count += num;
585       ++n;
586       if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
587         return std::string::npos;
588       }
589     } while (le != reinterpret_cast<const uint8_t*>(l));
590     return count;
591   }
592 
593  public:
pstoreConsole(const std::string & console)594   explicit pstoreConsole(const std::string& console) : console(console) {}
595   // scope of argument must be equal to or greater than scope of pstoreConsole
596   explicit pstoreConsole(const std::string&& console) = delete;
597   explicit pstoreConsole(std::string&& console) = delete;
598 
599   // Our implementation of rfind, use exact match first, then resort to fuzzy.
rfind(const std::string & needle) const600   size_t rfind(const std::string& needle) const {
601     size_t pos = console.rfind(needle);  // exact match?
602     if (pos != std::string::npos) return pos;
603 
604     // Check to make sure needle fits in console string.
605     pos = console.length();
606     if (needle.length() > pos) return std::string::npos;
607     pos -= needle.length();
608     // fuzzy match to maximum kBitErrorRate
609     for (;;) {
610       if (numError(pos, needle) != std::string::npos) return pos;
611       if (pos == 0) break;
612       --pos;
613     }
614     return std::string::npos;
615   }
616 
617   // Our implementation of find, use only fuzzy match.
find(const std::string & needle,size_t start=0) const618   size_t find(const std::string& needle, size_t start = 0) const {
619     // Check to make sure needle fits in console string.
620     if (needle.length() > console.length()) return std::string::npos;
621     const size_t last_pos = console.length() - needle.length();
622     // fuzzy match to maximum kBitErrorRate
623     for (size_t pos = start; pos <= last_pos; ++pos) {
624       if (numError(pos, needle) != std::string::npos) return pos;
625     }
626     return std::string::npos;
627   }
628 
operator const std::string&() const629   operator const std::string&() const { return console; }
630 };
631 
632 // If bit error match to needle, correct it.
633 // Return true if any corrections were discovered and applied.
correctForBitError(std::string & reason,const std::string & needle)634 bool correctForBitError(std::string& reason, const std::string& needle) {
635   bool corrected = false;
636   if (reason.length() < needle.length()) return corrected;
637   const pstoreConsole console(reason);
638   const size_t last_pos = reason.length() - needle.length();
639   for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
640     pos = console.find(needle, pos);
641     if (pos == std::string::npos) break;
642 
643     // exact match has no malice
644     if (needle == reason.substr(pos, needle.length())) continue;
645 
646     corrected = true;
647     reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
648   }
649   return corrected;
650 }
651 
652 // If bit error match to needle, correct it.
653 // Return true if any corrections were discovered and applied.
654 // Try again if we can replace underline with spaces.
correctForBitErrorOrUnderline(std::string & reason,const std::string & needle)655 bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
656   bool corrected = correctForBitError(reason, needle);
657   std::string _needle(needle);
658   std::transform(_needle.begin(), _needle.end(), _needle.begin(),
659                  [](char c) { return (c == '_') ? ' ' : c; });
660   if (needle != _needle) {
661     corrected |= correctForBitError(reason, _needle);
662   }
663   return corrected;
664 }
665 
666 // Converts a string value representing the reason the system booted to a
667 // string complying with Android system standard reason.
transformReason(std::string & reason)668 void transformReason(std::string& reason) {
669   std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
670   std::transform(reason.begin(), reason.end(), reason.begin(),
671                  [](char c) { return ::isblank(c) ? '_' : c; });
672   std::transform(reason.begin(), reason.end(), reason.begin(),
673                  [](char c) { return ::isprint(c) ? c : '?'; });
674 }
675 
676 // Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
677 // kernel_panic,<subreason>.
678 //
679 // If quoted flag is set, pull out and correct single quoted ('), newline (\n)
680 // or unprintable character terminated subreason, pos is supplied just beyond
681 // first quote.  if quoted false, pull out and correct newline (\n) or
682 // unprintable character terminated subreason.
683 //
684 // Heuristics to find termination is painted into a corner:
685 
686 // single bit error for quote ' that we can block.  It is acceptable for
687 // the others 7, g in reason.  2/9 chance will miss the terminating quote,
688 // but there is always the terminating newline that usually immediately
689 // follows to fortify our chances.
likely_single_quote(char c)690 bool likely_single_quote(char c) {
691   switch (static_cast<uint8_t>(c)) {
692     case '\'':         // '\''
693     case '\'' ^ 0x01:  // '&'
694     case '\'' ^ 0x02:  // '%'
695     case '\'' ^ 0x04:  // '#'
696     case '\'' ^ 0x08:  // '/'
697       return true;
698     case '\'' ^ 0x10:  // '7'
699       break;
700     case '\'' ^ 0x20:  // '\a' (unprintable)
701       return true;
702     case '\'' ^ 0x40:  // 'g'
703       break;
704     case '\'' ^ 0x80:  // 0xA7 (unprintable)
705       return true;
706   }
707   return false;
708 }
709 
710 // ::isprint(c) and likely_space() will prevent us from being called for
711 // fundamentally printable entries, except for '\r' and '\b'.
712 //
713 // Except for * and J, single bit errors for \n, all others are non-
714 // printable so easy catch.  It is _acceptable_ for *, J or j to exist in
715 // the reason string, so 2/9 chance we will miss the terminating newline.
716 //
717 // NB: J might not be acceptable, except if at the beginning or preceded
718 //     with a space, '(' or any of the quotes and their BER aliases.
719 // NB: * might not be acceptable, except if at the beginning or preceded
720 //     with a space, another *, or any of the quotes or their BER aliases.
721 //
722 // To reduce the chances to closer to 1/9 is too complicated for the gain.
likely_newline(char c)723 bool likely_newline(char c) {
724   switch (static_cast<uint8_t>(c)) {
725     case '\n':         // '\n' (unprintable)
726     case '\n' ^ 0x01:  // '\r' (unprintable)
727     case '\n' ^ 0x02:  // '\b' (unprintable)
728     case '\n' ^ 0x04:  // 0x0E (unprintable)
729     case '\n' ^ 0x08:  // 0x02 (unprintable)
730     case '\n' ^ 0x10:  // 0x1A (unprintable)
731       return true;
732     case '\n' ^ 0x20:  // '*'
733     case '\n' ^ 0x40:  // 'J'
734       break;
735     case '\n' ^ 0x80:  // 0x8A (unprintable)
736       return true;
737   }
738   return false;
739 }
740 
741 // ::isprint(c) will prevent us from being called for all the printable
742 // matches below.  If we let unprintables through because of this, they
743 // get converted to underscore (_) by the validation phase.
likely_space(char c)744 bool likely_space(char c) {
745   switch (static_cast<uint8_t>(c)) {
746     case ' ':          // ' '
747     case ' ' ^ 0x01:   // '!'
748     case ' ' ^ 0x02:   // '"'
749     case ' ' ^ 0x04:   // '$'
750     case ' ' ^ 0x08:   // '('
751     case ' ' ^ 0x10:   // '0'
752     case ' ' ^ 0x20:   // '\0' (unprintable)
753     case ' ' ^ 0x40:   // 'P'
754     case ' ' ^ 0x80:   // 0xA0 (unprintable)
755     case '\t':         // '\t'
756     case '\t' ^ 0x01:  // '\b' (unprintable) (likely_newline counters)
757     case '\t' ^ 0x02:  // '\v' (unprintable)
758     case '\t' ^ 0x04:  // '\r' (unprintable) (likely_newline counters)
759     case '\t' ^ 0x08:  // 0x01 (unprintable)
760     case '\t' ^ 0x10:  // 0x19 (unprintable)
761     case '\t' ^ 0x20:  // ')'
762     case '\t' ^ 0x40:  // '1'
763     case '\t' ^ 0x80:  // 0x89 (unprintable)
764       return true;
765   }
766   return false;
767 }
768 
getSubreason(const std::string & content,size_t pos,bool quoted)769 std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
770   static constexpr size_t max_reason_length = 256;
771 
772   std::string subReason(content.substr(pos, max_reason_length));
773   // Correct against any known strings that Bit Error Match
774   for (const auto& s : knownReasons) {
775     correctForBitErrorOrUnderline(subReason, s);
776   }
777   std::string terminator(quoted ? "'" : "");
778   for (const auto& m : kBootReasonMap) {
779     if (m.first.length() <= strlen("cold")) continue;  // too short?
780     if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
781     if (m.first.length() <= strlen("reboot,cold")) continue;  // short?
782     if (android::base::StartsWith(m.first, "reboot,")) {
783       correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
784     } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
785       correctForBitErrorOrUnderline(subReason,
786                                     m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
787     } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
788       correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
789     }
790   }
791   for (pos = 0; pos < subReason.length(); ++pos) {
792     char c = subReason[pos];
793     if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
794         (quoted && likely_single_quote(c))) {
795       subReason.erase(pos);
796       break;
797     }
798   }
799   transformReason(subReason);
800   return subReason;
801 }
802 
addKernelPanicSubReason(const pstoreConsole & console,std::string & ret)803 bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
804   // Check for kernel panic types to refine information
805   if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
806       (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
807     ret = "kernel_panic,sysrq";
808     // Invented for Android to allow daemons that specifically trigger sysrq
809     // to communicate more accurate boot subreasons via last console messages.
810     static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
811     auto pos = console.rfind(sysrqSubreason);
812     if (pos != std::string::npos) {
813       ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
814     }
815     return true;
816   }
817   if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
818       std::string::npos) {
819     ret = "kernel_panic,null";
820     return true;
821   }
822   if (console.rfind("Kernel BUG at ") != std::string::npos) {
823     ret = "kernel_panic,bug";
824     return true;
825   }
826 
827   std::string panic("Kernel panic - not syncing: ");
828   auto pos = console.rfind(panic);
829   if (pos != std::string::npos) {
830     static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
831         {"Out of memory", "oom"},
832         {"out of memory", "oom"},
833         {"Oh boy, that early out of memory", "oom"},  // omg
834         {"BUG!", "bug"},
835         {"hung_task: blocked tasks", "hung"},
836         {"audit: ", "audit"},
837         {"scheduling while atomic", "atomic"},
838         {"Attempted to kill init!", "init"},
839         {"Requested init", "init"},
840         {"No working init", "init"},
841         {"Could not decompress init", "init"},
842         {"RCU Stall", "hung,rcu"},
843         {"stack-protector", "stack"},
844         {"kernel stack overflow", "stack"},
845         {"Corrupt kernel stack", "stack"},
846         {"low stack detected", "stack"},
847         {"corrupted stack end", "stack"},
848         {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
849         {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
850         {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
851         {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
852     };
853 
854     ret = "kernel_panic";
855     for (auto& s : panicReasons) {
856       if (console.find(panic + s.first, pos) != std::string::npos) {
857         ret += "," + s.second;
858         return true;
859       }
860     }
861     auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
862     if (reason.length() > 3) {
863       ret += "," + reason;
864     }
865     return true;
866   }
867   return false;
868 }
869 
addKernelPanicSubReason(const std::string & content,std::string & ret)870 bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
871   return addKernelPanicSubReason(pstoreConsole(content), ret);
872 }
873 
874 const char system_reboot_reason_property[] = "sys.boot.reason";
875 const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
876 const char last_reboot_reason_file[] = LAST_REBOOT_REASON_FILE;
877 const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
878 constexpr size_t history_reboot_reason_size = 4;
879 const char history_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY ".history";
880 const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
881 
882 // Land system_boot_reason into system_reboot_reason_property.
883 // Shift system_boot_reason into history_reboot_reason_property.
BootReasonAddToHistory(const std::string & system_boot_reason)884 void BootReasonAddToHistory(const std::string& system_boot_reason) {
885   if (system_boot_reason.empty()) return;
886   LOG(INFO) << "Canonical boot reason: " << system_boot_reason;
887   auto old_system_boot_reason = android::base::GetProperty(system_reboot_reason_property, "");
888   if (!android::base::SetProperty(system_reboot_reason_property, system_boot_reason)) {
889     android::base::SetProperty(system_reboot_reason_property,
890                                system_boot_reason.substr(0, PROPERTY_VALUE_MAX - 1));
891   }
892   auto reason_history =
893       android::base::Split(android::base::GetProperty(history_reboot_reason_property, ""), "\n");
894   static auto mark = time(nullptr);
895   auto mark_str = std::string(",") + std::to_string(mark);
896   auto marked_system_boot_reason = system_boot_reason + mark_str;
897   if (!reason_history.empty()) {
898     // delete any entries that we just wrote in a previous
899     // call and leveraging duplicate line handling
900     auto last = old_system_boot_reason + mark_str;
901     // trim the list to (history_reboot_reason_size - 1)
902     ssize_t max = history_reboot_reason_size;
903     for (auto it = reason_history.begin(); it != reason_history.end();) {
904       if (it->empty() || (last == *it) || (marked_system_boot_reason == *it) || (--max <= 0)) {
905         it = reason_history.erase(it);
906       } else {
907         last = *it;
908         ++it;
909       }
910     }
911   }
912   // insert at the front, concatenating mark (<epoch time>) detail to the value.
913   reason_history.insert(reason_history.begin(), marked_system_boot_reason);
914   // If the property string is too long ( > PROPERTY_VALUE_MAX)
915   // we get an error, so trim out last entry and try again.
916   while (!android::base::SetProperty(history_reboot_reason_property,
917                                      android::base::Join(reason_history, '\n'))) {
918     auto it = std::prev(reason_history.end());
919     if (it == reason_history.end()) break;
920     reason_history.erase(it);
921   }
922 }
923 
924 // Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
BootReasonStrToReason(const std::string & boot_reason)925 std::string BootReasonStrToReason(const std::string& boot_reason) {
926   auto ret = android::base::GetProperty(system_reboot_reason_property, "");
927   std::string reason(boot_reason);
928   // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
929   if (reason == ret) ret = "";
930 
931   transformReason(reason);
932 
933   // Is the current system boot reason sys.boot.reason valid?
934   if (!isKnownRebootReason(ret)) ret = "";
935 
936   if (ret == "") {
937     // Is the bootloader boot reason ro.boot.bootreason known?
938     std::vector<std::string> words(android::base::Split(reason, ",_-"));
939     for (auto& s : knownReasons) {
940       std::string blunt;
941       for (auto& r : words) {
942         if (r == s) {
943           if (isBluntRebootReason(s)) {
944             blunt = s;
945           } else {
946             ret = s;
947             break;
948           }
949         }
950       }
951       if (ret == "") ret = blunt;
952       if (ret != "") break;
953     }
954   }
955 
956   if (ret == "") {
957     // A series of checks to take some officially unsupported reasons
958     // reported by the bootloader and find some logical and canonical
959     // sense.  In an ideal world, we would require those bootloaders
960     // to behave and follow our CTS standards.
961     //
962     // first member is the output
963     // second member is an unanchored regex for an alias
964     //
965     // If output has a prefix of <bang> '!', we do not use it as a
966     // match needle (and drop the <bang> prefix when landing in output),
967     // otherwise look for it as well. This helps keep the scale of the
968     // following table smaller.
969     static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
970         {"watchdog", "wdog"},
971         {"kernel_panic", "panic"},
972         {"shutdown,thermal", "thermal"},
973         {"warm,s3_wakeup", "s3_wakeup"},
974         {"hard,hw_reset", "hw_reset"},
975         {"cold,charger", "usb|power_on_cable"},
976         {"cold,powerkey", "powerkey|power_key|PowerKey|power_on"},
977         {"cold,rtc", "rtc"},
978         {"cold,rtc,2sec", "2sec_reboot"},
979         {"!warm", "wdt_by_pass_pwk"},  // change flavour of blunt
980         {"!reboot", "^wdt$"},          // change flavour of blunt
981         {"reboot,tool", "tool_by_pass_pwk"},
982         {"!reboot,longkey", "reboot_longkey"},
983         {"!reboot,longkey", "kpdpwr"},
984         {"!reboot,undervoltage", "uvlo"},
985         {"!reboot,powerloss", "smpl"},
986         {"bootloader", ""},
987     };
988 
989     for (auto& s : aliasReasons) {
990       size_t firstHasNot = s.first[0] == '!';
991       if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
992         ret = s.first;
993         break;
994       }
995       if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
996         ret = s.first.substr(firstHasNot);
997         break;
998       }
999     }
1000   }
1001 
1002   // If watchdog is the reason, see if there is a security angle?
1003   if (ret == "watchdog") {
1004     if (reason.find("sec") != std::string::npos) {
1005       ret += ",security";
1006     }
1007   }
1008 
1009   if (ret == "kernel_panic") {
1010     // Check to see if last klog has some refinement hints.
1011     std::string content;
1012     if (readPstoreConsole(content)) {
1013       addKernelPanicSubReason(content, ret);
1014     }
1015   } else if (isBluntRebootReason(ret)) {
1016     // Check the other available reason resources if the reason is still blunt.
1017 
1018     // Check to see if last klog has some refinement hints.
1019     std::string content;
1020     if (readPstoreConsole(content)) {
1021       const pstoreConsole console(content);
1022       // The toybox reboot command used directly (unlikely)? But also
1023       // catches init's response to Android's more controlled reboot command.
1024       if (console.rfind("reboot: Power down") != std::string::npos) {
1025         ret = "shutdown";  // Still too blunt, but more accurate.
1026         // ToDo: init should record the shutdown reason to kernel messages ala:
1027         //           init: shutdown system with command 'last_reboot_reason'
1028         //       so that if pstore has persistence we can get some details
1029         //       that could be missing in last_reboot_reason_property.
1030       }
1031 
1032       static const char cmd[] = "reboot: Restarting system with command '";
1033       size_t pos = console.rfind(cmd);
1034       if (pos != std::string::npos) {
1035         std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
1036         if (subReason != "") {  // Will not land "reboot" as that is too blunt.
1037           if (isKernelRebootReason(subReason)) {
1038             ret = "reboot," + subReason;  // User space can't talk kernel reasons.
1039           } else if (isKnownRebootReason(subReason)) {
1040             ret = subReason;
1041           } else {
1042             ret = "reboot," + subReason;  // legitimize unknown reasons
1043           }
1044         }
1045         // Some bootloaders shutdown results record in last kernel message.
1046         if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
1047           ret = "shutdown";
1048         }
1049       }
1050 
1051       // Check for kernel panics, allowed to override reboot command.
1052       if (!addKernelPanicSubReason(console, ret) &&
1053           // check for long-press power down
1054           ((console.rfind("Power held for ") != std::string::npos) ||
1055            (console.rfind("charger: [") != std::string::npos))) {
1056         ret = "cold";
1057       }
1058     }
1059 
1060     // TODO: use the HAL to get battery level (http://b/77725702).
1061 
1062     // Is there a controlled shutdown hint in last_reboot_reason_property?
1063     if (isBluntRebootReason(ret)) {
1064       // Content buffer no longer will have console data. Beware if more
1065       // checks added below, that depend on parsing console content.
1066       if (!android::base::ReadFileToString(last_reboot_reason_file, &content)) {
1067         content = android::base::GetProperty(last_reboot_reason_property, "");
1068       }
1069       transformReason(content);
1070 
1071       // Anything in last is better than 'super-blunt' reboot or shutdown.
1072       if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
1073         ret = content;
1074       }
1075     }
1076 
1077     // Other System Health HAL reasons?
1078 
1079     // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
1080     //       possibly offer hardware-specific clues from the PMIC.
1081   }
1082 
1083   // If unknown left over from above, make it "reboot,<boot_reason>"
1084   if (ret == "") {
1085     ret = "reboot";
1086     if (android::base::StartsWith(reason, "reboot")) {
1087       reason = reason.substr(strlen("reboot"));
1088       while ((reason[0] == ',') || (reason[0] == '_')) {
1089         reason = reason.substr(1);
1090       }
1091     }
1092     if (reason != "") {
1093       ret += ",";
1094       ret += reason;
1095     }
1096   }
1097 
1098   LOG(INFO) << "Canonical boot reason: " << ret;
1099   return ret;
1100 }
1101 
1102 // Returns the appropriate metric key prefix for the boot_complete metric such
1103 // that boot metrics after a system update are labeled as ota_boot_complete;
1104 // otherwise, they are labeled as boot_complete.  This method encapsulates the
1105 // bookkeeping required to track when a system update has occurred by storing
1106 // the UTC timestamp of the system build date and comparing against the current
1107 // system build date.
CalculateBootCompletePrefix()1108 std::string CalculateBootCompletePrefix() {
1109   static const std::string kBuildDateKey = "build_date";
1110   std::string boot_complete_prefix = "boot_complete";
1111 
1112   auto build_date_str = android::base::GetProperty("ro.build.date.utc", "");
1113   int32_t build_date;
1114   if (!android::base::ParseInt(build_date_str, &build_date)) {
1115     return std::string();
1116   }
1117 
1118   BootEventRecordStore boot_event_store;
1119   BootEventRecordStore::BootEventRecord record;
1120   if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1121     boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1122     boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
1123     BootReasonAddToHistory("reboot,factory_reset");
1124   } else if (build_date != record.second) {
1125     boot_complete_prefix = "ota_" + boot_complete_prefix;
1126     boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
1127     BootReasonAddToHistory("reboot,ota");
1128   }
1129 
1130   return boot_complete_prefix;
1131 }
1132 
1133 // Records the value of a given ro.boottime.init property in milliseconds.
RecordInitBootTimeProp(BootEventRecordStore * boot_event_store,const char * property)1134 void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
1135   auto value = android::base::GetProperty(property, "");
1136 
1137   int32_t time_in_ms;
1138   if (android::base::ParseInt(value, &time_in_ms)) {
1139     boot_event_store->AddBootEventWithValue(property, time_in_ms);
1140   }
1141 }
1142 
1143 // A map from bootloader timing stage to the time that stage took during boot.
1144 typedef std::map<std::string, int32_t> BootloaderTimingMap;
1145 
1146 // Returns a mapping from bootloader stage names to the time those stages
1147 // took to boot.
GetBootLoaderTimings()1148 const BootloaderTimingMap GetBootLoaderTimings() {
1149   BootloaderTimingMap timings;
1150 
1151   // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1152   // where timeN is in milliseconds.
1153   auto value = android::base::GetProperty("ro.boot.boottime", "");
1154   if (value.empty()) {
1155     // ro.boot.boottime is not reported on all devices.
1156     return BootloaderTimingMap();
1157   }
1158 
1159   auto stages = android::base::Split(value, ",");
1160   for (const auto& stageTiming : stages) {
1161     // |stageTiming| is of the form 'stage:time'.
1162     auto stageTimingValues = android::base::Split(stageTiming, ":");
1163     DCHECK_EQ(2U, stageTimingValues.size());
1164 
1165     if (stageTimingValues.size() < 2) continue;
1166     std::string stageName = stageTimingValues[0];
1167     int32_t time_ms;
1168     if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
1169       timings[stageName] = time_ms;
1170     }
1171   }
1172 
1173   return timings;
1174 }
1175 
1176 // Returns the total bootloader boot time from the ro.boot.boottime system property.
GetBootloaderTime(const BootloaderTimingMap & bootloader_timings)1177 int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1178   int32_t total_time = 0;
1179   for (const auto& timing : bootloader_timings) {
1180     total_time += timing.second;
1181   }
1182 
1183   return total_time;
1184 }
1185 
1186 // Parses and records the set of bootloader stages and associated boot times
1187 // from the ro.boot.boottime system property.
RecordBootloaderTimings(BootEventRecordStore * boot_event_store,const BootloaderTimingMap & bootloader_timings)1188 void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1189                              const BootloaderTimingMap& bootloader_timings) {
1190   int32_t total_time = 0;
1191   for (const auto& timing : bootloader_timings) {
1192     total_time += timing.second;
1193     boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1194   }
1195 
1196   boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
1197 }
1198 
1199 // Returns the closest estimation to the absolute device boot time, i.e.,
1200 // from power on to boot_complete, including bootloader times.
GetAbsoluteBootTime(const BootloaderTimingMap & bootloader_timings,std::chrono::milliseconds uptime)1201 std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1202                                               std::chrono::milliseconds uptime) {
1203   int32_t bootloader_time_ms = 0;
1204 
1205   for (const auto& timing : bootloader_timings) {
1206     if (timing.first.compare("SW") != 0) {
1207       bootloader_time_ms += timing.second;
1208     }
1209   }
1210 
1211   auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
1212   return bootloader_duration + uptime;
1213 }
1214 
1215 // Records the closest estimation to the absolute device boot time in seconds.
1216 // i.e. from power on to boot_complete, including bootloader times.
RecordAbsoluteBootTime(BootEventRecordStore * boot_event_store,std::chrono::milliseconds absolute_total)1217 void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1218                             std::chrono::milliseconds absolute_total) {
1219   auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1220   boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1221 }
1222 
1223 // Logs the total boot time and reason to statsd.
LogBootInfoToStatsd(std::chrono::milliseconds end_time,std::chrono::milliseconds total_duration,int32_t bootloader_duration_ms,double time_since_last_boot_sec)1224 void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1225                          std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1226                          double time_since_last_boot_sec) {
1227   auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "<EMPTY>");
1228   auto system_reason = android::base::GetProperty(system_reboot_reason_property, "<EMPTY>");
1229   android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1230                              system_reason.c_str(), end_time.count(), total_duration.count(),
1231                              (int64_t)bootloader_duration_ms,
1232                              (int64_t)time_since_last_boot_sec * 1000);
1233 }
1234 
SetSystemBootReason()1235 void SetSystemBootReason() {
1236   const auto bootloader_boot_reason =
1237       android::base::GetProperty(bootloader_reboot_reason_property, "");
1238   const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1239   // Record the scrubbed system_boot_reason to the property
1240   BootReasonAddToHistory(system_boot_reason);
1241   // Shift last_reboot_reason_property to last_last_reboot_reason_property
1242   std::string last_boot_reason;
1243   if (!android::base::ReadFileToString(last_reboot_reason_file, &last_boot_reason)) {
1244     PLOG(ERROR) << "Failed to read " << last_reboot_reason_file;
1245     last_boot_reason = android::base::GetProperty(last_reboot_reason_property, "");
1246     LOG(INFO) << "Value of " << last_reboot_reason_property << " : " << last_boot_reason;
1247   } else {
1248     LOG(INFO) << "Last reboot reason read from " << last_reboot_reason_file << " : "
1249               << last_boot_reason << ". Last reboot reason read from "
1250               << last_reboot_reason_property << " : "
1251               << android::base::GetProperty(last_reboot_reason_property, "");
1252   }
1253   if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1254     last_boot_reason = system_boot_reason;
1255   } else {
1256     transformReason(last_boot_reason);
1257   }
1258   LOG(INFO) << "Normalized last reboot reason : " << last_boot_reason;
1259   android::base::SetProperty(last_last_reboot_reason_property, last_boot_reason);
1260   android::base::SetProperty(last_reboot_reason_property, "");
1261   if (unlink(last_reboot_reason_file) != 0) {
1262     PLOG(ERROR) << "Failed to unlink " << last_reboot_reason_file;
1263   }
1264 }
1265 
1266 // Gets the boot time offset. This is useful when Android is running in a
1267 // container, because the boot_clock is not reset when Android reboots.
GetBootTimeOffset()1268 std::chrono::nanoseconds GetBootTimeOffset() {
1269   static const int64_t boottime_offset =
1270       android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1271   return std::chrono::nanoseconds(boottime_offset);
1272 }
1273 
1274 // Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1275 // clock.
GetUptime()1276 android::base::boot_clock::duration GetUptime() {
1277   return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1278 }
1279 
1280 // Records several metrics related to the time it takes to boot the device,
1281 // including disambiguating boot time on encrypted or non-encrypted devices.
RecordBootComplete()1282 void RecordBootComplete() {
1283   BootEventRecordStore boot_event_store;
1284   BootEventRecordStore::BootEventRecord record;
1285 
1286   auto uptime_ns = GetUptime();
1287   auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
1288   time_t current_time_utc = time(nullptr);
1289   time_t time_since_last_boot = 0;
1290 
1291   if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1292     time_t last_boot_time_utc = record.second;
1293     time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
1294     boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
1295   }
1296 
1297   boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
1298 
1299   // The boot_complete metric has two variants: boot_complete and
1300   // ota_boot_complete.  The latter signifies that the device is booting after
1301   // a system update.
1302   std::string boot_complete_prefix = CalculateBootCompletePrefix();
1303   if (boot_complete_prefix.empty()) {
1304     // The system is hosed because the build date property could not be read.
1305     return;
1306   }
1307 
1308   // post_decrypt_time_elapsed is only logged on encrypted devices.
1309   if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1310     // Log the amount of time elapsed until the device is decrypted, which
1311     // includes the variable amount of time the user takes to enter the
1312     // decryption password.
1313     boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
1314 
1315     // Subtract the decryption time to normalize the boot cycle timing.
1316     std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
1317     boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
1318                                            boot_complete.count());
1319   } else {
1320     boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1321                                            uptime_s.count());
1322   }
1323 
1324   // Record the total time from device startup to boot complete, regardless of
1325   // encryption state.
1326   // Note: we are recording seconds here even though the field in statsd atom specifies
1327   // milliseconds.
1328   boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
1329 
1330   RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1331   RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.first_stage");
1332   RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1333   RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
1334 
1335   const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
1336   int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
1337   RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1338 
1339   auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
1340   auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1341   RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1342 
1343   auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1344   auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1345 
1346   LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1347                       time_since_last_boot);
1348 }
1349 
1350 // Records the boot_reason metric by querying the ro.boot.bootreason system
1351 // property.
RecordBootReason()1352 void RecordBootReason() {
1353   const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
1354 
1355   if (reason.empty()) {
1356     // TODO(b/148575354): Replace with statsd.
1357     // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1358     // (and not corruption anywhere else in the reporting pipeline).
1359     // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1360     //                                        android::metricslogger::FIELD_PLATFORM_REASON,
1361     //                                        "<EMPTY>");
1362   } else {
1363     // TODO(b/148575354): Replace with statsd.
1364     // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1365     //                                        android::metricslogger::FIELD_PLATFORM_REASON,
1366     //                                        reason);
1367   }
1368 
1369   // Log the raw bootloader_boot_reason property value.
1370   int32_t boot_reason = BootReasonStrToEnum(reason);
1371   BootEventRecordStore boot_event_store;
1372   boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
1373 
1374   // Log the scrubbed system_boot_reason.
1375   const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
1376   int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1377   boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1378 
1379   if (reason == "") {
1380     android::base::SetProperty(bootloader_reboot_reason_property, system_reason);
1381   }
1382 }
1383 
1384 // Records two metrics related to the user resetting a device: the time at
1385 // which the device is reset, and the time since the user last reset the
1386 // device.  The former is only set once per-factory reset.
RecordFactoryReset()1387 void RecordFactoryReset() {
1388   BootEventRecordStore boot_event_store;
1389   BootEventRecordStore::BootEventRecord record;
1390 
1391   time_t current_time_utc = time(nullptr);
1392 
1393   if (current_time_utc < 0) {
1394     // UMA does not display negative values in buckets, so convert to positive.
1395     // Logging via BootEventRecordStore.
1396     android::util::stats_write(
1397         static_cast<int32_t>(android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED),
1398         static_cast<int32_t>(
1399             android::util::BOOT_TIME_EVENT_ERROR_CODE__EVENT__FACTORY_RESET_CURRENT_TIME_FAILURE),
1400         static_cast<int32_t>(std::abs(current_time_utc)));
1401 
1402     // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
1403     // is losing records somehow.
1404     boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1405                                            std::abs(current_time_utc));
1406     return;
1407   } else {
1408     android::util::stats_write(
1409         static_cast<int32_t>(android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED),
1410         static_cast<int32_t>(
1411             android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_CURRENT_TIME),
1412         static_cast<int64_t>(current_time_utc));
1413 
1414     // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
1415     // is losing records somehow.
1416     boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
1417   }
1418 
1419   // The factory_reset boot event does not exist after the device is reset, so
1420   // use this signal to mark the time of the factory reset.
1421   if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1422     boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
1423 
1424     // Don't log the time_since_factory_reset until some time has elapsed.
1425     // The data is not meaningful yet and skews the histogram buckets.
1426     return;
1427   }
1428 
1429   // Calculate and record the difference in time between now and the
1430   // factory_reset time.
1431   time_t factory_reset_utc = record.second;
1432   android::util::stats_write(
1433       static_cast<int32_t>(android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED),
1434       static_cast<int32_t>(
1435           android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RECORD_VALUE),
1436       static_cast<int64_t>(factory_reset_utc));
1437 
1438   // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
1439   // is losing records somehow.
1440   boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
1441 
1442   time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1443   boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
1444 }
1445 
1446 // List the associated boot reason(s), if arg is nullptr then all.
PrintBootReasonEnum(const char * arg)1447 void PrintBootReasonEnum(const char* arg) {
1448   int value = -1;
1449   if (arg != nullptr) {
1450     value = BootReasonStrToEnum(arg);
1451   }
1452   for (const auto& [match, id] : kBootReasonMap) {
1453     if ((value < 0) || (value == id)) {
1454       printf("%u\t%s\n", id, match.c_str());
1455     }
1456   }
1457 }
1458 
1459 }  // namespace
1460 
main(int argc,char ** argv)1461 int main(int argc, char** argv) {
1462   android::base::InitLogging(argv);
1463 
1464   const std::string cmd_line = GetCommandLine(argc, argv);
1465   LOG(INFO) << "Service started: " << cmd_line;
1466 
1467   int option_index = 0;
1468   static const char value_str[] = "value";
1469   static const char system_boot_reason_str[] = "set_system_boot_reason";
1470   static const char boot_complete_str[] = "record_boot_complete";
1471   static const char boot_reason_str[] = "record_boot_reason";
1472   static const char factory_reset_str[] = "record_time_since_factory_reset";
1473   static const char boot_reason_enum_str[] = "boot_reason_enum";
1474   static const struct option long_options[] = {
1475       // clang-format off
1476       { "help",                 no_argument,       NULL,   'h' },
1477       { "log",                  no_argument,       NULL,   'l' },
1478       { "print",                no_argument,       NULL,   'p' },
1479       { "record",               required_argument, NULL,   'r' },
1480       { value_str,              required_argument, NULL,   0 },
1481       { system_boot_reason_str, no_argument,       NULL,   0 },
1482       { boot_complete_str,      no_argument,       NULL,   0 },
1483       { boot_reason_str,        no_argument,       NULL,   0 },
1484       { factory_reset_str,      no_argument,       NULL,   0 },
1485       { boot_reason_enum_str,   optional_argument, NULL,   0 },
1486       { NULL,                   0,                 NULL,   0 }
1487       // clang-format on
1488   };
1489 
1490   std::string boot_event;
1491   std::string value;
1492   int opt = 0;
1493   while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
1494     switch (opt) {
1495       // This case handles long options which have no single-character mapping.
1496       case 0: {
1497         const std::string option_name = long_options[option_index].name;
1498         if (option_name == value_str) {
1499           // |optarg| is an external variable set by getopt representing
1500           // the option argument.
1501           value = optarg;
1502         } else if (option_name == system_boot_reason_str) {
1503           SetSystemBootReason();
1504         } else if (option_name == boot_complete_str) {
1505           RecordBootComplete();
1506         } else if (option_name == boot_reason_str) {
1507           RecordBootReason();
1508         } else if (option_name == factory_reset_str) {
1509           RecordFactoryReset();
1510         } else if (option_name == boot_reason_enum_str) {
1511           PrintBootReasonEnum(optarg);
1512         } else {
1513           LOG(ERROR) << "Invalid option: " << option_name;
1514         }
1515         break;
1516       }
1517 
1518       case 'h': {
1519         ShowHelp(argv[0]);
1520         break;
1521       }
1522 
1523       case 'l': {
1524         LogBootEvents();
1525         break;
1526       }
1527 
1528       case 'p': {
1529         PrintBootEvents();
1530         break;
1531       }
1532 
1533       case 'r': {
1534         // |optarg| is an external variable set by getopt representing
1535         // the option argument.
1536         boot_event = optarg;
1537         break;
1538       }
1539 
1540       default: {
1541         DCHECK_EQ(opt, '?');
1542 
1543         // |optopt| is an external variable set by getopt representing
1544         // the value of the invalid option.
1545         LOG(ERROR) << "Invalid option: " << optopt;
1546         ShowHelp(argv[0]);
1547         return EXIT_FAILURE;
1548       }
1549     }
1550   }
1551 
1552   if (!boot_event.empty()) {
1553     RecordBootEventFromCommandLine(boot_event, value);
1554   }
1555 
1556   return 0;
1557 }
1558