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