blob: 589b99a129da40c4b9442c4d435bdb7d059e5bdf [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}},
70 {"boot_decryption_complete",
71 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
72 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_ENCRYPTION}},
73 {"boot_complete_no_encryption",
74 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
75 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_NO_ENCRYPTION}},
76 {"boot_complete_post_decrypt",
77 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
78 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_POST_DECRYPT}},
79 {"factory_reset_boot_complete",
80 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
81 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE}},
82 {"factory_reset_boot_complete_no_encryption",
83 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
84 android::util::
85 BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE_NO_ENCRYPTION}},
86 {"factory_reset_boot_complete_post_decrypt",
87 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
88 android::util::
89 BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE_POST_DECRYPT}},
90 {"ota_boot_complete",
91 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
92 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE}},
93 {"ota_boot_complete_no_encryption",
94 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
95 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE_NO_ENCRYPTION}},
96 {"ota_boot_complete_post_decrypt",
97 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
98 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE_POST_DECRYPT}},
99 {"post_decrypt_time_elapsed",
100 {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
101 android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__POST_DECRYPT}},
102 // DURATION
103 {"absolute_boot_time",
104 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
105 android::util::BOOT_TIME_EVENT_DURATION__EVENT__ABSOLUTE_BOOT_TIME}},
106 {"boottime.bootloader.1BLE",
107 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
108 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_FIRST_STAGE_EXEC}},
109 {"boottime.bootloader.1BLL",
110 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
111 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_FIRST_STAGE_LOAD}},
112 {"boottime.bootloader.KL",
113 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
114 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_KERNEL_LOAD}},
115 {"boottime.bootloader.2BLE",
116 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
117 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_SECOND_STAGE_EXEC}},
118 {"boottime.bootloader.2BLL",
119 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
120 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_SECOND_STAGE_LOAD}},
121 {"boottime.bootloader.SW",
122 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
123 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_UI_WAIT}},
124 {"boottime.bootloader.total",
125 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
126 android::util::BOOT_TIME_EVENT_DURATION__EVENT__BOOTLOADER_TOTAL}},
127 {"boottime.init.cold_boot_wait",
128 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
129 android::util::BOOT_TIME_EVENT_DURATION__EVENT__COLDBOOT_WAIT}},
130 {"time_since_factory_reset",
131 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
132 android::util::BOOT_TIME_EVENT_DURATION__EVENT__FACTORY_RESET_TIME_SINCE_RESET}},
133 {"ro.boottime.init.first_stage",
134 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
135 android::util::BOOT_TIME_EVENT_DURATION__EVENT__ANDROID_INIT_STAGE_1}},
136 {"ro.boottime.init.selinux",
137 {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
138 android::util::BOOT_TIME_EVENT_DURATION__EVENT__SELINUX_INIT}},
139 // UTC_TIME
140 {"factory_reset",
141 {android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED,
142 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RESET_TIME}},
143 {"factory_reset_current_time",
144 {android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED,
145 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_CURRENT_TIME}},
146 {"factory_reset_record_value",
147 {android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED,
148 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RECORD_VALUE}},
149 // ERROR_CODE
150 {"factory_reset_current_time_failure",
151 {android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED,
152 android::util::BOOT_TIME_EVENT_ERROR_CODE__EVENT__FACTORY_RESET_CURRENT_TIME_FAILURE}},
153};
154
James Hawkinsabd73e62016-01-19 15:10:38 -0800155// Scans the boot event record store for record files and logs each boot event
156// via EventLog.
157void LogBootEvents() {
158 BootEventRecordStore boot_event_store;
James Hawkinsabd73e62016-01-19 15:10:38 -0800159 auto events = boot_event_store.GetAllBootEvents();
Keun young Park606af6d2020-01-15 10:09:03 -0800160 std::vector<std::string_view> notSupportedEvents;
161 for (const auto& event : events) {
162 const auto& name = event.first;
163 const auto& info = kBootEventToAtomInfo.find(name);
164 if (info != kBootEventToAtomInfo.end()) {
165 if (info->second.atom == android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED) {
166 android::util::stats_write(static_cast<int32_t>(info->second.atom),
167 static_cast<int32_t>(info->second.event),
168 static_cast<int32_t>(event.second));
169 } else {
170 android::util::stats_write(static_cast<int32_t>(info->second.atom),
171 static_cast<int32_t>(info->second.event),
172 static_cast<int64_t>(event.second));
173 }
174 } else {
175 notSupportedEvents.push_back(name);
176 }
177 }
178 if (!notSupportedEvents.empty()) {
179 LOG(WARNING) << "LogBootEvents, atomInfo not defined for events:"
180 << android::base::Join(notSupportedEvents, ',');
181 }
James Hawkinsabd73e62016-01-19 15:10:38 -0800182}
183
James Hawkinsc6275582016-03-22 10:47:44 -0700184// Records the named boot |event| to the record store. If |value| is non-empty
185// and is a proper string representation of an integer value, the converted
186// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700187void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -0700188 BootEventRecordStore boot_event_store;
189 if (!value_str.empty()) {
190 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -0700191 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -0700192 boot_event_store.AddBootEventWithValue(event, value);
193 }
James Hawkinsc6275582016-03-22 10:47:44 -0700194 } else {
195 boot_event_store.AddBootEvent(event);
196 }
197}
198
James Hawkinsabd73e62016-01-19 15:10:38 -0800199void PrintBootEvents() {
200 printf("Boot events:\n");
201 printf("------------\n");
202
203 BootEventRecordStore boot_event_store;
204 auto events = boot_event_store.GetAllBootEvents();
205 for (auto i = events.cbegin(); i != events.cend(); ++i) {
206 printf("%s\t%d\n", i->first.c_str(), i->second);
207 }
208}
209
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700210void ShowHelp(const char* cmd) {
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700211 fprintf(stderr, "Usage: %s [options]...\n", cmd);
James Hawkinsabd73e62016-01-19 15:10:38 -0800212 fprintf(stderr,
213 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +0800214 " -h, --help Show this help\n"
215 " -l, --log Log all metrics to logstorage\n"
216 " -p, --print Dump the boot event records to the console\n"
217 " -r, --record Record the timestamp of a named boot event\n"
218 " --value Optional value to associate with the boot event\n"
219 " --record_boot_complete Record metrics related to the time for the device boot\n"
220 " --record_boot_reason Record the reason why the device booted\n"
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700221 " --record_time_since_factory_reset Record the time since the device was reset\n"
222 " --boot_reason_enum=<reason> Report the match to the kBootReasonMap table\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800223}
224
225// Constructs a readable, printable string from the givencommand line
226// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700227std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800228 std::string cmd;
229 for (int i = 0; i < argc; ++i) {
230 cmd += argv[i];
231 cmd += " ";
232 }
233
234 return cmd;
235}
236
James Hawkins25f71222017-10-10 16:37:05 -0700237constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800238constexpr int32_t kUnknownBootReason = 1;
239
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800240// A mapping from boot reason string, as read from the ro.boot.bootreason
241// system property, to a unique integer ID. Viewers of log data dashboards for
242// the boot_reason metric may refer to this mapping to discern the histogram
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700243// values. Regex matching, to manage the scale, as a minimum require either
244// [, \ or * to be present in the string to switch to checking.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800245const std::map<std::string, int32_t> kBootReasonMap = {
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700246 {"reboot,[empty]", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700247 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700248 {"normal", 2},
249 {"recovery", 3},
250 {"reboot", 4},
251 {"PowerKey", 5},
252 {"hard_reset", 6},
253 {"kernel_panic", 7},
254 {"rpm_err", 8},
255 {"hw_reset", 9},
256 {"tz_err", 10},
257 {"adsp_err", 11},
258 {"modem_err", 12},
259 {"mba_err", 13},
260 {"Watchdog", 14},
261 {"Panic", 15},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700262 {"power_key", 16}, // aliasReasons to cold,powerkey (Mediatek)
263 {"power_on", 17}, // aliasReasons to cold,powerkey
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700264 {"Reboot", 18},
265 {"rtc", 19},
266 {"edl", 20},
267 {"oem_pon1", 21},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700268 {"oem_powerkey", 22}, // aliasReasons to cold,powerkey
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700269 {"oem_unknown_reset", 23},
270 {"srto: HWWDT reset SC", 24},
271 {"srto: HWWDT reset platform", 25},
272 {"srto: bootloader", 26},
273 {"srto: kernel panic", 27},
274 {"srto: kernel watchdog reset", 28},
275 {"srto: normal", 29},
276 {"srto: reboot", 30},
277 {"srto: reboot-bootloader", 31},
278 {"srto: security watchdog reset", 32},
279 {"srto: wakesrc", 33},
280 {"srto: watchdog", 34},
281 {"srto:1-1", 35},
282 {"srto:omap_hsmm", 36},
283 {"srto:phy0", 37},
284 {"srto:rtc0", 38},
285 {"srto:touchpad", 39},
286 {"watchdog", 40},
287 {"watchdogr", 41},
288 {"wdog_bark", 42},
289 {"wdog_bite", 43},
290 {"wdog_reset", 44},
Mark Salyzyn274b5442018-08-07 08:45:13 -0700291 {"shutdown,", 45}, // Trailing comma is intentional. Do NOT use.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700292 {"shutdown,userrequested", 46},
293 {"reboot,bootloader", 47},
294 {"reboot,cold", 48},
295 {"reboot,recovery", 49},
296 {"thermal_shutdown", 50},
297 {"s3_wakeup", 51},
298 {"kernel_panic,sysrq", 52},
299 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700300 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700301 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700302 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700303 {"bootloader", 55},
304 {"cold", 56},
305 {"hard", 57},
306 {"warm", 58},
Mark Salyzyn15199252018-03-16 09:26:05 -0700307 {"reboot,kernel_power_off_charging__reboot_system", 59}, // Can not happen
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700308 {"thermal-shutdown", 60},
309 {"shutdown,thermal", 61},
310 {"shutdown,battery", 62},
311 {"reboot,ota", 63},
312 {"reboot,factory_reset", 64},
313 {"reboot,", 65},
314 {"reboot,shell", 66},
315 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700316 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700317 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700318 {"cold,powerkey", 70},
319 {"warm,s3_wakeup", 71},
320 {"hard,hw_reset", 72},
321 {"shutdown,suspend", 73}, // Suspend to RAM
322 {"shutdown,hibernate", 74}, // Suspend to DISK
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700323 {"power_on_key", 75}, // aliasReasons to cold,powerkey
324 {"reboot_by_key", 76}, // translated to reboot,by_key
325 {"wdt_by_pass_pwk", 77}, // Mediatek
326 {"reboot_longkey", 78}, // translated to reboot,longkey
327 {"powerkey", 79}, // aliasReasons to cold,powerkey
328 {"usb", 80}, // aliasReasons to cold,charger (Mediatek)
329 {"wdt", 81}, // Mediatek
330 {"tool_by_pass_pwk", 82}, // aliasReasons to reboot,tool (Mediatek)
331 {"2sec_reboot", 83}, // aliasReasons to cold,rtc,2sec (Mediatek)
James Hawkins34073b52017-10-17 15:53:27 -0700332 {"reboot,by_key", 84},
333 {"reboot,longkey", 85},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700334 {"reboot,2sec", 86}, // Deprecate in two years, replaced with cold,rtc,2sec
Mark Salyzync89f9da2017-10-24 15:35:34 -0700335 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700336 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
337 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn75046892018-05-03 13:11:15 -0700338 {"reboot,rescueparty", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800339 {"charge", 91},
340 {"oem_tz_crash", 92},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700341 {"uvlo", 93}, // aliasReasons to reboot,undervoltage
James Hawkins74b17582017-11-20 14:13:41 -0800342 {"oem_ps_hold", 94},
343 {"abnormal_reset", 95},
344 {"oemerr_unknown", 96},
345 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800346 {"watchdog_apps_bite", 98},
347 {"xpu_err", 99},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700348 {"power_on_usb", 100}, // aliasReasons to cold,charger
James Hawkinsf4444f02017-11-30 15:01:40 -0800349 {"watchdog_rpm", 101},
350 {"watchdog_nonsec", 102},
351 {"watchdog_apps_bark", 103},
352 {"reboot_dmverity_corrupted", 104},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700353 {"reboot_smpl", 105}, // aliasReasons to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800354 {"watchdog_sdi_apps_reset", 106},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700355 {"smpl", 107}, // aliasReasons to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800356 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800357 {"reboot_normal", 109},
358 {"oem_lpass_cfg", 110},
359 {"oem_xpu_ns_error", 111},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700360 {"power_key_press", 112}, // aliasReasons to cold,powerkey
James Hawkinse2c27242017-12-18 13:40:27 -0800361 {"hardware_reset", 113},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700362 {"reboot_by_powerkey", 114}, // aliasReasons to cold,powerkey (is this correct?)
James Hawkinse2c27242017-12-18 13:40:27 -0800363 {"reboot_verity", 115},
364 {"oem_rpm_undef_error", 116},
365 {"oem_crash_on_the_lk", 117},
366 {"oem_rpm_reset", 118},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700367 {"reboot,powerloss", 119},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700368 {"reboot,undervoltage", 120},
James Hawkinse2c27242017-12-18 13:40:27 -0800369 {"factory_cable", 121},
370 {"oem_ar6320_failed_to_powerup", 122},
371 {"watchdog_rpm_bite", 123},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700372 {"power_on_cable", 124}, // aliasReasons to cold,charger
James Hawkinse2c27242017-12-18 13:40:27 -0800373 {"reboot_unknown", 125},
374 {"wireless_charger", 126},
375 {"0x776655ff", 127},
376 {"oem_thermal_bite_reset", 128},
377 {"charger", 129},
378 {"pon1", 130},
379 {"unknown", 131},
380 {"reboot_rtc", 132},
381 {"cold_boot", 133},
382 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800383 {"power-on", 135},
384 {"oem_adsp_resetting_the_soc", 136},
385 {"kpdpwr", 137},
386 {"oem_modem_timeout_waiting", 138},
387 {"usb_chg", 139},
388 {"warm_reset_0x02", 140},
389 {"warm_reset_0x80", 141},
390 {"pon_reason_0xb0", 142},
391 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800392 {"reboot_recovery_mode", 144},
393 {"oem_sdi_err_fatal", 145},
394 {"pmic_watchdog", 146},
395 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700396 {"cold,charger", 148},
397 {"cold,rtc", 149},
Mark Salyzyn4e7acf72018-03-16 11:00:26 -0700398 {"cold,rtc,2sec", 150}, // Mediatek
399 {"reboot,tool", 151}, // Mediatek
400 {"reboot,wdt", 152}, // Mediatek
401 {"reboot,unknown", 153}, // Mediatek
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700402 {"kernel_panic,audit", 154},
403 {"kernel_panic,atomic", 155},
404 {"kernel_panic,hung", 156},
405 {"kernel_panic,hung,rcu", 157},
406 {"kernel_panic,init", 158},
407 {"kernel_panic,oom", 159},
408 {"kernel_panic,stack", 160},
Mark Salyzynafd66f22018-03-19 15:16:29 -0700409 {"kernel_panic,sysrq,livelock,alarm", 161}, // llkd
410 {"kernel_panic,sysrq,livelock,driver", 162}, // llkd
411 {"kernel_panic,sysrq,livelock,zombie", 163}, // llkd
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700412 {"kernel_panic,modem", 164},
413 {"kernel_panic,adsp", 165},
414 {"kernel_panic,dsps", 166},
415 {"kernel_panic,wcnss", 167},
Mark Salyzyn78e54fd2018-06-08 10:19:16 -0700416 {"kernel_panic,_sde_encoder_phys_cmd_handle_ppdone_timeout", 168},
Mark Salyzyn6fc08292019-03-11 10:06:36 -0700417 {"recovery,quiescent", 169},
418 {"reboot,quiescent", 170},
Jone Choud51036d2019-03-20 19:38:05 +0800419 {"reboot,rtc", 171},
420 {"reboot,dm-verity_device_corrupted", 172},
421 {"reboot,dm-verity_enforcing", 173},
422 {"reboot,keys_clear", 174},
Jone Chou446d6c62019-04-18 15:43:26 +0800423 {"reboot,pmic_off_fault,.*", 175},
424 {"reboot,pmic_off_s3rst,.*", 176},
425 {"reboot,pmic_off_other,.*", 177},
Mark Salyzyn65d8b9b2019-05-23 09:07:54 -0700426 {"reboot,userrequested,fastboot", 178},
427 {"reboot,userrequested,recovery", 179},
428 {"reboot,userrequested,recovery,ui", 180},
429 {"shutdown,userrequested,fastboot", 181},
430 {"shutdown,userrequested,recovery", 182},
Mark Salyzyn8d1be802019-05-21 10:47:55 -0700431 {"reboot,unknown[0-9]*", 183},
Jone Choub9a80332019-06-10 23:24:39 +0800432 {"reboot,longkey,.*", 184},
Tom Cherrya76bfb22019-09-18 09:41:36 -0700433 {"reboot,boringssl-self-check-failed", 185},
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000434 {"reboot,userspace_failed,shutdown_aborted", 186},
435 {"reboot,userspace_failed,watchdog_triggered", 187},
436 {"reboot,userspace_failed,watchdog_fork", 188},
437 {"reboot,userspace_failed,*", 189},
438 {"reboot,mount_userdata_failed", 190},
Jim Kayeb7386a62020-07-01 16:57:01 -0700439 {"reboot,forcedsilent", 191},
440 {"reboot,forcednonsilent", 192},
Lisa Liu82674de2021-03-16 17:43:32 +0800441 {"reboot,thermal,tj", 193},
Howie Changd5f24c52021-08-30 17:27:01 +0800442 {"reboot,emergency", 194},
443 {"reboot,factory", 195},
444 {"reboot,fastboot", 196},
445 {"reboot,gsa,hard", 197},
446 {"reboot,gsa,soft", 198},
447 {"reboot,master_dc,fault_n", 199},
448 {"reboot,master_dc,reset", 200},
449 {"reboot,ocp", 201},
450 {"reboot,pin", 202},
451 {"reboot,rom_recovery", 203},
452 {"reboot,uvlo", 204},
453 {"reboot,uvlo,pmic,if", 205},
454 {"reboot,uvlo,pmic,main", 206},
455 {"reboot,uvlo,pmic,sub", 207},
456 {"reboot,warm", 208},
457 {"watchdog,aoc", 209},
458 {"watchdog,apc", 210},
459 {"watchdog,apc,bl,debug,early", 211},
460 {"watchdog,apc,bl,early", 212},
461 {"watchdog,apc,early", 213},
462 {"watchdog,apm", 214},
463 {"watchdog,gsa,hard", 215},
464 {"watchdog,gsa,soft", 216},
465 {"watchdog,pmucal", 217},
Jason Chiu17251022022-06-28 21:17:49 +0800466 {"reboot,early,bl", 218},
467 {"watchdog,apc,gsa,crashed", 219},
468 {"watchdog,apc,bl31,crashed", 220},
469 {"watchdog,apc,pbl,crashed", 221},
470 {"reboot,memory_protect,hyp", 222},
Jone Chou11160ed2022-07-14 00:24:52 +0800471 {"reboot,tsd,pmic,main", 223},
472 {"reboot,tsd,pmic,sub", 224},
473 {"reboot,ocp,pmic,main", 225},
474 {"reboot,ocp,pmic,sub", 226},
475 {"reboot,sys_ldo_ok,pmic,main", 227},
476 {"reboot,sys_ldo_ok,pmic,sub", 228},
477 {"reboot,smpl_timeout,pmic,main", 229},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800478};
479
480// Converts a string value representing the reason the system booted to an
481// integer representation. This is necessary for logging the boot_reason metric
482// via Tron, which does not accept non-integer buckets in histograms.
483int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800484 auto mapping = kBootReasonMap.find(boot_reason);
485 if (mapping != kBootReasonMap.end()) {
486 return mapping->second;
487 }
488
James Hawkins25f71222017-10-10 16:37:05 -0700489 if (boot_reason.empty()) {
490 return kEmptyBootReason;
491 }
492
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700493 for (const auto& [match, id] : kBootReasonMap) {
494 // Regex matches as a minimum require either [, \ or * to be present.
495 if (match.find_first_of("[\\*") == match.npos) continue;
496 // enforce match from beginning to end
497 auto exact = match;
498 if (exact[0] != '^') exact = "^" + exact;
499 if (exact[exact.size() - 1] != '$') exact = exact + "$";
500 if (std::regex_search(boot_reason, std::regex(exact))) return id;
501 }
502
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800503 LOG(INFO) << "Unknown boot reason: " << boot_reason;
504 return kUnknownBootReason;
505}
506
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700507// Canonical list of supported primary reboot reasons.
508const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700509 // clang-format off
510 // kernel
511 "watchdog",
512 "kernel_panic",
513 // strong
514 "recovery", // Should not happen from ro.boot.bootreason
515 "bootloader", // Should not happen from ro.boot.bootreason
516 // blunt
517 "cold",
518 "hard",
519 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700520 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700521 "shutdown", // Can not happen from ro.boot.bootreason
522 "reboot", // Default catch-all for anything unknown
523 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700524};
525
526// Returns true if the supplied reason prefix is considered detailed enough.
527bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700528 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700529 if (s == "cold") break;
530 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800531 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700532 return true;
533 }
534 }
535 return false;
536}
537
538// Returns true if the supplied reason prefix is associated with the kernel.
539bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700540 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700541 if (s == "recovery") break;
542 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800543 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700544 return true;
545 }
546 }
547 return false;
548}
549
550// Returns true if the supplied reason prefix is considered known.
551bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700552 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700553 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800554 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700555 return true;
556 }
557 }
558 return false;
559}
560
561// If the reboot reason should be improved, report true if is too blunt.
562bool isBluntRebootReason(const std::string& r) {
563 if (isStrongRebootReason(r)) return false;
564
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700565 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700566
567 size_t pos = 0;
568 while ((pos = r.find(',', pos)) != std::string::npos) {
569 ++pos;
570 std::string next(r.substr(pos));
571 if (next.length() == 0) break;
572 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700573 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
574 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700575 }
576 return true;
577}
578
Mark Salyzyn64610892017-09-18 10:41:14 -0700579bool readPstoreConsole(std::string& console) {
580 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
581 return true;
582 }
583 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
584}
585
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700586// Implement a variant of std::string::rfind that is resilient to errors in
587// the data stream being inspected.
588class pstoreConsole {
589 private:
590 const size_t kBitErrorRate = 8; // number of bits per error
591 const std::string& console;
592
593 // Number of bits that differ between the two arguments l and r.
594 // Returns zero if the values for l and r are identical.
595 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
596
597 // A string comparison function, reports the number of errors discovered
598 // in the match to a maximum of the bitLength / kBitErrorRate, at that
599 // point returning npos to indicate match is too poor.
600 //
601 // Since called in rfind which works backwards, expect cache locality will
602 // help if we check in reverse here as well for performance.
603 //
604 // Assumption: l (from console.c_str() + pos) is long enough to house
605 // _r.length(), checked in rfind caller below.
606 //
607 size_t numError(size_t pos, const std::string& _r) const {
608 const char* l = console.c_str() + pos;
609 const char* r = _r.c_str();
610 size_t n = _r.length();
611 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
612 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
613 size_t count = 0;
614 n = 0;
615 do {
616 // individual character bit error rate > threshold + slop
617 size_t num = numError(*--le, *--re);
618 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
619 // total bit error rate > threshold + slop
620 count += num;
621 ++n;
622 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
623 return std::string::npos;
624 }
625 } while (le != reinterpret_cast<const uint8_t*>(l));
626 return count;
627 }
628
629 public:
630 explicit pstoreConsole(const std::string& console) : console(console) {}
631 // scope of argument must be equal to or greater than scope of pstoreConsole
632 explicit pstoreConsole(const std::string&& console) = delete;
633 explicit pstoreConsole(std::string&& console) = delete;
634
635 // Our implementation of rfind, use exact match first, then resort to fuzzy.
636 size_t rfind(const std::string& needle) const {
637 size_t pos = console.rfind(needle); // exact match?
638 if (pos != std::string::npos) return pos;
639
640 // Check to make sure needle fits in console string.
641 pos = console.length();
642 if (needle.length() > pos) return std::string::npos;
643 pos -= needle.length();
644 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800645 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700646 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800647 if (pos == 0) break;
648 --pos;
649 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700650 return std::string::npos;
651 }
652
653 // Our implementation of find, use only fuzzy match.
654 size_t find(const std::string& needle, size_t start = 0) const {
655 // Check to make sure needle fits in console string.
656 if (needle.length() > console.length()) return std::string::npos;
657 const size_t last_pos = console.length() - needle.length();
658 // fuzzy match to maximum kBitErrorRate
659 for (size_t pos = start; pos <= last_pos; ++pos) {
660 if (numError(pos, needle) != std::string::npos) return pos;
661 }
662 return std::string::npos;
663 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700664
665 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700666};
667
668// If bit error match to needle, correct it.
669// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700670bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700671 bool corrected = false;
672 if (reason.length() < needle.length()) return corrected;
673 const pstoreConsole console(reason);
674 const size_t last_pos = reason.length() - needle.length();
675 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
676 pos = console.find(needle, pos);
677 if (pos == std::string::npos) break;
678
679 // exact match has no malice
680 if (needle == reason.substr(pos, needle.length())) continue;
681
682 corrected = true;
683 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
684 }
685 return corrected;
686}
687
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700688// If bit error match to needle, correct it.
689// Return true if any corrections were discovered and applied.
690// Try again if we can replace underline with spaces.
691bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
692 bool corrected = correctForBitError(reason, needle);
693 std::string _needle(needle);
694 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
695 [](char c) { return (c == '_') ? ' ' : c; });
696 if (needle != _needle) {
697 corrected |= correctForBitError(reason, _needle);
698 }
699 return corrected;
700}
701
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700702// Converts a string value representing the reason the system booted to a
703// string complying with Android system standard reason.
704void transformReason(std::string& reason) {
705 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
706 std::transform(reason.begin(), reason.end(), reason.begin(),
707 [](char c) { return ::isblank(c) ? '_' : c; });
708 std::transform(reason.begin(), reason.end(), reason.begin(),
709 [](char c) { return ::isprint(c) ? c : '?'; });
710}
711
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700712// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
713// kernel_panic,<subreason>.
714//
715// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
716// or unprintable character terminated subreason, pos is supplied just beyond
717// first quote. if quoted false, pull out and correct newline (\n) or
718// unprintable character terminated subreason.
719//
720// Heuristics to find termination is painted into a corner:
721
722// single bit error for quote ' that we can block. It is acceptable for
723// the others 7, g in reason. 2/9 chance will miss the terminating quote,
724// but there is always the terminating newline that usually immediately
725// follows to fortify our chances.
726bool likely_single_quote(char c) {
727 switch (static_cast<uint8_t>(c)) {
728 case '\'': // '\''
729 case '\'' ^ 0x01: // '&'
730 case '\'' ^ 0x02: // '%'
731 case '\'' ^ 0x04: // '#'
732 case '\'' ^ 0x08: // '/'
733 return true;
734 case '\'' ^ 0x10: // '7'
735 break;
736 case '\'' ^ 0x20: // '\a' (unprintable)
737 return true;
738 case '\'' ^ 0x40: // 'g'
739 break;
740 case '\'' ^ 0x80: // 0xA7 (unprintable)
741 return true;
742 }
743 return false;
744}
745
746// ::isprint(c) and likely_space() will prevent us from being called for
747// fundamentally printable entries, except for '\r' and '\b'.
748//
749// Except for * and J, single bit errors for \n, all others are non-
750// printable so easy catch. It is _acceptable_ for *, J or j to exist in
751// the reason string, so 2/9 chance we will miss the terminating newline.
752//
753// NB: J might not be acceptable, except if at the beginning or preceded
754// with a space, '(' or any of the quotes and their BER aliases.
755// NB: * might not be acceptable, except if at the beginning or preceded
756// with a space, another *, or any of the quotes or their BER aliases.
757//
758// To reduce the chances to closer to 1/9 is too complicated for the gain.
759bool likely_newline(char c) {
760 switch (static_cast<uint8_t>(c)) {
761 case '\n': // '\n' (unprintable)
762 case '\n' ^ 0x01: // '\r' (unprintable)
763 case '\n' ^ 0x02: // '\b' (unprintable)
764 case '\n' ^ 0x04: // 0x0E (unprintable)
765 case '\n' ^ 0x08: // 0x02 (unprintable)
766 case '\n' ^ 0x10: // 0x1A (unprintable)
767 return true;
768 case '\n' ^ 0x20: // '*'
769 case '\n' ^ 0x40: // 'J'
770 break;
771 case '\n' ^ 0x80: // 0x8A (unprintable)
772 return true;
773 }
774 return false;
775}
776
777// ::isprint(c) will prevent us from being called for all the printable
778// matches below. If we let unprintables through because of this, they
779// get converted to underscore (_) by the validation phase.
780bool likely_space(char c) {
781 switch (static_cast<uint8_t>(c)) {
782 case ' ': // ' '
783 case ' ' ^ 0x01: // '!'
784 case ' ' ^ 0x02: // '"'
785 case ' ' ^ 0x04: // '$'
786 case ' ' ^ 0x08: // '('
787 case ' ' ^ 0x10: // '0'
788 case ' ' ^ 0x20: // '\0' (unprintable)
789 case ' ' ^ 0x40: // 'P'
790 case ' ' ^ 0x80: // 0xA0 (unprintable)
791 case '\t': // '\t'
792 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
793 case '\t' ^ 0x02: // '\v' (unprintable)
794 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
795 case '\t' ^ 0x08: // 0x01 (unprintable)
796 case '\t' ^ 0x10: // 0x19 (unprintable)
797 case '\t' ^ 0x20: // ')'
798 case '\t' ^ 0x40: // '1'
799 case '\t' ^ 0x80: // 0x89 (unprintable)
800 return true;
801 }
802 return false;
803}
804
805std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700806 static constexpr size_t max_reason_length = 256;
807
808 std::string subReason(content.substr(pos, max_reason_length));
809 // Correct against any known strings that Bit Error Match
810 for (const auto& s : knownReasons) {
811 correctForBitErrorOrUnderline(subReason, s);
812 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700813 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700814 for (const auto& m : kBootReasonMap) {
815 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700816 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700817 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
818 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700819 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700820 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700821 correctForBitErrorOrUnderline(subReason,
822 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
823 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
824 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700825 }
826 }
827 for (pos = 0; pos < subReason.length(); ++pos) {
828 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700829 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
830 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700831 subReason.erase(pos);
832 break;
833 }
834 }
835 transformReason(subReason);
836 return subReason;
837}
838
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700839bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700840 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700841 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
842 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700843 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700844 // Invented for Android to allow daemons that specifically trigger sysrq
845 // to communicate more accurate boot subreasons via last console messages.
846 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
847 auto pos = console.rfind(sysrqSubreason);
848 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700849 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700850 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700851 return true;
852 }
853 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
854 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700855 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700856 return true;
857 }
858 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700859 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700860 return true;
861 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700862
863 std::string panic("Kernel panic - not syncing: ");
864 auto pos = console.rfind(panic);
865 if (pos != std::string::npos) {
866 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
867 {"Out of memory", "oom"},
868 {"out of memory", "oom"},
869 {"Oh boy, that early out of memory", "oom"}, // omg
870 {"BUG!", "bug"},
871 {"hung_task: blocked tasks", "hung"},
872 {"audit: ", "audit"},
873 {"scheduling while atomic", "atomic"},
874 {"Attempted to kill init!", "init"},
875 {"Requested init", "init"},
876 {"No working init", "init"},
877 {"Could not decompress init", "init"},
878 {"RCU Stall", "hung,rcu"},
879 {"stack-protector", "stack"},
880 {"kernel stack overflow", "stack"},
881 {"Corrupt kernel stack", "stack"},
882 {"low stack detected", "stack"},
883 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700884 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
885 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
886 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
887 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700888 };
889
890 ret = "kernel_panic";
891 for (auto& s : panicReasons) {
892 if (console.find(panic + s.first, pos) != std::string::npos) {
893 ret += "," + s.second;
894 return true;
895 }
896 }
897 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
898 if (reason.length() > 3) {
899 ret += "," + reason;
900 }
901 return true;
902 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700903 return false;
904}
905
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700906bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
907 return addKernelPanicSubReason(pstoreConsole(content), ret);
908}
909
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700910const char system_reboot_reason_property[] = "sys.boot.reason";
911const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
Mark Salyzynee016ce2019-05-23 10:00:34 -0700912const char last_reboot_reason_file[] = LAST_REBOOT_REASON_FILE;
Mark Salyzynadc433d2018-06-05 08:17:35 -0700913const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700914constexpr size_t history_reboot_reason_size = 4;
915const char history_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY ".history";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700916const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
917
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700918// Land system_boot_reason into system_reboot_reason_property.
919// Shift system_boot_reason into history_reboot_reason_property.
920void BootReasonAddToHistory(const std::string& system_boot_reason) {
921 if (system_boot_reason.empty()) return;
922 LOG(INFO) << "Canonical boot reason: " << system_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800923 auto old_system_boot_reason = android::base::GetProperty(system_reboot_reason_property, "");
924 if (!android::base::SetProperty(system_reboot_reason_property, system_boot_reason)) {
925 android::base::SetProperty(system_reboot_reason_property,
926 system_boot_reason.substr(0, PROPERTY_VALUE_MAX - 1));
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700927 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800928 auto reason_history =
929 android::base::Split(android::base::GetProperty(history_reboot_reason_property, ""), "\n");
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700930 static auto mark = time(nullptr);
931 auto mark_str = std::string(",") + std::to_string(mark);
932 auto marked_system_boot_reason = system_boot_reason + mark_str;
933 if (!reason_history.empty()) {
934 // delete any entries that we just wrote in a previous
935 // call and leveraging duplicate line handling
936 auto last = old_system_boot_reason + mark_str;
937 // trim the list to (history_reboot_reason_size - 1)
938 ssize_t max = history_reboot_reason_size;
939 for (auto it = reason_history.begin(); it != reason_history.end();) {
940 if (it->empty() || (last == *it) || (marked_system_boot_reason == *it) || (--max <= 0)) {
941 it = reason_history.erase(it);
942 } else {
943 last = *it;
944 ++it;
945 }
946 }
947 }
948 // insert at the front, concatenating mark (<epoch time>) detail to the value.
949 reason_history.insert(reason_history.begin(), marked_system_boot_reason);
950 // If the property string is too long ( > PROPERTY_VALUE_MAX)
951 // we get an error, so trim out last entry and try again.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800952 while (!android::base::SetProperty(history_reboot_reason_property,
953 android::base::Join(reason_history, '\n'))) {
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700954 auto it = std::prev(reason_history.end());
955 if (it == reason_history.end()) break;
956 reason_history.erase(it);
957 }
958}
959
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700960// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
961std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800962 auto ret = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700963 std::string reason(boot_reason);
964 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
965 if (reason == ret) ret = "";
966
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700967 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700968
969 // Is the current system boot reason sys.boot.reason valid?
970 if (!isKnownRebootReason(ret)) ret = "";
971
972 if (ret == "") {
973 // Is the bootloader boot reason ro.boot.bootreason known?
974 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700975 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700976 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700977 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700978 if (r == s) {
979 if (isBluntRebootReason(s)) {
980 blunt = s;
981 } else {
982 ret = s;
983 break;
984 }
985 }
986 }
987 if (ret == "") ret = blunt;
988 if (ret != "") break;
989 }
990 }
991
992 if (ret == "") {
993 // A series of checks to take some officially unsupported reasons
994 // reported by the bootloader and find some logical and canonical
995 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700996 // to behave and follow our CTS standards.
997 //
998 // first member is the output
999 // second member is an unanchored regex for an alias
1000 //
Mark Salyzyn28193282018-03-16 09:05:59 -07001001 // If output has a prefix of <bang> '!', we do not use it as a
1002 // match needle (and drop the <bang> prefix when landing in output),
1003 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -07001004 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001005 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001006 {"watchdog", "wdog"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001007 {"kernel_panic", "panic"},
1008 {"shutdown,thermal", "thermal"},
1009 {"warm,s3_wakeup", "s3_wakeup"},
1010 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -07001011 {"cold,charger", "usb|power_on_cable"},
1012 {"cold,powerkey", "powerkey|power_key|PowerKey|power_on"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -07001013 {"cold,rtc", "rtc"},
Mark Salyzyn186f6762018-03-16 11:00:26 -07001014 {"cold,rtc,2sec", "2sec_reboot"},
1015 {"!warm", "wdt_by_pass_pwk"}, // change flavour of blunt
1016 {"!reboot", "^wdt$"}, // change flavour of blunt
1017 {"reboot,tool", "tool_by_pass_pwk"},
Mark Salyzyn88d1b4a2018-06-07 09:39:24 -07001018 {"!reboot,longkey", "reboot_longkey"},
1019 {"!reboot,longkey", "kpdpwr"},
Mark Salyzynec7bafe2018-09-26 08:01:04 -07001020 {"!reboot,undervoltage", "uvlo"},
Mark Salyzynf62983a2018-09-26 09:55:25 -07001021 {"!reboot,powerloss", "smpl"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001022 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001023 };
1024
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001025 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -07001026 size_t firstHasNot = s.first[0] == '!';
1027 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001028 ret = s.first;
1029 break;
1030 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -07001031 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -07001032 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001033 break;
1034 }
1035 }
1036 }
1037
1038 // If watchdog is the reason, see if there is a security angle?
1039 if (ret == "watchdog") {
1040 if (reason.find("sec") != std::string::npos) {
1041 ret += ",security";
1042 }
1043 }
1044
Mark Salyzyn64610892017-09-18 10:41:14 -07001045 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001046 // Check to see if last klog has some refinement hints.
1047 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -07001048 if (readPstoreConsole(content)) {
1049 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001050 }
Mark Salyzyn64610892017-09-18 10:41:14 -07001051 } else if (isBluntRebootReason(ret)) {
1052 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001053
Mark Salyzyn64610892017-09-18 10:41:14 -07001054 // Check to see if last klog has some refinement hints.
1055 std::string content;
1056 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001057 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -07001058 // The toybox reboot command used directly (unlikely)? But also
1059 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001060 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -07001061 ret = "shutdown"; // Still too blunt, but more accurate.
1062 // ToDo: init should record the shutdown reason to kernel messages ala:
1063 // init: shutdown system with command 'last_reboot_reason'
1064 // so that if pstore has persistence we can get some details
1065 // that could be missing in last_reboot_reason_property.
1066 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001067
Mark Salyzyn64610892017-09-18 10:41:14 -07001068 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001069 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -07001070 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -07001071 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -07001072 if (subReason != "") { // Will not land "reboot" as that is too blunt.
1073 if (isKernelRebootReason(subReason)) {
1074 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -07001075 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -07001076 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -07001077 } else {
1078 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -07001079 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001080 }
Mark Salyzyn15199252018-03-16 09:26:05 -07001081 // Some bootloaders shutdown results record in last kernel message.
1082 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
1083 ret = "shutdown";
1084 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001085 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001086
Mark Salyzyn64610892017-09-18 10:41:14 -07001087 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001088 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -07001089 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -07001090 ((console.rfind("Power held for ") != std::string::npos) ||
1091 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -07001092 ret = "cold";
1093 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001094 }
1095
Elliott Hughes50a24eb2018-06-14 10:59:09 -07001096 // TODO: use the HAL to get battery level (http://b/77725702).
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001097
1098 // Is there a controlled shutdown hint in last_reboot_reason_property?
1099 if (isBluntRebootReason(ret)) {
1100 // Content buffer no longer will have console data. Beware if more
1101 // checks added below, that depend on parsing console content.
Mark Salyzynee016ce2019-05-23 10:00:34 -07001102 if (!android::base::ReadFileToString(last_reboot_reason_file, &content)) {
1103 content = android::base::GetProperty(last_reboot_reason_property, "");
1104 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -07001105 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001106
Mark Salyzyn62909822017-10-09 09:27:16 -07001107 // Anything in last is better than 'super-blunt' reboot or shutdown.
1108 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
1109 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001110 }
1111 }
1112
1113 // Other System Health HAL reasons?
1114
1115 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
1116 // possibly offer hardware-specific clues from the PMIC.
1117 }
1118
1119 // If unknown left over from above, make it "reboot,<boot_reason>"
1120 if (ret == "") {
1121 ret = "reboot";
1122 if (android::base::StartsWith(reason, "reboot")) {
1123 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -07001124 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001125 reason = reason.substr(1);
1126 }
1127 }
1128 if (reason != "") {
1129 ret += ",";
1130 ret += reason;
1131 }
1132 }
1133
1134 LOG(INFO) << "Canonical boot reason: " << ret;
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001135 return ret;
1136}
1137
James Hawkinsb9cf7712016-04-08 15:32:19 -07001138// Returns the appropriate metric key prefix for the boot_complete metric such
1139// that boot metrics after a system update are labeled as ota_boot_complete;
1140// otherwise, they are labeled as boot_complete. This method encapsulates the
1141// bookkeeping required to track when a system update has occurred by storing
1142// the UTC timestamp of the system build date and comparing against the current
1143// system build date.
1144std::string CalculateBootCompletePrefix() {
1145 static const std::string kBuildDateKey = "build_date";
1146 std::string boot_complete_prefix = "boot_complete";
1147
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001148 auto build_date_str = android::base::GetProperty("ro.build.date.utc", "");
James Hawkins4dded612016-07-28 11:50:23 -07001149 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -07001150 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -07001151 return std::string();
1152 }
James Hawkinsb9cf7712016-04-08 15:32:19 -07001153
1154 BootEventRecordStore boot_event_store;
1155 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -07001156 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1157 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1158 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001159 BootReasonAddToHistory("reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001160 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001161 boot_complete_prefix = "ota_" + boot_complete_prefix;
1162 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001163 BootReasonAddToHistory("reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001164 }
1165
1166 return boot_complete_prefix;
1167}
1168
James Hawkinsef0a0902017-01-06 14:38:23 -08001169// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001170void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001171 auto value = android::base::GetProperty(property, "");
James Hawkinsef0a0902017-01-06 14:38:23 -08001172
James Hawkins27c05222017-01-26 11:55:44 -08001173 int32_t time_in_ms;
1174 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001175 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1176 }
1177}
1178
James Hawkins1bfcaec2017-05-19 14:27:27 -07001179// A map from bootloader timing stage to the time that stage took during boot.
1180typedef std::map<std::string, int32_t> BootloaderTimingMap;
1181
1182// Returns a mapping from bootloader stage names to the time those stages
1183// took to boot.
1184const BootloaderTimingMap GetBootLoaderTimings() {
1185 BootloaderTimingMap timings;
1186
1187 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1188 // where timeN is in milliseconds.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001189 auto value = android::base::GetProperty("ro.boot.boottime", "");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001190 if (value.empty()) {
1191 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001192 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001193 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001194
1195 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001196 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001197 // |stageTiming| is of the form 'stage:time'.
1198 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001199 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001200
Mark Salyzyn7c721162019-02-08 10:41:15 -08001201 if (stageTimingValues.size() < 2) continue;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001202 std::string stageName = stageTimingValues[0];
1203 int32_t time_ms;
1204 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001205 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001206 }
1207 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001208
James Hawkins1bfcaec2017-05-19 14:27:27 -07001209 return timings;
1210}
1211
Tej Singh4eacd382018-01-25 17:59:57 -08001212// Returns the total bootloader boot time from the ro.boot.boottime system property.
1213int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1214 int32_t total_time = 0;
1215 for (const auto& timing : bootloader_timings) {
1216 total_time += timing.second;
1217 }
1218
1219 return total_time;
1220}
1221
James Hawkins1bfcaec2017-05-19 14:27:27 -07001222// Parses and records the set of bootloader stages and associated boot times
1223// from the ro.boot.boottime system property.
1224void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1225 const BootloaderTimingMap& bootloader_timings) {
1226 int32_t total_time = 0;
1227 for (const auto& timing : bootloader_timings) {
1228 total_time += timing.second;
1229 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1230 }
1231
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001232 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001233}
1234
Tej Singh4eacd382018-01-25 17:59:57 -08001235// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001236// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001237std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1238 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001239 int32_t bootloader_time_ms = 0;
1240
1241 for (const auto& timing : bootloader_timings) {
1242 if (timing.first.compare("SW") != 0) {
1243 bootloader_time_ms += timing.second;
1244 }
1245 }
1246
1247 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001248 return bootloader_duration + uptime;
1249}
1250
1251// Records the closest estimation to the absolute device boot time in seconds.
1252// i.e. from power on to boot_complete, including bootloader times.
1253void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1254 std::chrono::milliseconds absolute_total) {
1255 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1256 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1257}
1258
1259// Logs the total boot time and reason to statsd.
1260void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1261 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1262 double time_since_last_boot_sec) {
Wei Wang699e3422019-05-22 09:46:02 -07001263 auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "<EMPTY>");
1264 auto system_reason = android::base::GetProperty(system_reboot_reason_property, "<EMPTY>");
Tej Singh4eacd382018-01-25 17:59:57 -08001265 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1266 system_reason.c_str(), end_time.count(), total_duration.count(),
1267 (int64_t)bootloader_duration_ms,
1268 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001269}
1270
Tej Singhfe3e7622018-02-06 15:57:38 -08001271void SetSystemBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001272 const auto bootloader_boot_reason =
1273 android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001274 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1275 // Record the scrubbed system_boot_reason to the property
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001276 BootReasonAddToHistory(system_boot_reason);
Mark Salyzynadc433d2018-06-05 08:17:35 -07001277 // Shift last_reboot_reason_property to last_last_reboot_reason_property
Mark Salyzynee016ce2019-05-23 10:00:34 -07001278 std::string last_boot_reason;
1279 if (!android::base::ReadFileToString(last_reboot_reason_file, &last_boot_reason)) {
Nikita Ioffe49062f32020-03-31 23:47:45 +01001280 PLOG(ERROR) << "Failed to read " << last_reboot_reason_file;
Mark Salyzynee016ce2019-05-23 10:00:34 -07001281 last_boot_reason = android::base::GetProperty(last_reboot_reason_property, "");
Nikita Ioffe49062f32020-03-31 23:47:45 +01001282 LOG(INFO) << "Value of " << last_reboot_reason_property << " : " << last_boot_reason;
1283 } else {
1284 LOG(INFO) << "Last reboot reason read from " << last_reboot_reason_file << " : "
1285 << last_boot_reason << ". Last reboot reason read from "
1286 << last_reboot_reason_property << " : "
1287 << android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzynee016ce2019-05-23 10:00:34 -07001288 }
Mark Salyzynadc433d2018-06-05 08:17:35 -07001289 if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1290 last_boot_reason = system_boot_reason;
1291 } else {
1292 transformReason(last_boot_reason);
1293 }
Nikita Ioffe49062f32020-03-31 23:47:45 +01001294 LOG(INFO) << "Normalized last reboot reason : " << last_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001295 android::base::SetProperty(last_last_reboot_reason_property, last_boot_reason);
1296 android::base::SetProperty(last_reboot_reason_property, "");
Nikita Ioffe49062f32020-03-31 23:47:45 +01001297 if (unlink(last_reboot_reason_file) != 0) {
1298 PLOG(ERROR) << "Failed to unlink " << last_reboot_reason_file;
1299 }
Tej Singhfe3e7622018-02-06 15:57:38 -08001300}
1301
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001302// Gets the boot time offset. This is useful when Android is running in a
1303// container, because the boot_clock is not reset when Android reboots.
1304std::chrono::nanoseconds GetBootTimeOffset() {
1305 static const int64_t boottime_offset =
1306 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1307 return std::chrono::nanoseconds(boottime_offset);
1308}
1309
1310// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1311// clock.
1312android::base::boot_clock::duration GetUptime() {
1313 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1314}
1315
James Hawkinsc08e9962016-03-11 14:59:50 -08001316// Records several metrics related to the time it takes to boot the device,
1317// including disambiguating boot time on encrypted or non-encrypted devices.
1318void RecordBootComplete() {
1319 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001320 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001321
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001322 auto uptime_ns = GetUptime();
1323 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001324 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001325 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001326
1327 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1328 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001329 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001330 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001331 }
1332
1333 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001334
James Hawkinsb9cf7712016-04-08 15:32:19 -07001335 // The boot_complete metric has two variants: boot_complete and
1336 // ota_boot_complete. The latter signifies that the device is booting after
1337 // a system update.
1338 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001339 if (boot_complete_prefix.empty()) {
1340 // The system is hosed because the build date property could not be read.
1341 return;
1342 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001343
1344 // post_decrypt_time_elapsed is only logged on encrypted devices.
1345 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1346 // Log the amount of time elapsed until the device is decrypted, which
1347 // includes the variable amount of time the user takes to enter the
1348 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001349 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001350
1351 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001352 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001353 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001354 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001355 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001356 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1357 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001358 }
1359
1360 // Record the total time from device startup to boot complete, regardless of
1361 // encryption state.
Yifan Hong08ba15d2021-03-03 16:32:52 -08001362 // Note: we are recording seconds here even though the field in statsd atom specifies
1363 // milliseconds.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001364 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001365
1366 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
Mark Salyzyn10377df2019-03-27 08:10:41 -07001367 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.first_stage");
James Hawkinsef0a0902017-01-06 14:38:23 -08001368 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1369 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001370
James Hawkins1bfcaec2017-05-19 14:27:27 -07001371 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001372 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001373 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1374
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001375 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001376 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1377 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1378
1379 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1380 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1381
1382 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1383 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001384}
1385
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001386// Records the boot_reason metric by querying the ro.boot.bootreason system
1387// property.
1388void RecordBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001389 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
James Hawkins25f71222017-10-10 16:37:05 -07001390
1391 if (reason.empty()) {
Howard Rofe0b3892020-01-31 17:37:32 -08001392 // TODO(b/148575354): Replace with statsd.
James Hawkins25f71222017-10-10 16:37:05 -07001393 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1394 // (and not corruption anywhere else in the reporting pipeline).
Howard Rofe0b3892020-01-31 17:37:32 -08001395 // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1396 // android::metricslogger::FIELD_PLATFORM_REASON,
1397 // "<EMPTY>");
James Hawkins25f71222017-10-10 16:37:05 -07001398 } else {
Howard Rofe0b3892020-01-31 17:37:32 -08001399 // TODO(b/148575354): Replace with statsd.
1400 // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1401 // android::metricslogger::FIELD_PLATFORM_REASON,
1402 // reason);
James Hawkins25f71222017-10-10 16:37:05 -07001403 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001404
1405 // Log the raw bootloader_boot_reason property value.
1406 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001407 BootEventRecordStore boot_event_store;
1408 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001409
1410 // Log the scrubbed system_boot_reason.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001411 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001412 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1413 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1414
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001415 if (reason == "") {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001416 android::base::SetProperty(bootloader_reboot_reason_property, system_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001417 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001418}
1419
James Hawkins500d7152016-02-16 15:05:54 -08001420// Records two metrics related to the user resetting a device: the time at
1421// which the device is reset, and the time since the user last reset the
1422// device. The former is only set once per-factory reset.
1423void RecordFactoryReset() {
1424 BootEventRecordStore boot_event_store;
1425 BootEventRecordStore::BootEventRecord record;
1426
1427 time_t current_time_utc = time(nullptr);
1428
James Hawkins0660b302016-03-08 16:18:15 -08001429 if (current_time_utc < 0) {
1430 // UMA does not display negative values in buckets, so convert to positive.
Keun young Park606af6d2020-01-15 10:09:03 -08001431 // Logging via BootEventRecordStore.
1432 android::util::stats_write(
1433 static_cast<int32_t>(android::util::BOOT_TIME_EVENT_ERROR_CODE_REPORTED),
1434 static_cast<int32_t>(
1435 android::util::BOOT_TIME_EVENT_ERROR_CODE__EVENT__FACTORY_RESET_CURRENT_TIME_FAILURE),
1436 static_cast<int32_t>(std::abs(current_time_utc)));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001437
James Hawkins9aec9262017-01-31 11:42:24 -08001438 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001439 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001440 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1441 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001442 return;
1443 } else {
Keun young Park606af6d2020-01-15 10:09:03 -08001444 android::util::stats_write(
1445 static_cast<int32_t>(android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED),
1446 static_cast<int32_t>(
1447 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_CURRENT_TIME),
1448 static_cast<int64_t>(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001449
James Hawkins9aec9262017-01-31 11:42:24 -08001450 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001451 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001452 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001453 }
1454
James Hawkins500d7152016-02-16 15:05:54 -08001455 // The factory_reset boot event does not exist after the device is reset, so
1456 // use this signal to mark the time of the factory reset.
1457 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1458 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001459
1460 // Don't log the time_since_factory_reset until some time has elapsed.
1461 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001462 return;
1463 }
1464
1465 // Calculate and record the difference in time between now and the
1466 // factory_reset time.
1467 time_t factory_reset_utc = record.second;
Keun young Park606af6d2020-01-15 10:09:03 -08001468 android::util::stats_write(
1469 static_cast<int32_t>(android::util::BOOT_TIME_EVENT_UTC_TIME_REPORTED),
1470 static_cast<int32_t>(
1471 android::util::BOOT_TIME_EVENT_UTC_TIME__EVENT__FACTORY_RESET_RECORD_VALUE),
1472 static_cast<int64_t>(factory_reset_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001473
James Hawkins9aec9262017-01-31 11:42:24 -08001474 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001475 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001476 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001477
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001478 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1479 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001480}
1481
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001482// List the associated boot reason(s), if arg is nullptr then all.
1483void PrintBootReasonEnum(const char* arg) {
1484 int value = -1;
1485 if (arg != nullptr) {
1486 value = BootReasonStrToEnum(arg);
1487 }
1488 for (const auto& [match, id] : kBootReasonMap) {
1489 if ((value < 0) || (value == id)) {
1490 printf("%u\t%s\n", id, match.c_str());
1491 }
1492 }
1493}
1494
James Hawkinsabd73e62016-01-19 15:10:38 -08001495} // namespace
1496
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001497int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001498 android::base::InitLogging(argv);
1499
1500 const std::string cmd_line = GetCommandLine(argc, argv);
1501 LOG(INFO) << "Service started: " << cmd_line;
1502
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001503 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001504 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001505 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001506 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001507 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001508 static const char factory_reset_str[] = "record_time_since_factory_reset";
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001509 static const char boot_reason_enum_str[] = "boot_reason_enum";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001510 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001511 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001512 { "help", no_argument, NULL, 'h' },
1513 { "log", no_argument, NULL, 'l' },
1514 { "print", no_argument, NULL, 'p' },
1515 { "record", required_argument, NULL, 'r' },
1516 { value_str, required_argument, NULL, 0 },
1517 { system_boot_reason_str, no_argument, NULL, 0 },
1518 { boot_complete_str, no_argument, NULL, 0 },
1519 { boot_reason_str, no_argument, NULL, 0 },
1520 { factory_reset_str, no_argument, NULL, 0 },
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001521 { boot_reason_enum_str, optional_argument, NULL, 0 },
Tej Singhfe3e7622018-02-06 15:57:38 -08001522 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001523 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001524 };
1525
James Hawkinsc6275582016-03-22 10:47:44 -07001526 std::string boot_event;
1527 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001528 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001529 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001530 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001531 // This case handles long options which have no single-character mapping.
1532 case 0: {
1533 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001534 if (option_name == value_str) {
1535 // |optarg| is an external variable set by getopt representing
1536 // the option argument.
1537 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001538 } else if (option_name == system_boot_reason_str) {
1539 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001540 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001541 RecordBootComplete();
1542 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001543 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001544 } else if (option_name == factory_reset_str) {
1545 RecordFactoryReset();
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001546 } else if (option_name == boot_reason_enum_str) {
1547 PrintBootReasonEnum(optarg);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001548 } else {
1549 LOG(ERROR) << "Invalid option: " << option_name;
1550 }
1551 break;
1552 }
1553
James Hawkinsabd73e62016-01-19 15:10:38 -08001554 case 'h': {
1555 ShowHelp(argv[0]);
1556 break;
1557 }
1558
1559 case 'l': {
1560 LogBootEvents();
1561 break;
1562 }
1563
1564 case 'p': {
1565 PrintBootEvents();
1566 break;
1567 }
1568
1569 case 'r': {
1570 // |optarg| is an external variable set by getopt representing
1571 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001572 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001573 break;
1574 }
1575
1576 default: {
1577 DCHECK_EQ(opt, '?');
1578
1579 // |optopt| is an external variable set by getopt representing
1580 // the value of the invalid option.
1581 LOG(ERROR) << "Invalid option: " << optopt;
1582 ShowHelp(argv[0]);
1583 return EXIT_FAILURE;
1584 }
1585 }
1586 }
1587
James Hawkinsc6275582016-03-22 10:47:44 -07001588 if (!boot_event.empty()) {
1589 RecordBootEventFromCommandLine(boot_event, value);
1590 }
1591
James Hawkinsabd73e62016-01-19 15:10:38 -08001592 return 0;
1593}