blob: 3b8866e51afbc47809412928e6b14d9fafd6c038 [file] [log] [blame]
James Hawkinsabd73e62016-01-19 15:10:38 -08001/*
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
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080021#include <getopt.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070022#include <sys/klog.h>
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070023#include <unistd.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070024
James Hawkinse78ea772017-03-24 11:43:02 -070025#include <chrono>
James Hawkins0660b302016-03-08 16:18:15 -080026#include <cmath>
James Hawkinsabd73e62016-01-19 15:10:38 -080027#include <cstddef>
28#include <cstdio>
James Hawkins500d7152016-02-16 15:05:54 -080029#include <ctime>
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -070030#include <iterator>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080031#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080032#include <memory>
Mark Salyzyn25900dd2018-03-16 09:05:59 -070033#include <regex>
James Hawkinsabd73e62016-01-19 15:10:38 -080034#include <string>
Keun young Park606af6d2020-01-15 10:09:03 -080035#include <string_view>
36#include <unordered_map>
Mark Salyzyn853bb802018-03-16 08:44:56 -070037#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080038#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070039
James Hawkinse78ea772017-03-24 11:43:02 -070040#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070041#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080042#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070043#include <android-base/parseint.h>
Luis Hector Chavez583d34c2018-04-12 15:25:15 -070044#include <android-base/properties.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080045#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070046#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070047#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080048#include <cutils/properties.h>
Tej Singh4eacd382018-01-25 17:59:57 -080049#include <statslog.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070050
James Hawkinsabd73e62016-01-19 15:10:38 -080051#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080052
53namespace {
54
Keun young Park606af6d2020-01-15 10:09:03 -080055struct AtomInfo {
56 int32_t atom;
57 int32_t event;
58};
59
60// Maps BootEvent used inside bootstat into statsd atom defined in
jiajia tangf0839572022-07-07 14:30:19 +080061// frameworks/proto_logging/stats/atoms.proto.
Keun young Park606af6d2020-01-15 10:09:03 -080062const 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}},
Keun young Park606af6d2020-01-15 10:09:03 -080070 {"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}},
Keun young Park606af6d2020-01-15 10:09:03 -080073 {"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}},
Keun young Park606af6d2020-01-15 10:09:03 -080080 {"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}},
Keun young Park606af6d2020-01-15 10:09:03 -080086 // 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
James Hawkinsabd73e62016-01-19 15:10:38 -0800139// Scans the boot event record store for record files and logs each boot event
140// via EventLog.
141void LogBootEvents() {
142 BootEventRecordStore boot_event_store;
James Hawkinsabd73e62016-01-19 15:10:38 -0800143 auto events = boot_event_store.GetAllBootEvents();
Keun young Park606af6d2020-01-15 10:09:03 -0800144 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 }
James Hawkinsabd73e62016-01-19 15:10:38 -0800166}
167
James Hawkinsc6275582016-03-22 10:47:44 -0700168// 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.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700171void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -0700172 BootEventRecordStore boot_event_store;
173 if (!value_str.empty()) {
174 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -0700175 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -0700176 boot_event_store.AddBootEventWithValue(event, value);
177 }
James Hawkinsc6275582016-03-22 10:47:44 -0700178 } else {
179 boot_event_store.AddBootEvent(event);
180 }
181}
182
James Hawkinsabd73e62016-01-19 15:10:38 -0800183void 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
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700194void ShowHelp(const char* cmd) {
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700195 fprintf(stderr, "Usage: %s [options]...\n", cmd);
James Hawkinsabd73e62016-01-19 15:10:38 -0800196 fprintf(stderr,
197 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +0800198 " -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"
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700205 " --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");
James Hawkinsabd73e62016-01-19 15:10:38 -0800207}
208
209// Constructs a readable, printable string from the givencommand line
210// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700211std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800212 std::string cmd;
213 for (int i = 0; i < argc; ++i) {
214 cmd += argv[i];
215 cmd += " ";
216 }
217
218 return cmd;
219}
220
James Hawkins25f71222017-10-10 16:37:05 -0700221constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800222constexpr int32_t kUnknownBootReason = 1;
223
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800224// 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
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700227// values. Regex matching, to manage the scale, as a minimum require either
228// [, \ or * to be present in the string to switch to checking.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800229const std::map<std::string, int32_t> kBootReasonMap = {
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700230 {"reboot,[empty]", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700231 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700232 {"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},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700246 {"power_key", 16}, // aliasReasons to cold,powerkey (Mediatek)
247 {"power_on", 17}, // aliasReasons to cold,powerkey
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700248 {"Reboot", 18},
249 {"rtc", 19},
250 {"edl", 20},
251 {"oem_pon1", 21},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700252 {"oem_powerkey", 22}, // aliasReasons to cold,powerkey
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700253 {"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},
Mark Salyzyn274b5442018-08-07 08:45:13 -0700275 {"shutdown,", 45}, // Trailing comma is intentional. Do NOT use.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700276 {"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},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700284 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700285 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700286 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700287 {"bootloader", 55},
288 {"cold", 56},
289 {"hard", 57},
290 {"warm", 58},
Mark Salyzyn15199252018-03-16 09:26:05 -0700291 {"reboot,kernel_power_off_charging__reboot_system", 59}, // Can not happen
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700292 {"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},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700300 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700301 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700302 {"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
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700307 {"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)
James Hawkins34073b52017-10-17 15:53:27 -0700316 {"reboot,by_key", 84},
317 {"reboot,longkey", 85},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700318 {"reboot,2sec", 86}, // Deprecate in two years, replaced with cold,rtc,2sec
Mark Salyzync89f9da2017-10-24 15:35:34 -0700319 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700320 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
321 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn75046892018-05-03 13:11:15 -0700322 {"reboot,rescueparty", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800323 {"charge", 91},
324 {"oem_tz_crash", 92},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700325 {"uvlo", 93}, // aliasReasons to reboot,undervoltage
James Hawkins74b17582017-11-20 14:13:41 -0800326 {"oem_ps_hold", 94},
327 {"abnormal_reset", 95},
328 {"oemerr_unknown", 96},
329 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800330 {"watchdog_apps_bite", 98},
331 {"xpu_err", 99},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700332 {"power_on_usb", 100}, // aliasReasons to cold,charger
James Hawkinsf4444f02017-11-30 15:01:40 -0800333 {"watchdog_rpm", 101},
334 {"watchdog_nonsec", 102},
335 {"watchdog_apps_bark", 103},
336 {"reboot_dmverity_corrupted", 104},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700337 {"reboot_smpl", 105}, // aliasReasons to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800338 {"watchdog_sdi_apps_reset", 106},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700339 {"smpl", 107}, // aliasReasons to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800340 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800341 {"reboot_normal", 109},
342 {"oem_lpass_cfg", 110},
343 {"oem_xpu_ns_error", 111},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700344 {"power_key_press", 112}, // aliasReasons to cold,powerkey
James Hawkinse2c27242017-12-18 13:40:27 -0800345 {"hardware_reset", 113},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700346 {"reboot_by_powerkey", 114}, // aliasReasons to cold,powerkey (is this correct?)
James Hawkinse2c27242017-12-18 13:40:27 -0800347 {"reboot_verity", 115},
348 {"oem_rpm_undef_error", 116},
349 {"oem_crash_on_the_lk", 117},
350 {"oem_rpm_reset", 118},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700351 {"reboot,powerloss", 119},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700352 {"reboot,undervoltage", 120},
James Hawkinse2c27242017-12-18 13:40:27 -0800353 {"factory_cable", 121},
354 {"oem_ar6320_failed_to_powerup", 122},
355 {"watchdog_rpm_bite", 123},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700356 {"power_on_cable", 124}, // aliasReasons to cold,charger
James Hawkinse2c27242017-12-18 13:40:27 -0800357 {"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},
James Hawkinsb607dae2018-01-05 14:42:55 -0800367 {"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},
James Hawkins79a4ee22018-01-26 14:31:04 -0800376 {"reboot_recovery_mode", 144},
377 {"oem_sdi_err_fatal", 145},
378 {"pmic_watchdog", 146},
379 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700380 {"cold,charger", 148},
381 {"cold,rtc", 149},
Mark Salyzyn4e7acf72018-03-16 11:00:26 -0700382 {"cold,rtc,2sec", 150}, // Mediatek
383 {"reboot,tool", 151}, // Mediatek
384 {"reboot,wdt", 152}, // Mediatek
385 {"reboot,unknown", 153}, // Mediatek
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700386 {"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},
Mark Salyzynafd66f22018-03-19 15:16:29 -0700393 {"kernel_panic,sysrq,livelock,alarm", 161}, // llkd
394 {"kernel_panic,sysrq,livelock,driver", 162}, // llkd
395 {"kernel_panic,sysrq,livelock,zombie", 163}, // llkd
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700396 {"kernel_panic,modem", 164},
397 {"kernel_panic,adsp", 165},
398 {"kernel_panic,dsps", 166},
399 {"kernel_panic,wcnss", 167},
Mark Salyzyn78e54fd2018-06-08 10:19:16 -0700400 {"kernel_panic,_sde_encoder_phys_cmd_handle_ppdone_timeout", 168},
Mark Salyzyn6fc08292019-03-11 10:06:36 -0700401 {"recovery,quiescent", 169},
402 {"reboot,quiescent", 170},
Jone Choud51036d2019-03-20 19:38:05 +0800403 {"reboot,rtc", 171},
404 {"reboot,dm-verity_device_corrupted", 172},
405 {"reboot,dm-verity_enforcing", 173},
406 {"reboot,keys_clear", 174},
Jone Chou446d6c62019-04-18 15:43:26 +0800407 {"reboot,pmic_off_fault,.*", 175},
408 {"reboot,pmic_off_s3rst,.*", 176},
409 {"reboot,pmic_off_other,.*", 177},
Mark Salyzyn65d8b9b2019-05-23 09:07:54 -0700410 {"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},
Mark Salyzyn8d1be802019-05-21 10:47:55 -0700415 {"reboot,unknown[0-9]*", 183},
Jone Choub9a80332019-06-10 23:24:39 +0800416 {"reboot,longkey,.*", 184},
Tom Cherrya76bfb22019-09-18 09:41:36 -0700417 {"reboot,boringssl-self-check-failed", 185},
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000418 {"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},
Jim Kayeb7386a62020-07-01 16:57:01 -0700423 {"reboot,forcedsilent", 191},
424 {"reboot,forcednonsilent", 192},
Lisa Liu82674de2021-03-16 17:43:32 +0800425 {"reboot,thermal,tj", 193},
Howie Changd5f24c52021-08-30 17:27:01 +0800426 {"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},
Jason Chiu17251022022-06-28 21:17:49 +0800450 {"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},
Jone Chou11160ed2022-07-14 00:24:52 +0800455 {"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},
David Tracy691d8052023-03-23 17:51:11 -0700462 {"reboot,ota,.*", 230},
463 {"reboot,periodic,.*", 231},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800464};
465
466// Converts a string value representing the reason the system booted to an
467// integer representation. This is necessary for logging the boot_reason metric
468// via Tron, which does not accept non-integer buckets in histograms.
469int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800470 auto mapping = kBootReasonMap.find(boot_reason);
471 if (mapping != kBootReasonMap.end()) {
472 return mapping->second;
473 }
474
James Hawkins25f71222017-10-10 16:37:05 -0700475 if (boot_reason.empty()) {
476 return kEmptyBootReason;
477 }
478
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700479 for (const auto& [match, id] : kBootReasonMap) {
480 // Regex matches as a minimum require either [, \ or * to be present.
481 if (match.find_first_of("[\\*") == match.npos) continue;
482 // enforce match from beginning to end
483 auto exact = match;
484 if (exact[0] != '^') exact = "^" + exact;
485 if (exact[exact.size() - 1] != '$') exact = exact + "$";
486 if (std::regex_search(boot_reason, std::regex(exact))) return id;
487 }
488
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800489 LOG(INFO) << "Unknown boot reason: " << boot_reason;
490 return kUnknownBootReason;
491}
492
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700493// Canonical list of supported primary reboot reasons.
494const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700495 // clang-format off
496 // kernel
497 "watchdog",
498 "kernel_panic",
499 // strong
500 "recovery", // Should not happen from ro.boot.bootreason
501 "bootloader", // Should not happen from ro.boot.bootreason
502 // blunt
503 "cold",
504 "hard",
505 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700506 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700507 "shutdown", // Can not happen from ro.boot.bootreason
508 "reboot", // Default catch-all for anything unknown
509 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700510};
511
512// Returns true if the supplied reason prefix is considered detailed enough.
513bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700514 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700515 if (s == "cold") break;
516 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800517 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700518 return true;
519 }
520 }
521 return false;
522}
523
524// Returns true if the supplied reason prefix is associated with the kernel.
525bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700526 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700527 if (s == "recovery") break;
528 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800529 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700530 return true;
531 }
532 }
533 return false;
534}
535
536// Returns true if the supplied reason prefix is considered known.
537bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700538 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700539 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800540 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700541 return true;
542 }
543 }
544 return false;
545}
546
547// If the reboot reason should be improved, report true if is too blunt.
548bool isBluntRebootReason(const std::string& r) {
549 if (isStrongRebootReason(r)) return false;
550
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700551 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700552
553 size_t pos = 0;
554 while ((pos = r.find(',', pos)) != std::string::npos) {
555 ++pos;
556 std::string next(r.substr(pos));
557 if (next.length() == 0) break;
558 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700559 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
560 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700561 }
562 return true;
563}
564
Mark Salyzyn64610892017-09-18 10:41:14 -0700565bool readPstoreConsole(std::string& console) {
566 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
567 return true;
568 }
569 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
570}
571
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700572// Implement a variant of std::string::rfind that is resilient to errors in
573// the data stream being inspected.
574class pstoreConsole {
575 private:
576 const size_t kBitErrorRate = 8; // number of bits per error
577 const std::string& console;
578
579 // Number of bits that differ between the two arguments l and r.
580 // Returns zero if the values for l and r are identical.
581 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
582
583 // A string comparison function, reports the number of errors discovered
584 // in the match to a maximum of the bitLength / kBitErrorRate, at that
585 // point returning npos to indicate match is too poor.
586 //
587 // Since called in rfind which works backwards, expect cache locality will
588 // help if we check in reverse here as well for performance.
589 //
590 // Assumption: l (from console.c_str() + pos) is long enough to house
591 // _r.length(), checked in rfind caller below.
592 //
593 size_t numError(size_t pos, const std::string& _r) const {
594 const char* l = console.c_str() + pos;
595 const char* r = _r.c_str();
596 size_t n = _r.length();
597 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
598 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
599 size_t count = 0;
600 n = 0;
601 do {
602 // individual character bit error rate > threshold + slop
603 size_t num = numError(*--le, *--re);
604 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
605 // total bit error rate > threshold + slop
606 count += num;
607 ++n;
608 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
609 return std::string::npos;
610 }
611 } while (le != reinterpret_cast<const uint8_t*>(l));
612 return count;
613 }
614
615 public:
616 explicit pstoreConsole(const std::string& console) : console(console) {}
617 // scope of argument must be equal to or greater than scope of pstoreConsole
618 explicit pstoreConsole(const std::string&& console) = delete;
619 explicit pstoreConsole(std::string&& console) = delete;
620
621 // Our implementation of rfind, use exact match first, then resort to fuzzy.
622 size_t rfind(const std::string& needle) const {
623 size_t pos = console.rfind(needle); // exact match?
624 if (pos != std::string::npos) return pos;
625
626 // Check to make sure needle fits in console string.
627 pos = console.length();
628 if (needle.length() > pos) return std::string::npos;
629 pos -= needle.length();
630 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800631 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700632 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800633 if (pos == 0) break;
634 --pos;
635 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700636 return std::string::npos;
637 }
638
639 // Our implementation of find, use only fuzzy match.
640 size_t find(const std::string& needle, size_t start = 0) const {
641 // Check to make sure needle fits in console string.
642 if (needle.length() > console.length()) return std::string::npos;
643 const size_t last_pos = console.length() - needle.length();
644 // fuzzy match to maximum kBitErrorRate
645 for (size_t pos = start; pos <= last_pos; ++pos) {
646 if (numError(pos, needle) != std::string::npos) return pos;
647 }
648 return std::string::npos;
649 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700650
651 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700652};
653
654// If bit error match to needle, correct it.
655// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700656bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700657 bool corrected = false;
658 if (reason.length() < needle.length()) return corrected;
659 const pstoreConsole console(reason);
660 const size_t last_pos = reason.length() - needle.length();
661 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
662 pos = console.find(needle, pos);
663 if (pos == std::string::npos) break;
664
665 // exact match has no malice
666 if (needle == reason.substr(pos, needle.length())) continue;
667
668 corrected = true;
669 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
670 }
671 return corrected;
672}
673
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700674// If bit error match to needle, correct it.
675// Return true if any corrections were discovered and applied.
676// Try again if we can replace underline with spaces.
677bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
678 bool corrected = correctForBitError(reason, needle);
679 std::string _needle(needle);
680 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
681 [](char c) { return (c == '_') ? ' ' : c; });
682 if (needle != _needle) {
683 corrected |= correctForBitError(reason, _needle);
684 }
685 return corrected;
686}
687
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700688// Converts a string value representing the reason the system booted to a
689// string complying with Android system standard reason.
690void transformReason(std::string& reason) {
691 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
692 std::transform(reason.begin(), reason.end(), reason.begin(),
693 [](char c) { return ::isblank(c) ? '_' : c; });
694 std::transform(reason.begin(), reason.end(), reason.begin(),
695 [](char c) { return ::isprint(c) ? c : '?'; });
696}
697
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700698// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
699// kernel_panic,<subreason>.
700//
701// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
702// or unprintable character terminated subreason, pos is supplied just beyond
703// first quote. if quoted false, pull out and correct newline (\n) or
704// unprintable character terminated subreason.
705//
706// Heuristics to find termination is painted into a corner:
707
708// single bit error for quote ' that we can block. It is acceptable for
709// the others 7, g in reason. 2/9 chance will miss the terminating quote,
710// but there is always the terminating newline that usually immediately
711// follows to fortify our chances.
712bool likely_single_quote(char c) {
713 switch (static_cast<uint8_t>(c)) {
714 case '\'': // '\''
715 case '\'' ^ 0x01: // '&'
716 case '\'' ^ 0x02: // '%'
717 case '\'' ^ 0x04: // '#'
718 case '\'' ^ 0x08: // '/'
719 return true;
720 case '\'' ^ 0x10: // '7'
721 break;
722 case '\'' ^ 0x20: // '\a' (unprintable)
723 return true;
724 case '\'' ^ 0x40: // 'g'
725 break;
726 case '\'' ^ 0x80: // 0xA7 (unprintable)
727 return true;
728 }
729 return false;
730}
731
732// ::isprint(c) and likely_space() will prevent us from being called for
733// fundamentally printable entries, except for '\r' and '\b'.
734//
735// Except for * and J, single bit errors for \n, all others are non-
736// printable so easy catch. It is _acceptable_ for *, J or j to exist in
737// the reason string, so 2/9 chance we will miss the terminating newline.
738//
739// NB: J might not be acceptable, except if at the beginning or preceded
740// with a space, '(' or any of the quotes and their BER aliases.
741// NB: * might not be acceptable, except if at the beginning or preceded
742// with a space, another *, or any of the quotes or their BER aliases.
743//
744// To reduce the chances to closer to 1/9 is too complicated for the gain.
745bool likely_newline(char c) {
746 switch (static_cast<uint8_t>(c)) {
747 case '\n': // '\n' (unprintable)
748 case '\n' ^ 0x01: // '\r' (unprintable)
749 case '\n' ^ 0x02: // '\b' (unprintable)
750 case '\n' ^ 0x04: // 0x0E (unprintable)
751 case '\n' ^ 0x08: // 0x02 (unprintable)
752 case '\n' ^ 0x10: // 0x1A (unprintable)
753 return true;
754 case '\n' ^ 0x20: // '*'
755 case '\n' ^ 0x40: // 'J'
756 break;
757 case '\n' ^ 0x80: // 0x8A (unprintable)
758 return true;
759 }
760 return false;
761}
762
763// ::isprint(c) will prevent us from being called for all the printable
764// matches below. If we let unprintables through because of this, they
765// get converted to underscore (_) by the validation phase.
766bool likely_space(char c) {
767 switch (static_cast<uint8_t>(c)) {
768 case ' ': // ' '
769 case ' ' ^ 0x01: // '!'
770 case ' ' ^ 0x02: // '"'
771 case ' ' ^ 0x04: // '$'
772 case ' ' ^ 0x08: // '('
773 case ' ' ^ 0x10: // '0'
774 case ' ' ^ 0x20: // '\0' (unprintable)
775 case ' ' ^ 0x40: // 'P'
776 case ' ' ^ 0x80: // 0xA0 (unprintable)
777 case '\t': // '\t'
778 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
779 case '\t' ^ 0x02: // '\v' (unprintable)
780 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
781 case '\t' ^ 0x08: // 0x01 (unprintable)
782 case '\t' ^ 0x10: // 0x19 (unprintable)
783 case '\t' ^ 0x20: // ')'
784 case '\t' ^ 0x40: // '1'
785 case '\t' ^ 0x80: // 0x89 (unprintable)
786 return true;
787 }
788 return false;
789}
790
791std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700792 static constexpr size_t max_reason_length = 256;
793
794 std::string subReason(content.substr(pos, max_reason_length));
795 // Correct against any known strings that Bit Error Match
796 for (const auto& s : knownReasons) {
797 correctForBitErrorOrUnderline(subReason, s);
798 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700799 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700800 for (const auto& m : kBootReasonMap) {
801 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700802 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700803 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
804 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700805 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700806 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700807 correctForBitErrorOrUnderline(subReason,
808 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
809 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
810 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700811 }
812 }
813 for (pos = 0; pos < subReason.length(); ++pos) {
814 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700815 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
816 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700817 subReason.erase(pos);
818 break;
819 }
820 }
821 transformReason(subReason);
822 return subReason;
823}
824
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700825bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700826 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700827 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
828 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700829 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700830 // Invented for Android to allow daemons that specifically trigger sysrq
831 // to communicate more accurate boot subreasons via last console messages.
832 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
833 auto pos = console.rfind(sysrqSubreason);
834 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700835 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700836 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700837 return true;
838 }
839 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
840 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700841 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700842 return true;
843 }
844 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700845 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700846 return true;
847 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700848
849 std::string panic("Kernel panic - not syncing: ");
850 auto pos = console.rfind(panic);
851 if (pos != std::string::npos) {
852 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
853 {"Out of memory", "oom"},
854 {"out of memory", "oom"},
855 {"Oh boy, that early out of memory", "oom"}, // omg
856 {"BUG!", "bug"},
857 {"hung_task: blocked tasks", "hung"},
858 {"audit: ", "audit"},
859 {"scheduling while atomic", "atomic"},
860 {"Attempted to kill init!", "init"},
861 {"Requested init", "init"},
862 {"No working init", "init"},
863 {"Could not decompress init", "init"},
864 {"RCU Stall", "hung,rcu"},
865 {"stack-protector", "stack"},
866 {"kernel stack overflow", "stack"},
867 {"Corrupt kernel stack", "stack"},
868 {"low stack detected", "stack"},
869 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700870 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
871 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
872 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
873 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700874 };
875
876 ret = "kernel_panic";
877 for (auto& s : panicReasons) {
878 if (console.find(panic + s.first, pos) != std::string::npos) {
879 ret += "," + s.second;
880 return true;
881 }
882 }
883 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
884 if (reason.length() > 3) {
885 ret += "," + reason;
886 }
887 return true;
888 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700889 return false;
890}
891
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700892bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
893 return addKernelPanicSubReason(pstoreConsole(content), ret);
894}
895
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700896const char system_reboot_reason_property[] = "sys.boot.reason";
897const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
Mark Salyzynee016ce2019-05-23 10:00:34 -0700898const char last_reboot_reason_file[] = LAST_REBOOT_REASON_FILE;
Mark Salyzynadc433d2018-06-05 08:17:35 -0700899const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700900constexpr size_t history_reboot_reason_size = 4;
901const char history_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY ".history";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700902const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
903
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700904// Land system_boot_reason into system_reboot_reason_property.
905// Shift system_boot_reason into history_reboot_reason_property.
906void BootReasonAddToHistory(const std::string& system_boot_reason) {
907 if (system_boot_reason.empty()) return;
908 LOG(INFO) << "Canonical boot reason: " << system_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800909 auto old_system_boot_reason = android::base::GetProperty(system_reboot_reason_property, "");
910 if (!android::base::SetProperty(system_reboot_reason_property, system_boot_reason)) {
911 android::base::SetProperty(system_reboot_reason_property,
912 system_boot_reason.substr(0, PROPERTY_VALUE_MAX - 1));
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700913 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800914 auto reason_history =
915 android::base::Split(android::base::GetProperty(history_reboot_reason_property, ""), "\n");
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700916 static auto mark = time(nullptr);
917 auto mark_str = std::string(",") + std::to_string(mark);
918 auto marked_system_boot_reason = system_boot_reason + mark_str;
919 if (!reason_history.empty()) {
920 // delete any entries that we just wrote in a previous
921 // call and leveraging duplicate line handling
922 auto last = old_system_boot_reason + mark_str;
923 // trim the list to (history_reboot_reason_size - 1)
924 ssize_t max = history_reboot_reason_size;
925 for (auto it = reason_history.begin(); it != reason_history.end();) {
926 if (it->empty() || (last == *it) || (marked_system_boot_reason == *it) || (--max <= 0)) {
927 it = reason_history.erase(it);
928 } else {
929 last = *it;
930 ++it;
931 }
932 }
933 }
934 // insert at the front, concatenating mark (<epoch time>) detail to the value.
935 reason_history.insert(reason_history.begin(), marked_system_boot_reason);
936 // If the property string is too long ( > PROPERTY_VALUE_MAX)
937 // we get an error, so trim out last entry and try again.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800938 while (!android::base::SetProperty(history_reboot_reason_property,
939 android::base::Join(reason_history, '\n'))) {
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700940 auto it = std::prev(reason_history.end());
941 if (it == reason_history.end()) break;
942 reason_history.erase(it);
943 }
944}
945
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700946// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
947std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800948 auto ret = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700949 std::string reason(boot_reason);
950 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
951 if (reason == ret) ret = "";
952
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700953 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700954
955 // Is the current system boot reason sys.boot.reason valid?
956 if (!isKnownRebootReason(ret)) ret = "";
957
958 if (ret == "") {
959 // Is the bootloader boot reason ro.boot.bootreason known?
960 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700961 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700962 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700963 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700964 if (r == s) {
965 if (isBluntRebootReason(s)) {
966 blunt = s;
967 } else {
968 ret = s;
969 break;
970 }
971 }
972 }
973 if (ret == "") ret = blunt;
974 if (ret != "") break;
975 }
976 }
977
978 if (ret == "") {
979 // A series of checks to take some officially unsupported reasons
980 // reported by the bootloader and find some logical and canonical
981 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700982 // to behave and follow our CTS standards.
983 //
984 // first member is the output
985 // second member is an unanchored regex for an alias
986 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700987 // If output has a prefix of <bang> '!', we do not use it as a
988 // match needle (and drop the <bang> prefix when landing in output),
989 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700990 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700991 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700992 {"watchdog", "wdog"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700993 {"kernel_panic", "panic"},
994 {"shutdown,thermal", "thermal"},
995 {"warm,s3_wakeup", "s3_wakeup"},
996 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700997 {"cold,charger", "usb|power_on_cable"},
998 {"cold,powerkey", "powerkey|power_key|PowerKey|power_on"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700999 {"cold,rtc", "rtc"},
Mark Salyzyn186f6762018-03-16 11:00:26 -07001000 {"cold,rtc,2sec", "2sec_reboot"},
1001 {"!warm", "wdt_by_pass_pwk"}, // change flavour of blunt
1002 {"!reboot", "^wdt$"}, // change flavour of blunt
1003 {"reboot,tool", "tool_by_pass_pwk"},
Mark Salyzyn88d1b4a2018-06-07 09:39:24 -07001004 {"!reboot,longkey", "reboot_longkey"},
1005 {"!reboot,longkey", "kpdpwr"},
Mark Salyzynec7bafe2018-09-26 08:01:04 -07001006 {"!reboot,undervoltage", "uvlo"},
Mark Salyzynf62983a2018-09-26 09:55:25 -07001007 {"!reboot,powerloss", "smpl"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001008 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001009 };
1010
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001011 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -07001012 size_t firstHasNot = s.first[0] == '!';
1013 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001014 ret = s.first;
1015 break;
1016 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -07001017 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -07001018 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001019 break;
1020 }
1021 }
1022 }
1023
1024 // If watchdog is the reason, see if there is a security angle?
1025 if (ret == "watchdog") {
1026 if (reason.find("sec") != std::string::npos) {
1027 ret += ",security";
1028 }
1029 }
1030
Mark Salyzyn64610892017-09-18 10:41:14 -07001031 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001032 // Check to see if last klog has some refinement hints.
1033 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -07001034 if (readPstoreConsole(content)) {
1035 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001036 }
Mark Salyzyn64610892017-09-18 10:41:14 -07001037 } else if (isBluntRebootReason(ret)) {
1038 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001039
Mark Salyzyn64610892017-09-18 10:41:14 -07001040 // Check to see if last klog has some refinement hints.
1041 std::string content;
1042 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001043 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -07001044 // The toybox reboot command used directly (unlikely)? But also
1045 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001046 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -07001047 ret = "shutdown"; // Still too blunt, but more accurate.
1048 // ToDo: init should record the shutdown reason to kernel messages ala:
1049 // init: shutdown system with command 'last_reboot_reason'
1050 // so that if pstore has persistence we can get some details
1051 // that could be missing in last_reboot_reason_property.
1052 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001053
Mark Salyzyn64610892017-09-18 10:41:14 -07001054 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001055 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -07001056 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -07001057 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -07001058 if (subReason != "") { // Will not land "reboot" as that is too blunt.
1059 if (isKernelRebootReason(subReason)) {
1060 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -07001061 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -07001062 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -07001063 } else {
1064 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -07001065 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001066 }
Mark Salyzyn15199252018-03-16 09:26:05 -07001067 // Some bootloaders shutdown results record in last kernel message.
1068 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
1069 ret = "shutdown";
1070 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001071 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001072
Mark Salyzyn64610892017-09-18 10:41:14 -07001073 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001074 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -07001075 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001076 ((console.rfind("Power held for ") != std::string::npos) ||
1077 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -07001078 ret = "cold";
1079 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001080 }
1081
Elliott Hughes50a24eb2018-06-14 10:59:09 -07001082 // TODO: use the HAL to get battery level (http://b/77725702).
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001083
1084 // Is there a controlled shutdown hint in last_reboot_reason_property?
1085 if (isBluntRebootReason(ret)) {
1086 // Content buffer no longer will have console data. Beware if more
1087 // checks added below, that depend on parsing console content.
Mark Salyzynee016ce2019-05-23 10:00:34 -07001088 if (!android::base::ReadFileToString(last_reboot_reason_file, &content)) {
1089 content = android::base::GetProperty(last_reboot_reason_property, "");
1090 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -07001091 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001092
Mark Salyzyn62909822017-10-09 09:27:16 -07001093 // Anything in last is better than 'super-blunt' reboot or shutdown.
1094 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
1095 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001096 }
1097 }
1098
1099 // Other System Health HAL reasons?
1100
1101 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
1102 // possibly offer hardware-specific clues from the PMIC.
1103 }
1104
1105 // If unknown left over from above, make it "reboot,<boot_reason>"
1106 if (ret == "") {
1107 ret = "reboot";
1108 if (android::base::StartsWith(reason, "reboot")) {
1109 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -07001110 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001111 reason = reason.substr(1);
1112 }
1113 }
1114 if (reason != "") {
1115 ret += ",";
1116 ret += reason;
1117 }
1118 }
1119
1120 LOG(INFO) << "Canonical boot reason: " << ret;
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001121 return ret;
1122}
1123
James Hawkinsb9cf7712016-04-08 15:32:19 -07001124// Returns the appropriate metric key prefix for the boot_complete metric such
1125// that boot metrics after a system update are labeled as ota_boot_complete;
1126// otherwise, they are labeled as boot_complete. This method encapsulates the
1127// bookkeeping required to track when a system update has occurred by storing
1128// the UTC timestamp of the system build date and comparing against the current
1129// system build date.
1130std::string CalculateBootCompletePrefix() {
1131 static const std::string kBuildDateKey = "build_date";
1132 std::string boot_complete_prefix = "boot_complete";
1133
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001134 auto build_date_str = android::base::GetProperty("ro.build.date.utc", "");
James Hawkins4dded612016-07-28 11:50:23 -07001135 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -07001136 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -07001137 return std::string();
1138 }
James Hawkinsb9cf7712016-04-08 15:32:19 -07001139
1140 BootEventRecordStore boot_event_store;
1141 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -07001142 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1143 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1144 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001145 BootReasonAddToHistory("reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001146 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001147 boot_complete_prefix = "ota_" + boot_complete_prefix;
1148 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001149 BootReasonAddToHistory("reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001150 }
1151
1152 return boot_complete_prefix;
1153}
1154
James Hawkinsef0a0902017-01-06 14:38:23 -08001155// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001156void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001157 auto value = android::base::GetProperty(property, "");
James Hawkinsef0a0902017-01-06 14:38:23 -08001158
James Hawkins27c05222017-01-26 11:55:44 -08001159 int32_t time_in_ms;
1160 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001161 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1162 }
1163}
1164
James Hawkins1bfcaec2017-05-19 14:27:27 -07001165// A map from bootloader timing stage to the time that stage took during boot.
1166typedef std::map<std::string, int32_t> BootloaderTimingMap;
1167
1168// Returns a mapping from bootloader stage names to the time those stages
1169// took to boot.
1170const BootloaderTimingMap GetBootLoaderTimings() {
1171 BootloaderTimingMap timings;
1172
1173 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1174 // where timeN is in milliseconds.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001175 auto value = android::base::GetProperty("ro.boot.boottime", "");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001176 if (value.empty()) {
1177 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001178 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001179 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001180
1181 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001182 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001183 // |stageTiming| is of the form 'stage:time'.
1184 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001185 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001186
Mark Salyzyn7c721162019-02-08 10:41:15 -08001187 if (stageTimingValues.size() < 2) continue;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001188 std::string stageName = stageTimingValues[0];
1189 int32_t time_ms;
1190 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001191 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001192 }
1193 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001194
James Hawkins1bfcaec2017-05-19 14:27:27 -07001195 return timings;
1196}
1197
Tej Singh4eacd382018-01-25 17:59:57 -08001198// Returns the total bootloader boot time from the ro.boot.boottime system property.
1199int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1200 int32_t total_time = 0;
1201 for (const auto& timing : bootloader_timings) {
1202 total_time += timing.second;
1203 }
1204
1205 return total_time;
1206}
1207
James Hawkins1bfcaec2017-05-19 14:27:27 -07001208// Parses and records the set of bootloader stages and associated boot times
1209// from the ro.boot.boottime system property.
1210void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1211 const BootloaderTimingMap& bootloader_timings) {
1212 int32_t total_time = 0;
1213 for (const auto& timing : bootloader_timings) {
1214 total_time += timing.second;
1215 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1216 }
1217
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001218 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001219}
1220
Tej Singh4eacd382018-01-25 17:59:57 -08001221// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001222// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001223std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1224 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001225 int32_t bootloader_time_ms = 0;
1226
1227 for (const auto& timing : bootloader_timings) {
1228 if (timing.first.compare("SW") != 0) {
1229 bootloader_time_ms += timing.second;
1230 }
1231 }
1232
1233 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001234 return bootloader_duration + uptime;
1235}
1236
1237// Records the closest estimation to the absolute device boot time in seconds.
1238// i.e. from power on to boot_complete, including bootloader times.
1239void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1240 std::chrono::milliseconds absolute_total) {
1241 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1242 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1243}
1244
1245// Logs the total boot time and reason to statsd.
1246void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1247 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1248 double time_since_last_boot_sec) {
Wei Wang699e3422019-05-22 09:46:02 -07001249 auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "<EMPTY>");
1250 auto system_reason = android::base::GetProperty(system_reboot_reason_property, "<EMPTY>");
Tej Singh4eacd382018-01-25 17:59:57 -08001251 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1252 system_reason.c_str(), end_time.count(), total_duration.count(),
1253 (int64_t)bootloader_duration_ms,
1254 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001255}
1256
Tej Singhfe3e7622018-02-06 15:57:38 -08001257void SetSystemBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001258 const auto bootloader_boot_reason =
1259 android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001260 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1261 // Record the scrubbed system_boot_reason to the property
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001262 BootReasonAddToHistory(system_boot_reason);
Mark Salyzynadc433d2018-06-05 08:17:35 -07001263 // Shift last_reboot_reason_property to last_last_reboot_reason_property
Mark Salyzynee016ce2019-05-23 10:00:34 -07001264 std::string last_boot_reason;
1265 if (!android::base::ReadFileToString(last_reboot_reason_file, &last_boot_reason)) {
Nikita Ioffe49062f32020-03-31 23:47:45 +01001266 PLOG(ERROR) << "Failed to read " << last_reboot_reason_file;
Mark Salyzynee016ce2019-05-23 10:00:34 -07001267 last_boot_reason = android::base::GetProperty(last_reboot_reason_property, "");
Nikita Ioffe49062f32020-03-31 23:47:45 +01001268 LOG(INFO) << "Value of " << last_reboot_reason_property << " : " << last_boot_reason;
1269 } else {
1270 LOG(INFO) << "Last reboot reason read from " << last_reboot_reason_file << " : "
1271 << last_boot_reason << ". Last reboot reason read from "
1272 << last_reboot_reason_property << " : "
1273 << android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzynee016ce2019-05-23 10:00:34 -07001274 }
Mark Salyzynadc433d2018-06-05 08:17:35 -07001275 if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1276 last_boot_reason = system_boot_reason;
1277 } else {
1278 transformReason(last_boot_reason);
1279 }
Nikita Ioffe49062f32020-03-31 23:47:45 +01001280 LOG(INFO) << "Normalized last reboot reason : " << last_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001281 android::base::SetProperty(last_last_reboot_reason_property, last_boot_reason);
1282 android::base::SetProperty(last_reboot_reason_property, "");
Nikita Ioffe49062f32020-03-31 23:47:45 +01001283 if (unlink(last_reboot_reason_file) != 0) {
1284 PLOG(ERROR) << "Failed to unlink " << last_reboot_reason_file;
1285 }
Tej Singhfe3e7622018-02-06 15:57:38 -08001286}
1287
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001288// Gets the boot time offset. This is useful when Android is running in a
1289// container, because the boot_clock is not reset when Android reboots.
1290std::chrono::nanoseconds GetBootTimeOffset() {
1291 static const int64_t boottime_offset =
1292 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1293 return std::chrono::nanoseconds(boottime_offset);
1294}
1295
1296// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1297// clock.
1298android::base::boot_clock::duration GetUptime() {
1299 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1300}
1301
Eric Biggersd76e4e02022-09-26 18:54:10 +00001302// Records several metrics related to the time it takes to boot the device.
James Hawkinsc08e9962016-03-11 14:59:50 -08001303void RecordBootComplete() {
1304 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001305 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001306
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001307 auto uptime_ns = GetUptime();
1308 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001309 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001310 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001311
1312 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1313 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001314 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001315 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001316 }
1317
1318 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001319
James Hawkinsb9cf7712016-04-08 15:32:19 -07001320 // The boot_complete metric has two variants: boot_complete and
1321 // ota_boot_complete. The latter signifies that the device is booting after
1322 // a system update.
1323 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001324 if (boot_complete_prefix.empty()) {
1325 // The system is hosed because the build date property could not be read.
1326 return;
1327 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001328
Eric Biggersd76e4e02022-09-26 18:54:10 +00001329 // The *_no_encryption events are emitted unconditionally, since they are left
1330 // over from a time when encryption meant "full-disk encryption". But Android
1331 // now always uses file-based encryption instead of full-disk encryption. At
1332 // some point, these misleading and redundant events should be removed.
1333 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1334 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001335
Eric Biggersd76e4e02022-09-26 18:54:10 +00001336 // Record the total time from device startup to boot complete. Note: we are
1337 // recording seconds here even though the field in statsd atom specifies
Yifan Hong08ba15d2021-03-03 16:32:52 -08001338 // milliseconds.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001339 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001340
1341 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
Mark Salyzyn10377df2019-03-27 08:10:41 -07001342 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.first_stage");
James Hawkinsef0a0902017-01-06 14:38:23 -08001343 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1344 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001345
James Hawkins1bfcaec2017-05-19 14:27:27 -07001346 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001347 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001348 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1349
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001350 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001351 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1352 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1353
1354 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1355 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1356
1357 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1358 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001359}
1360
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001361// Records the boot_reason metric by querying the ro.boot.bootreason system
1362// property.
1363void RecordBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001364 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
James Hawkins25f71222017-10-10 16:37:05 -07001365
1366 if (reason.empty()) {
Howard Rofe0b3892020-01-31 17:37:32 -08001367 // TODO(b/148575354): Replace with statsd.
James Hawkins25f71222017-10-10 16:37:05 -07001368 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1369 // (and not corruption anywhere else in the reporting pipeline).
Howard Rofe0b3892020-01-31 17:37:32 -08001370 // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1371 // android::metricslogger::FIELD_PLATFORM_REASON,
1372 // "<EMPTY>");
James Hawkins25f71222017-10-10 16:37:05 -07001373 } else {
Howard Rofe0b3892020-01-31 17:37:32 -08001374 // TODO(b/148575354): Replace with statsd.
1375 // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1376 // android::metricslogger::FIELD_PLATFORM_REASON,
1377 // reason);
James Hawkins25f71222017-10-10 16:37:05 -07001378 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001379
1380 // Log the raw bootloader_boot_reason property value.
1381 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001382 BootEventRecordStore boot_event_store;
1383 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001384
1385 // Log the scrubbed system_boot_reason.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001386 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001387 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1388 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1389
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001390 if (reason == "") {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001391 android::base::SetProperty(bootloader_reboot_reason_property, system_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001392 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001393}
1394
James Hawkins500d7152016-02-16 15:05:54 -08001395// Records two metrics related to the user resetting a device: the time at
1396// which the device is reset, and the time since the user last reset the
1397// device. The former is only set once per-factory reset.
1398void RecordFactoryReset() {
1399 BootEventRecordStore boot_event_store;
1400 BootEventRecordStore::BootEventRecord record;
1401
1402 time_t current_time_utc = time(nullptr);
1403
James Hawkins0660b302016-03-08 16:18:15 -08001404 if (current_time_utc < 0) {
1405 // UMA does not display negative values in buckets, so convert to positive.
Keun young Park606af6d2020-01-15 10:09:03 -08001406 // Logging via BootEventRecordStore.
1407 android::util::stats_write(
1408 static_cast<int32_t>(android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED),
1409 static_cast<int32_t>(
1410 android::util::BOOT_TIME_EVENT_ERROR_CODE__EVENT__FACTORY_RESET_CURRENT_TIME_FAILURE),
1411 static_cast<int32_t>(std::abs(current_time_utc)));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001412
James Hawkins9aec9262017-01-31 11:42:24 -08001413 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001414 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001415 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1416 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001417 return;
1418 } else {
Keun young Park606af6d2020-01-15 10:09:03 -08001419 android::util::stats_write(
1420 static_cast<int32_t>(android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED),
1421 static_cast<int32_t>(
1422 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_CURRENT_TIME),
1423 static_cast<int64_t>(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001424
James Hawkins9aec9262017-01-31 11:42:24 -08001425 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001426 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001427 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001428 }
1429
James Hawkins500d7152016-02-16 15:05:54 -08001430 // The factory_reset boot event does not exist after the device is reset, so
1431 // use this signal to mark the time of the factory reset.
1432 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1433 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001434
1435 // Don't log the time_since_factory_reset until some time has elapsed.
1436 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001437 return;
1438 }
1439
1440 // Calculate and record the difference in time between now and the
1441 // factory_reset time.
1442 time_t factory_reset_utc = record.second;
Keun young Park606af6d2020-01-15 10:09:03 -08001443 android::util::stats_write(
1444 static_cast<int32_t>(android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED),
1445 static_cast<int32_t>(
1446 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RECORD_VALUE),
1447 static_cast<int64_t>(factory_reset_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001448
James Hawkins9aec9262017-01-31 11:42:24 -08001449 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001450 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001451 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001452
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001453 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1454 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001455}
1456
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001457// List the associated boot reason(s), if arg is nullptr then all.
1458void PrintBootReasonEnum(const char* arg) {
1459 int value = -1;
1460 if (arg != nullptr) {
1461 value = BootReasonStrToEnum(arg);
1462 }
1463 for (const auto& [match, id] : kBootReasonMap) {
1464 if ((value < 0) || (value == id)) {
1465 printf("%u\t%s\n", id, match.c_str());
1466 }
1467 }
1468}
1469
James Hawkinsabd73e62016-01-19 15:10:38 -08001470} // namespace
1471
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001472int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001473 android::base::InitLogging(argv);
1474
1475 const std::string cmd_line = GetCommandLine(argc, argv);
1476 LOG(INFO) << "Service started: " << cmd_line;
1477
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001478 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001479 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001480 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001481 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001482 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001483 static const char factory_reset_str[] = "record_time_since_factory_reset";
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001484 static const char boot_reason_enum_str[] = "boot_reason_enum";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001485 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001486 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001487 { "help", no_argument, NULL, 'h' },
1488 { "log", no_argument, NULL, 'l' },
1489 { "print", no_argument, NULL, 'p' },
1490 { "record", required_argument, NULL, 'r' },
1491 { value_str, required_argument, NULL, 0 },
1492 { system_boot_reason_str, no_argument, NULL, 0 },
1493 { boot_complete_str, no_argument, NULL, 0 },
1494 { boot_reason_str, no_argument, NULL, 0 },
1495 { factory_reset_str, no_argument, NULL, 0 },
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001496 { boot_reason_enum_str, optional_argument, NULL, 0 },
Tej Singhfe3e7622018-02-06 15:57:38 -08001497 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001498 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001499 };
1500
James Hawkinsc6275582016-03-22 10:47:44 -07001501 std::string boot_event;
1502 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001503 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001504 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001505 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001506 // This case handles long options which have no single-character mapping.
1507 case 0: {
1508 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001509 if (option_name == value_str) {
1510 // |optarg| is an external variable set by getopt representing
1511 // the option argument.
1512 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001513 } else if (option_name == system_boot_reason_str) {
1514 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001515 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001516 RecordBootComplete();
1517 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001518 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001519 } else if (option_name == factory_reset_str) {
1520 RecordFactoryReset();
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001521 } else if (option_name == boot_reason_enum_str) {
1522 PrintBootReasonEnum(optarg);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001523 } else {
1524 LOG(ERROR) << "Invalid option: " << option_name;
1525 }
1526 break;
1527 }
1528
James Hawkinsabd73e62016-01-19 15:10:38 -08001529 case 'h': {
1530 ShowHelp(argv[0]);
1531 break;
1532 }
1533
1534 case 'l': {
1535 LogBootEvents();
1536 break;
1537 }
1538
1539 case 'p': {
1540 PrintBootEvents();
1541 break;
1542 }
1543
1544 case 'r': {
1545 // |optarg| is an external variable set by getopt representing
1546 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001547 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001548 break;
1549 }
1550
1551 default: {
1552 DCHECK_EQ(opt, '?');
1553
1554 // |optopt| is an external variable set by getopt representing
1555 // the value of the invalid option.
1556 LOG(ERROR) << "Invalid option: " << optopt;
1557 ShowHelp(argv[0]);
1558 return EXIT_FAILURE;
1559 }
1560 }
1561 }
1562
James Hawkinsc6275582016-03-22 10:47:44 -07001563 if (!boot_event.empty()) {
1564 RecordBootEventFromCommandLine(boot_event, value);
1565 }
1566
James Hawkinsabd73e62016-01-19 15:10:38 -08001567 return 0;
1568}