blob: e60e6be2541c74534c91b358aff8c6af61dc4cde [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>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080030#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080031#include <memory>
Mark Salyzyn25900dd2018-03-16 09:05:59 -070032#include <regex>
James Hawkinsabd73e62016-01-19 15:10:38 -080033#include <string>
Mark Salyzyn853bb802018-03-16 08:44:56 -070034#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080035#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070036
James Hawkinse78ea772017-03-24 11:43:02 -070037#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070038#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080039#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070040#include <android-base/parseint.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080041#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070042#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070043#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080044#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070045#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080046#include <metricslogger/metrics_logger.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070047
James Hawkinsabd73e62016-01-19 15:10:38 -080048#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080049
50namespace {
51
James Hawkinsabd73e62016-01-19 15:10:38 -080052// Scans the boot event record store for record files and logs each boot event
53// via EventLog.
54void LogBootEvents() {
55 BootEventRecordStore boot_event_store;
56
57 auto events = boot_event_store.GetAllBootEvents();
58 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080059 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080060 }
61}
62
James Hawkinsc6275582016-03-22 10:47:44 -070063// Records the named boot |event| to the record store. If |value| is non-empty
64// and is a proper string representation of an integer value, the converted
65// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070066void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070067 BootEventRecordStore boot_event_store;
68 if (!value_str.empty()) {
69 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070070 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070071 boot_event_store.AddBootEventWithValue(event, value);
72 }
James Hawkinsc6275582016-03-22 10:47:44 -070073 } else {
74 boot_event_store.AddBootEvent(event);
75 }
76}
77
James Hawkinsabd73e62016-01-19 15:10:38 -080078void PrintBootEvents() {
79 printf("Boot events:\n");
80 printf("------------\n");
81
82 BootEventRecordStore boot_event_store;
83 auto events = boot_event_store.GetAllBootEvents();
84 for (auto i = events.cbegin(); i != events.cend(); ++i) {
85 printf("%s\t%d\n", i->first.c_str(), i->second);
86 }
87}
88
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070089void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080090 fprintf(stderr, "Usage: %s [options]\n", cmd);
91 fprintf(stderr,
92 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080093 " -h, --help Show this help\n"
94 " -l, --log Log all metrics to logstorage\n"
95 " -p, --print Dump the boot event records to the console\n"
96 " -r, --record Record the timestamp of a named boot event\n"
97 " --value Optional value to associate with the boot event\n"
98 " --record_boot_complete Record metrics related to the time for the device boot\n"
99 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -0800100 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800101}
102
103// Constructs a readable, printable string from the givencommand line
104// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700105std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800106 std::string cmd;
107 for (int i = 0; i < argc; ++i) {
108 cmd += argv[i];
109 cmd += " ";
110 }
111
112 return cmd;
113}
114
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800115// Convenience wrapper over the property API that returns an
116// std::string.
117std::string GetProperty(const char* key) {
118 std::vector<char> temp(PROPERTY_VALUE_MAX);
119 const int len = property_get(key, &temp[0], nullptr);
120 if (len < 0) {
121 return "";
122 }
123 return std::string(&temp[0], len);
124}
125
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700126void SetProperty(const char* key, const std::string& val) {
127 property_set(key, val.c_str());
128}
129
130void SetProperty(const char* key, const char* val) {
131 property_set(key, val);
132}
133
James Hawkins25f71222017-10-10 16:37:05 -0700134constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800135constexpr int32_t kUnknownBootReason = 1;
136
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800137// A mapping from boot reason string, as read from the ro.boot.bootreason
138// system property, to a unique integer ID. Viewers of log data dashboards for
139// the boot_reason metric may refer to this mapping to discern the histogram
140// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800141const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700142 {"empty", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700143 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700144 {"normal", 2},
145 {"recovery", 3},
146 {"reboot", 4},
147 {"PowerKey", 5},
148 {"hard_reset", 6},
149 {"kernel_panic", 7},
150 {"rpm_err", 8},
151 {"hw_reset", 9},
152 {"tz_err", 10},
153 {"adsp_err", 11},
154 {"modem_err", 12},
155 {"mba_err", 13},
156 {"Watchdog", 14},
157 {"Panic", 15},
158 {"power_key", 16},
159 {"power_on", 17},
160 {"Reboot", 18},
161 {"rtc", 19},
162 {"edl", 20},
163 {"oem_pon1", 21},
164 {"oem_powerkey", 22},
165 {"oem_unknown_reset", 23},
166 {"srto: HWWDT reset SC", 24},
167 {"srto: HWWDT reset platform", 25},
168 {"srto: bootloader", 26},
169 {"srto: kernel panic", 27},
170 {"srto: kernel watchdog reset", 28},
171 {"srto: normal", 29},
172 {"srto: reboot", 30},
173 {"srto: reboot-bootloader", 31},
174 {"srto: security watchdog reset", 32},
175 {"srto: wakesrc", 33},
176 {"srto: watchdog", 34},
177 {"srto:1-1", 35},
178 {"srto:omap_hsmm", 36},
179 {"srto:phy0", 37},
180 {"srto:rtc0", 38},
181 {"srto:touchpad", 39},
182 {"watchdog", 40},
183 {"watchdogr", 41},
184 {"wdog_bark", 42},
185 {"wdog_bite", 43},
186 {"wdog_reset", 44},
187 {"shutdown,", 45}, // Trailing comma is intentional.
188 {"shutdown,userrequested", 46},
189 {"reboot,bootloader", 47},
190 {"reboot,cold", 48},
191 {"reboot,recovery", 49},
192 {"thermal_shutdown", 50},
193 {"s3_wakeup", 51},
194 {"kernel_panic,sysrq", 52},
195 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700196 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700197 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700198 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700199 {"bootloader", 55},
200 {"cold", 56},
201 {"hard", 57},
202 {"warm", 58},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700203 // {"recovery", 59}, // Duplicate of enum 3 above. Immediate reuse possible.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700204 {"thermal-shutdown", 60},
205 {"shutdown,thermal", 61},
206 {"shutdown,battery", 62},
207 {"reboot,ota", 63},
208 {"reboot,factory_reset", 64},
209 {"reboot,", 65},
210 {"reboot,shell", 66},
211 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700212 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700213 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700214 {"cold,powerkey", 70},
215 {"warm,s3_wakeup", 71},
216 {"hard,hw_reset", 72},
217 {"shutdown,suspend", 73}, // Suspend to RAM
218 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700219 {"power_on_key", 75},
220 {"reboot_by_key", 76},
221 {"wdt_by_pass_pwk", 77},
222 {"reboot_longkey", 78},
223 {"powerkey", 79},
224 {"usb", 80},
225 {"wdt", 81},
226 {"tool_by_pass_pwk", 82},
227 {"2sec_reboot", 83},
228 {"reboot,by_key", 84},
229 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700230 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700231 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700232 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
233 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn2b820532018-03-16 08:53:34 -0700234 // {"usb", 90}, // Duplicate of enum 80 above. Immediate reuse possible.
James Hawkins74b17582017-11-20 14:13:41 -0800235 {"charge", 91},
236 {"oem_tz_crash", 92},
237 {"uvlo", 93},
238 {"oem_ps_hold", 94},
239 {"abnormal_reset", 95},
240 {"oemerr_unknown", 96},
241 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800242 {"watchdog_apps_bite", 98},
243 {"xpu_err", 99},
244 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800245 {"watchdog_rpm", 101},
246 {"watchdog_nonsec", 102},
247 {"watchdog_apps_bark", 103},
248 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800249 {"reboot_smpl", 105},
250 {"watchdog_sdi_apps_reset", 106},
251 {"smpl", 107},
252 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800253 {"reboot_normal", 109},
254 {"oem_lpass_cfg", 110},
255 {"oem_xpu_ns_error", 111},
256 {"power_key_press", 112},
257 {"hardware_reset", 113},
258 {"reboot_by_powerkey", 114},
259 {"reboot_verity", 115},
260 {"oem_rpm_undef_error", 116},
261 {"oem_crash_on_the_lk", 117},
262 {"oem_rpm_reset", 118},
263 {"oem_lpass_cfg", 119},
264 {"oem_xpu_ns_error", 120},
265 {"factory_cable", 121},
266 {"oem_ar6320_failed_to_powerup", 122},
267 {"watchdog_rpm_bite", 123},
268 {"power_on_cable", 124},
269 {"reboot_unknown", 125},
270 {"wireless_charger", 126},
271 {"0x776655ff", 127},
272 {"oem_thermal_bite_reset", 128},
273 {"charger", 129},
274 {"pon1", 130},
275 {"unknown", 131},
276 {"reboot_rtc", 132},
277 {"cold_boot", 133},
278 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800279 {"power-on", 135},
280 {"oem_adsp_resetting_the_soc", 136},
281 {"kpdpwr", 137},
282 {"oem_modem_timeout_waiting", 138},
283 {"usb_chg", 139},
284 {"warm_reset_0x02", 140},
285 {"warm_reset_0x80", 141},
286 {"pon_reason_0xb0", 142},
287 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800288 {"reboot_recovery_mode", 144},
289 {"oem_sdi_err_fatal", 145},
290 {"pmic_watchdog", 146},
291 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700292 {"cold,charger", 148},
293 {"cold,rtc", 149},
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700294 {"cold,rtc,2sec", 150},
295 {"reboot,tool", 151},
296 {"reboot,wdt", 152},
297 {"reboot,unknown", 153},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700298 {"kernel_panic,audit", 154},
299 {"kernel_panic,atomic", 155},
300 {"kernel_panic,hung", 156},
301 {"kernel_panic,hung,rcu", 157},
302 {"kernel_panic,init", 158},
303 {"kernel_panic,oom", 159},
304 {"kernel_panic,stack", 160},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800305};
306
307// Converts a string value representing the reason the system booted to an
308// integer representation. This is necessary for logging the boot_reason metric
309// via Tron, which does not accept non-integer buckets in histograms.
310int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800311 auto mapping = kBootReasonMap.find(boot_reason);
312 if (mapping != kBootReasonMap.end()) {
313 return mapping->second;
314 }
315
James Hawkins25f71222017-10-10 16:37:05 -0700316 if (boot_reason.empty()) {
317 return kEmptyBootReason;
318 }
319
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800320 LOG(INFO) << "Unknown boot reason: " << boot_reason;
321 return kUnknownBootReason;
322}
323
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700324// Canonical list of supported primary reboot reasons.
325const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700326 // clang-format off
327 // kernel
328 "watchdog",
329 "kernel_panic",
330 // strong
331 "recovery", // Should not happen from ro.boot.bootreason
332 "bootloader", // Should not happen from ro.boot.bootreason
333 // blunt
334 "cold",
335 "hard",
336 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700337 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700338 "shutdown", // Can not happen from ro.boot.bootreason
339 "reboot", // Default catch-all for anything unknown
340 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700341};
342
343// Returns true if the supplied reason prefix is considered detailed enough.
344bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700345 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700346 if (s == "cold") break;
347 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800348 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700349 return true;
350 }
351 }
352 return false;
353}
354
355// Returns true if the supplied reason prefix is associated with the kernel.
356bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700357 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700358 if (s == "recovery") break;
359 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800360 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700361 return true;
362 }
363 }
364 return false;
365}
366
367// Returns true if the supplied reason prefix is considered known.
368bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700369 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700370 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800371 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700372 return true;
373 }
374 }
375 return false;
376}
377
378// If the reboot reason should be improved, report true if is too blunt.
379bool isBluntRebootReason(const std::string& r) {
380 if (isStrongRebootReason(r)) return false;
381
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700382 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700383
384 size_t pos = 0;
385 while ((pos = r.find(',', pos)) != std::string::npos) {
386 ++pos;
387 std::string next(r.substr(pos));
388 if (next.length() == 0) break;
389 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700390 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
391 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700392 }
393 return true;
394}
395
Mark Salyzyn64610892017-09-18 10:41:14 -0700396bool readPstoreConsole(std::string& console) {
397 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
398 return true;
399 }
400 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
401}
402
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700403// Implement a variant of std::string::rfind that is resilient to errors in
404// the data stream being inspected.
405class pstoreConsole {
406 private:
407 const size_t kBitErrorRate = 8; // number of bits per error
408 const std::string& console;
409
410 // Number of bits that differ between the two arguments l and r.
411 // Returns zero if the values for l and r are identical.
412 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
413
414 // A string comparison function, reports the number of errors discovered
415 // in the match to a maximum of the bitLength / kBitErrorRate, at that
416 // point returning npos to indicate match is too poor.
417 //
418 // Since called in rfind which works backwards, expect cache locality will
419 // help if we check in reverse here as well for performance.
420 //
421 // Assumption: l (from console.c_str() + pos) is long enough to house
422 // _r.length(), checked in rfind caller below.
423 //
424 size_t numError(size_t pos, const std::string& _r) const {
425 const char* l = console.c_str() + pos;
426 const char* r = _r.c_str();
427 size_t n = _r.length();
428 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
429 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
430 size_t count = 0;
431 n = 0;
432 do {
433 // individual character bit error rate > threshold + slop
434 size_t num = numError(*--le, *--re);
435 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
436 // total bit error rate > threshold + slop
437 count += num;
438 ++n;
439 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
440 return std::string::npos;
441 }
442 } while (le != reinterpret_cast<const uint8_t*>(l));
443 return count;
444 }
445
446 public:
447 explicit pstoreConsole(const std::string& console) : console(console) {}
448 // scope of argument must be equal to or greater than scope of pstoreConsole
449 explicit pstoreConsole(const std::string&& console) = delete;
450 explicit pstoreConsole(std::string&& console) = delete;
451
452 // Our implementation of rfind, use exact match first, then resort to fuzzy.
453 size_t rfind(const std::string& needle) const {
454 size_t pos = console.rfind(needle); // exact match?
455 if (pos != std::string::npos) return pos;
456
457 // Check to make sure needle fits in console string.
458 pos = console.length();
459 if (needle.length() > pos) return std::string::npos;
460 pos -= needle.length();
461 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800462 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700463 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800464 if (pos == 0) break;
465 --pos;
466 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700467 return std::string::npos;
468 }
469
470 // Our implementation of find, use only fuzzy match.
471 size_t find(const std::string& needle, size_t start = 0) const {
472 // Check to make sure needle fits in console string.
473 if (needle.length() > console.length()) return std::string::npos;
474 const size_t last_pos = console.length() - needle.length();
475 // fuzzy match to maximum kBitErrorRate
476 for (size_t pos = start; pos <= last_pos; ++pos) {
477 if (numError(pos, needle) != std::string::npos) return pos;
478 }
479 return std::string::npos;
480 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700481
482 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700483};
484
485// If bit error match to needle, correct it.
486// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700487bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700488 bool corrected = false;
489 if (reason.length() < needle.length()) return corrected;
490 const pstoreConsole console(reason);
491 const size_t last_pos = reason.length() - needle.length();
492 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
493 pos = console.find(needle, pos);
494 if (pos == std::string::npos) break;
495
496 // exact match has no malice
497 if (needle == reason.substr(pos, needle.length())) continue;
498
499 corrected = true;
500 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
501 }
502 return corrected;
503}
504
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700505// If bit error match to needle, correct it.
506// Return true if any corrections were discovered and applied.
507// Try again if we can replace underline with spaces.
508bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
509 bool corrected = correctForBitError(reason, needle);
510 std::string _needle(needle);
511 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
512 [](char c) { return (c == '_') ? ' ' : c; });
513 if (needle != _needle) {
514 corrected |= correctForBitError(reason, _needle);
515 }
516 return corrected;
517}
518
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700519// Converts a string value representing the reason the system booted to a
520// string complying with Android system standard reason.
521void transformReason(std::string& reason) {
522 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
523 std::transform(reason.begin(), reason.end(), reason.begin(),
524 [](char c) { return ::isblank(c) ? '_' : c; });
525 std::transform(reason.begin(), reason.end(), reason.begin(),
526 [](char c) { return ::isprint(c) ? c : '?'; });
527}
528
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700529// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
530// kernel_panic,<subreason>.
531//
532// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
533// or unprintable character terminated subreason, pos is supplied just beyond
534// first quote. if quoted false, pull out and correct newline (\n) or
535// unprintable character terminated subreason.
536//
537// Heuristics to find termination is painted into a corner:
538
539// single bit error for quote ' that we can block. It is acceptable for
540// the others 7, g in reason. 2/9 chance will miss the terminating quote,
541// but there is always the terminating newline that usually immediately
542// follows to fortify our chances.
543bool likely_single_quote(char c) {
544 switch (static_cast<uint8_t>(c)) {
545 case '\'': // '\''
546 case '\'' ^ 0x01: // '&'
547 case '\'' ^ 0x02: // '%'
548 case '\'' ^ 0x04: // '#'
549 case '\'' ^ 0x08: // '/'
550 return true;
551 case '\'' ^ 0x10: // '7'
552 break;
553 case '\'' ^ 0x20: // '\a' (unprintable)
554 return true;
555 case '\'' ^ 0x40: // 'g'
556 break;
557 case '\'' ^ 0x80: // 0xA7 (unprintable)
558 return true;
559 }
560 return false;
561}
562
563// ::isprint(c) and likely_space() will prevent us from being called for
564// fundamentally printable entries, except for '\r' and '\b'.
565//
566// Except for * and J, single bit errors for \n, all others are non-
567// printable so easy catch. It is _acceptable_ for *, J or j to exist in
568// the reason string, so 2/9 chance we will miss the terminating newline.
569//
570// NB: J might not be acceptable, except if at the beginning or preceded
571// with a space, '(' or any of the quotes and their BER aliases.
572// NB: * might not be acceptable, except if at the beginning or preceded
573// with a space, another *, or any of the quotes or their BER aliases.
574//
575// To reduce the chances to closer to 1/9 is too complicated for the gain.
576bool likely_newline(char c) {
577 switch (static_cast<uint8_t>(c)) {
578 case '\n': // '\n' (unprintable)
579 case '\n' ^ 0x01: // '\r' (unprintable)
580 case '\n' ^ 0x02: // '\b' (unprintable)
581 case '\n' ^ 0x04: // 0x0E (unprintable)
582 case '\n' ^ 0x08: // 0x02 (unprintable)
583 case '\n' ^ 0x10: // 0x1A (unprintable)
584 return true;
585 case '\n' ^ 0x20: // '*'
586 case '\n' ^ 0x40: // 'J'
587 break;
588 case '\n' ^ 0x80: // 0x8A (unprintable)
589 return true;
590 }
591 return false;
592}
593
594// ::isprint(c) will prevent us from being called for all the printable
595// matches below. If we let unprintables through because of this, they
596// get converted to underscore (_) by the validation phase.
597bool likely_space(char c) {
598 switch (static_cast<uint8_t>(c)) {
599 case ' ': // ' '
600 case ' ' ^ 0x01: // '!'
601 case ' ' ^ 0x02: // '"'
602 case ' ' ^ 0x04: // '$'
603 case ' ' ^ 0x08: // '('
604 case ' ' ^ 0x10: // '0'
605 case ' ' ^ 0x20: // '\0' (unprintable)
606 case ' ' ^ 0x40: // 'P'
607 case ' ' ^ 0x80: // 0xA0 (unprintable)
608 case '\t': // '\t'
609 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
610 case '\t' ^ 0x02: // '\v' (unprintable)
611 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
612 case '\t' ^ 0x08: // 0x01 (unprintable)
613 case '\t' ^ 0x10: // 0x19 (unprintable)
614 case '\t' ^ 0x20: // ')'
615 case '\t' ^ 0x40: // '1'
616 case '\t' ^ 0x80: // 0x89 (unprintable)
617 return true;
618 }
619 return false;
620}
621
622std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700623 static constexpr size_t max_reason_length = 256;
624
625 std::string subReason(content.substr(pos, max_reason_length));
626 // Correct against any known strings that Bit Error Match
627 for (const auto& s : knownReasons) {
628 correctForBitErrorOrUnderline(subReason, s);
629 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700630 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700631 for (const auto& m : kBootReasonMap) {
632 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700633 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700634 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
635 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700636 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700637 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700638 correctForBitErrorOrUnderline(subReason,
639 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
640 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
641 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700642 }
643 }
644 for (pos = 0; pos < subReason.length(); ++pos) {
645 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700646 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
647 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700648 subReason.erase(pos);
649 break;
650 }
651 }
652 transformReason(subReason);
653 return subReason;
654}
655
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700656bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700657 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700658 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
659 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700660 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700661 // Invented for Android to allow daemons that specifically trigger sysrq
662 // to communicate more accurate boot subreasons via last console messages.
663 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
664 auto pos = console.rfind(sysrqSubreason);
665 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700666 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700667 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700668 return true;
669 }
670 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
671 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700672 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700673 return true;
674 }
675 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700676 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700677 return true;
678 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700679
680 std::string panic("Kernel panic - not syncing: ");
681 auto pos = console.rfind(panic);
682 if (pos != std::string::npos) {
683 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
684 {"Out of memory", "oom"},
685 {"out of memory", "oom"},
686 {"Oh boy, that early out of memory", "oom"}, // omg
687 {"BUG!", "bug"},
688 {"hung_task: blocked tasks", "hung"},
689 {"audit: ", "audit"},
690 {"scheduling while atomic", "atomic"},
691 {"Attempted to kill init!", "init"},
692 {"Requested init", "init"},
693 {"No working init", "init"},
694 {"Could not decompress init", "init"},
695 {"RCU Stall", "hung,rcu"},
696 {"stack-protector", "stack"},
697 {"kernel stack overflow", "stack"},
698 {"Corrupt kernel stack", "stack"},
699 {"low stack detected", "stack"},
700 {"corrupted stack end", "stack"},
701 };
702
703 ret = "kernel_panic";
704 for (auto& s : panicReasons) {
705 if (console.find(panic + s.first, pos) != std::string::npos) {
706 ret += "," + s.second;
707 return true;
708 }
709 }
710 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
711 if (reason.length() > 3) {
712 ret += "," + reason;
713 }
714 return true;
715 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700716 return false;
717}
718
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700719bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
720 return addKernelPanicSubReason(pstoreConsole(content), ret);
721}
722
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700723const char system_reboot_reason_property[] = "sys.boot.reason";
724const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
725const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
726
727// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
728std::string BootReasonStrToReason(const std::string& boot_reason) {
729 std::string ret(GetProperty(system_reboot_reason_property));
730 std::string reason(boot_reason);
731 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
732 if (reason == ret) ret = "";
733
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700734 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700735
736 // Is the current system boot reason sys.boot.reason valid?
737 if (!isKnownRebootReason(ret)) ret = "";
738
739 if (ret == "") {
740 // Is the bootloader boot reason ro.boot.bootreason known?
741 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700742 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700743 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700744 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700745 if (r == s) {
746 if (isBluntRebootReason(s)) {
747 blunt = s;
748 } else {
749 ret = s;
750 break;
751 }
752 }
753 }
754 if (ret == "") ret = blunt;
755 if (ret != "") break;
756 }
757 }
758
759 if (ret == "") {
760 // A series of checks to take some officially unsupported reasons
761 // reported by the bootloader and find some logical and canonical
762 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700763 // to behave and follow our CTS standards.
764 //
765 // first member is the output
766 // second member is an unanchored regex for an alias
767 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700768 // If output has a prefix of <bang> '!', we do not use it as a
769 // match needle (and drop the <bang> prefix when landing in output),
770 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700771 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700772 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700773 {"watchdog", "wdog"},
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700774 {"cold,powerkey", "powerkey|power_key|PowerKey"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700775 {"kernel_panic", "panic"},
776 {"shutdown,thermal", "thermal"},
777 {"warm,s3_wakeup", "s3_wakeup"},
778 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700779 {"cold,charger", "usb"},
780 {"cold,rtc", "rtc"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700781 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700782 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700783 };
784
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700785 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700786 size_t firstHasNot = s.first[0] == '!';
787 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700788 ret = s.first;
789 break;
790 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700791 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700792 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700793 break;
794 }
795 }
796 }
797
798 // If watchdog is the reason, see if there is a security angle?
799 if (ret == "watchdog") {
800 if (reason.find("sec") != std::string::npos) {
801 ret += ",security";
802 }
803 }
804
Mark Salyzyn64610892017-09-18 10:41:14 -0700805 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700806 // Check to see if last klog has some refinement hints.
807 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700808 if (readPstoreConsole(content)) {
809 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700810 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700811 } else if (isBluntRebootReason(ret)) {
812 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700813
Mark Salyzyn64610892017-09-18 10:41:14 -0700814 // Check to see if last klog has some refinement hints.
815 std::string content;
816 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700817 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700818 // The toybox reboot command used directly (unlikely)? But also
819 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700820 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700821 ret = "shutdown"; // Still too blunt, but more accurate.
822 // ToDo: init should record the shutdown reason to kernel messages ala:
823 // init: shutdown system with command 'last_reboot_reason'
824 // so that if pstore has persistence we can get some details
825 // that could be missing in last_reboot_reason_property.
826 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700827
Mark Salyzyn64610892017-09-18 10:41:14 -0700828 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700829 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700830 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700831 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700832 if (subReason != "") { // Will not land "reboot" as that is too blunt.
833 if (isKernelRebootReason(subReason)) {
834 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700835 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700836 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700837 } else {
838 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700839 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700840 }
841 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700842
Mark Salyzyn64610892017-09-18 10:41:14 -0700843 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700844 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700845 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700846 ((console.rfind("Power held for ") != std::string::npos) ||
847 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700848 ret = "cold";
849 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700850 }
851
852 // The following battery test should migrate to a default system health HAL
853
854 // Let us not worry if the reboot command was issued, for the cases of
855 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
856 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
857 // battery could conceivably lead to these, so worthy of override.
858 if (isBluntRebootReason(ret)) {
859 // Heuristic to determine if shutdown possibly because of a dead battery?
860 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700861 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700862 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700863 const pstoreConsole console(content);
864 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700865 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700866 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700867 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700868 // correct common errors
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700869 correctForBitError(digits, "100 ");
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700870 if (digits[0] == '!') digits[0] = '1';
871 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700872 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700873 const char* endptr = digits.c_str();
874 unsigned level = 0;
875 while (::isdigit(*endptr)) {
876 level *= 10;
877 level += *endptr++ - '0';
878 // make sure no leading zeros, except zero itself, and range check.
879 if ((level == 0) || (level > 100)) break;
880 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700881 // example bit error rate issues for 10%
882 // 'l=10 ' no bits in error
883 // 'l=00 ' single bit error (fails above)
884 // 'l=1 ' single bit error
885 // 'l=0 ' double bit error
886 // There are others, not typically critical because of 2%
887 // battery_dead_threshold. KISS check, make sure second
888 // character after digit sequence is not a space.
889 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700890 LOG(INFO) << "Battery level at shutdown " << level << "%";
891 if (level <= battery_dead_threshold) {
892 ret = "shutdown,battery";
893 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700894 } else { // Most likely
895 digits = ""; // reset digits
896
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700897 // Content buffer no longer will have console data. Beware if more
898 // checks added below, that depend on parsing console content.
899 content = "";
900
901 LOG(DEBUG) << "Can not find last low battery in last console messages";
902 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700903 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700904 if (fp != nullptr) {
905 android::base::ReadFdToString(fileno(fp), &content);
906 }
907 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700908 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
909 const char* match = logcat_battery;
910
911 if (content == "") {
912 // Service logd.klog not running, go to smaller buffer in the kernel.
913 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
914 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700915 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700916 std::unique_ptr<char[]> buf(new char[len]);
917 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
918 if (rc < len) {
919 len = rc + 1;
920 }
921 buf[--len] = '\0';
922 content = buf.get();
923 }
924 match = battery;
925 }
926
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700927 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700928 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700929 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700930 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700931 endptr = digits.c_str();
932 level = 0;
933 while (::isdigit(*endptr)) {
934 level *= 10;
935 level += *endptr++ - '0';
936 // make sure no leading zeros, except zero itself, and range check.
937 if ((level == 0) || (level > 100)) break;
938 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700939 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700940 LOG(INFO) << "Battery level at startup " << level << "%";
941 if (level <= battery_dead_threshold) {
942 ret = "shutdown,battery";
943 }
944 } else {
945 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
946 }
947 }
948 }
949
950 // Is there a controlled shutdown hint in last_reboot_reason_property?
951 if (isBluntRebootReason(ret)) {
952 // Content buffer no longer will have console data. Beware if more
953 // checks added below, that depend on parsing console content.
954 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700955 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700956
Mark Salyzyn62909822017-10-09 09:27:16 -0700957 // Anything in last is better than 'super-blunt' reboot or shutdown.
958 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
959 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700960 }
961 }
962
963 // Other System Health HAL reasons?
964
965 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
966 // possibly offer hardware-specific clues from the PMIC.
967 }
968
969 // If unknown left over from above, make it "reboot,<boot_reason>"
970 if (ret == "") {
971 ret = "reboot";
972 if (android::base::StartsWith(reason, "reboot")) {
973 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700974 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700975 reason = reason.substr(1);
976 }
977 }
978 if (reason != "") {
979 ret += ",";
980 ret += reason;
981 }
982 }
983
984 LOG(INFO) << "Canonical boot reason: " << ret;
985 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
986 // Rewrite as it must be old news, kernel reasons trump user space.
987 SetProperty(last_reboot_reason_property, ret);
988 }
989 return ret;
990}
991
James Hawkinsb9cf7712016-04-08 15:32:19 -0700992// Returns the appropriate metric key prefix for the boot_complete metric such
993// that boot metrics after a system update are labeled as ota_boot_complete;
994// otherwise, they are labeled as boot_complete. This method encapsulates the
995// bookkeeping required to track when a system update has occurred by storing
996// the UTC timestamp of the system build date and comparing against the current
997// system build date.
998std::string CalculateBootCompletePrefix() {
999 static const std::string kBuildDateKey = "build_date";
1000 std::string boot_complete_prefix = "boot_complete";
1001
1002 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -07001003 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -07001004 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -07001005 return std::string();
1006 }
James Hawkinsb9cf7712016-04-08 15:32:19 -07001007
1008 BootEventRecordStore boot_event_store;
1009 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -07001010 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1011 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1012 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001013 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001014 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001015 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001016 boot_complete_prefix = "ota_" + boot_complete_prefix;
1017 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001018 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001019 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001020 }
1021
1022 return boot_complete_prefix;
1023}
1024
James Hawkinsef0a0902017-01-06 14:38:23 -08001025// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001026void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001027 std::string value = GetProperty(property);
1028
James Hawkins27c05222017-01-26 11:55:44 -08001029 int32_t time_in_ms;
1030 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001031 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1032 }
1033}
1034
James Hawkins1bfcaec2017-05-19 14:27:27 -07001035// A map from bootloader timing stage to the time that stage took during boot.
1036typedef std::map<std::string, int32_t> BootloaderTimingMap;
1037
1038// Returns a mapping from bootloader stage names to the time those stages
1039// took to boot.
1040const BootloaderTimingMap GetBootLoaderTimings() {
1041 BootloaderTimingMap timings;
1042
1043 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1044 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -08001045 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001046 if (value.empty()) {
1047 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001048 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001049 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001050
1051 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001052 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001053 // |stageTiming| is of the form 'stage:time'.
1054 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001055 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001056
1057 std::string stageName = stageTimingValues[0];
1058 int32_t time_ms;
1059 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001060 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001061 }
1062 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001063
James Hawkins1bfcaec2017-05-19 14:27:27 -07001064 return timings;
1065}
1066
1067// Parses and records the set of bootloader stages and associated boot times
1068// from the ro.boot.boottime system property.
1069void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1070 const BootloaderTimingMap& bootloader_timings) {
1071 int32_t total_time = 0;
1072 for (const auto& timing : bootloader_timings) {
1073 total_time += timing.second;
1074 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1075 }
1076
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001077 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001078}
1079
James Hawkins1bfcaec2017-05-19 14:27:27 -07001080// Records the closest estimation to the absolute device boot time, i.e.,
1081// from power on to boot_complete, including bootloader times.
1082void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1083 const BootloaderTimingMap& bootloader_timings,
1084 std::chrono::milliseconds uptime) {
1085 int32_t bootloader_time_ms = 0;
1086
1087 for (const auto& timing : bootloader_timings) {
1088 if (timing.first.compare("SW") != 0) {
1089 bootloader_time_ms += timing.second;
1090 }
1091 }
1092
1093 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
1094 auto absolute_total =
1095 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
1096 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
1097}
1098
James Hawkinsc08e9962016-03-11 14:59:50 -08001099// Records several metrics related to the time it takes to boot the device,
1100// including disambiguating boot time on encrypted or non-encrypted devices.
1101void RecordBootComplete() {
1102 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001103 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001104
James Hawkins1bfcaec2017-05-19 14:27:27 -07001105 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
1106 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001107 time_t current_time_utc = time(nullptr);
1108
1109 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1110 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001111 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
1112 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001113 }
1114
1115 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001116
James Hawkinsb9cf7712016-04-08 15:32:19 -07001117 // The boot_complete metric has two variants: boot_complete and
1118 // ota_boot_complete. The latter signifies that the device is booting after
1119 // a system update.
1120 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001121 if (boot_complete_prefix.empty()) {
1122 // The system is hosed because the build date property could not be read.
1123 return;
1124 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001125
1126 // post_decrypt_time_elapsed is only logged on encrypted devices.
1127 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1128 // Log the amount of time elapsed until the device is decrypted, which
1129 // includes the variable amount of time the user takes to enter the
1130 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -07001131 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001132
1133 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -07001134 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001135 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001136 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001137 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001138 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001139 }
1140
1141 // Record the total time from device startup to boot complete, regardless of
1142 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -07001143 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001144
1145 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1146 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1147 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001148
James Hawkins1bfcaec2017-05-19 14:27:27 -07001149 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
1150 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1151
1152 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
1153 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -08001154}
1155
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001156// Records the boot_reason metric by querying the ro.boot.bootreason system
1157// property.
1158void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001159 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -07001160
1161 if (reason.empty()) {
1162 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1163 // (and not corruption anywhere else in the reporting pipeline).
1164 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1165 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1166 } else {
1167 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1168 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1169 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001170
1171 // Log the raw bootloader_boot_reason property value.
1172 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001173 BootEventRecordStore boot_event_store;
1174 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001175
1176 // Log the scrubbed system_boot_reason.
1177 const std::string system_reason(BootReasonStrToReason(reason));
1178 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1179 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1180
1181 // Record the scrubbed system_boot_reason to the property
1182 SetProperty(system_reboot_reason_property, system_reason);
1183 if (reason == "") {
1184 SetProperty(bootloader_reboot_reason_property, system_reason);
1185 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001186}
1187
James Hawkins500d7152016-02-16 15:05:54 -08001188// Records two metrics related to the user resetting a device: the time at
1189// which the device is reset, and the time since the user last reset the
1190// device. The former is only set once per-factory reset.
1191void RecordFactoryReset() {
1192 BootEventRecordStore boot_event_store;
1193 BootEventRecordStore::BootEventRecord record;
1194
1195 time_t current_time_utc = time(nullptr);
1196
James Hawkins0660b302016-03-08 16:18:15 -08001197 if (current_time_utc < 0) {
1198 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001199 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1200 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001201
James Hawkins9aec9262017-01-31 11:42:24 -08001202 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001203 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001204 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1205 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001206 return;
1207 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001208 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001209
James Hawkins9aec9262017-01-31 11:42:24 -08001210 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001211 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001212 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001213 }
1214
James Hawkins500d7152016-02-16 15:05:54 -08001215 // The factory_reset boot event does not exist after the device is reset, so
1216 // use this signal to mark the time of the factory reset.
1217 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1218 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001219
1220 // Don't log the time_since_factory_reset until some time has elapsed.
1221 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001222 return;
1223 }
1224
1225 // Calculate and record the difference in time between now and the
1226 // factory_reset time.
1227 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001228 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001229
James Hawkins9aec9262017-01-31 11:42:24 -08001230 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001231 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001232 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001233
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001234 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1235 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001236}
1237
James Hawkinsabd73e62016-01-19 15:10:38 -08001238} // namespace
1239
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001240int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001241 android::base::InitLogging(argv);
1242
1243 const std::string cmd_line = GetCommandLine(argc, argv);
1244 LOG(INFO) << "Service started: " << cmd_line;
1245
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001246 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001247 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -08001248 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001249 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001250 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001251 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001252 // clang-format off
1253 { "help", no_argument, NULL, 'h' },
1254 { "log", no_argument, NULL, 'l' },
1255 { "print", no_argument, NULL, 'p' },
1256 { "record", required_argument, NULL, 'r' },
1257 { value_str, required_argument, NULL, 0 },
1258 { boot_complete_str, no_argument, NULL, 0 },
1259 { boot_reason_str, no_argument, NULL, 0 },
1260 { factory_reset_str, no_argument, NULL, 0 },
1261 { NULL, 0, NULL, 0 }
1262 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001263 };
1264
James Hawkinsc6275582016-03-22 10:47:44 -07001265 std::string boot_event;
1266 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001267 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001268 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001269 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001270 // This case handles long options which have no single-character mapping.
1271 case 0: {
1272 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001273 if (option_name == value_str) {
1274 // |optarg| is an external variable set by getopt representing
1275 // the option argument.
1276 value = optarg;
1277 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001278 RecordBootComplete();
1279 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001280 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001281 } else if (option_name == factory_reset_str) {
1282 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001283 } else {
1284 LOG(ERROR) << "Invalid option: " << option_name;
1285 }
1286 break;
1287 }
1288
James Hawkinsabd73e62016-01-19 15:10:38 -08001289 case 'h': {
1290 ShowHelp(argv[0]);
1291 break;
1292 }
1293
1294 case 'l': {
1295 LogBootEvents();
1296 break;
1297 }
1298
1299 case 'p': {
1300 PrintBootEvents();
1301 break;
1302 }
1303
1304 case 'r': {
1305 // |optarg| is an external variable set by getopt representing
1306 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001307 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001308 break;
1309 }
1310
1311 default: {
1312 DCHECK_EQ(opt, '?');
1313
1314 // |optopt| is an external variable set by getopt representing
1315 // the value of the invalid option.
1316 LOG(ERROR) << "Invalid option: " << optopt;
1317 ShowHelp(argv[0]);
1318 return EXIT_FAILURE;
1319 }
1320 }
1321 }
1322
James Hawkinsc6275582016-03-22 10:47:44 -07001323 if (!boot_event.empty()) {
1324 RecordBootEventFromCommandLine(boot_event, value);
1325 }
1326
James Hawkinsabd73e62016-01-19 15:10:38 -08001327 return 0;
1328}