1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 // The bootstat command provides options to persist boot events with the current
18 // timestamp, dump the persisted events, and log all events to EventLog to be
19 // uploaded to Android log storage via Tron.
20
21 #include <getopt.h>
22 #include <sys/klog.h>
23 #include <unistd.h>
24
25 #include <chrono>
26 #include <cmath>
27 #include <cstddef>
28 #include <cstdio>
29 #include <ctime>
30 #include <map>
31 #include <memory>
32 #include <string>
33 #include <vector>
34
35 #include <android-base/chrono_utils.h>
36 #include <android-base/file.h>
37 #include <android-base/logging.h>
38 #include <android-base/parseint.h>
39 #include <android-base/properties.h>
40 #include <android-base/strings.h>
41 #include <android/log.h>
42 #include <cutils/android_reboot.h>
43 #include <cutils/properties.h>
44 #include <log/logcat.h>
45 #include <metricslogger/metrics_logger.h>
46 #include <statslog.h>
47
48 #include "boot_event_record_store.h"
49
50 namespace {
51
52 // Scans the boot event record store for record files and logs each boot event
53 // via EventLog.
LogBootEvents()54 void LogBootEvents() {
55 BootEventRecordStore boot_event_store;
56
57 auto events = boot_event_store.GetAllBootEvents();
58 for (auto i = events.cbegin(); i != events.cend(); ++i) {
59 android::metricslogger::LogHistogram(i->first, i->second);
60 }
61 }
62
63 // 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.
RecordBootEventFromCommandLine(const std::string & event,const std::string & value_str)66 void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
67 BootEventRecordStore boot_event_store;
68 if (!value_str.empty()) {
69 int32_t value = 0;
70 if (android::base::ParseInt(value_str, &value)) {
71 boot_event_store.AddBootEventWithValue(event, value);
72 }
73 } else {
74 boot_event_store.AddBootEvent(event);
75 }
76 }
77
PrintBootEvents()78 void 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
ShowHelp(const char * cmd)89 void ShowHelp(const char* cmd) {
90 fprintf(stderr, "Usage: %s [options]\n", cmd);
91 fprintf(stderr,
92 "options include:\n"
93 " -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"
100 " --record_time_since_factory_reset Record the time since the device was reset\n");
101 }
102
103 // Constructs a readable, printable string from the givencommand line
104 // arguments.
GetCommandLine(int argc,char ** argv)105 std::string GetCommandLine(int argc, char** argv) {
106 std::string cmd;
107 for (int i = 0; i < argc; ++i) {
108 cmd += argv[i];
109 cmd += " ";
110 }
111
112 return cmd;
113 }
114
115 // Convenience wrapper over the property API that returns an
116 // std::string.
GetProperty(const char * key)117 std::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
SetProperty(const char * key,const std::string & val)126 void SetProperty(const char* key, const std::string& val) {
127 property_set(key, val.c_str());
128 }
129
SetProperty(const char * key,const char * val)130 void SetProperty(const char* key, const char* val) {
131 property_set(key, val);
132 }
133
134 constexpr int32_t kEmptyBootReason = 0;
135 constexpr int32_t kUnknownBootReason = 1;
136
137 // 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.
141 const std::map<std::string, int32_t> kBootReasonMap = {
142 {"empty", kEmptyBootReason},
143 {"unknown", kUnknownBootReason},
144 {"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},
196 {"kernel_panic,BUG", 54},
197 {"bootloader", 55},
198 {"cold", 56},
199 {"hard", 57},
200 {"warm", 58},
201 {"recovery", 59},
202 {"thermal-shutdown", 60},
203 {"shutdown,thermal", 61},
204 {"shutdown,battery", 62},
205 {"reboot,ota", 63},
206 {"reboot,factory_reset", 64},
207 {"reboot,", 65},
208 {"reboot,shell", 66},
209 {"reboot,adb", 67},
210 {"reboot,userrequested", 68},
211 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
212 {"cold,powerkey", 70},
213 {"warm,s3_wakeup", 71},
214 {"hard,hw_reset", 72},
215 {"shutdown,suspend", 73}, // Suspend to RAM
216 {"shutdown,hibernate", 74}, // Suspend to DISK
217 {"power_on_key", 75},
218 {"reboot_by_key", 76},
219 {"wdt_by_pass_pwk", 77},
220 {"reboot_longkey", 78},
221 {"powerkey", 79},
222 {"usb", 80},
223 {"wdt", 81},
224 {"tool_by_pass_pwk", 82},
225 {"2sec_reboot", 83},
226 {"reboot,by_key", 84},
227 {"reboot,longkey", 85},
228 {"reboot,2sec", 86},
229 {"shutdown,thermal,battery", 87},
230 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
231 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
232 {"usb", 90},
233 {"charge", 91},
234 {"oem_tz_crash", 92},
235 {"uvlo", 93},
236 {"oem_ps_hold", 94},
237 {"abnormal_reset", 95},
238 {"oemerr_unknown", 96},
239 {"reboot_fastboot_mode", 97},
240 {"watchdog_apps_bite", 98},
241 {"xpu_err", 99},
242 {"power_on_usb", 100},
243 {"watchdog_rpm", 101},
244 {"watchdog_nonsec", 102},
245 {"watchdog_apps_bark", 103},
246 {"reboot_dmverity_corrupted", 104},
247 {"reboot_smpl", 105},
248 {"watchdog_sdi_apps_reset", 106},
249 {"smpl", 107},
250 {"oem_modem_failed_to_powerup", 108},
251 {"reboot_normal", 109},
252 {"oem_lpass_cfg", 110},
253 {"oem_xpu_ns_error", 111},
254 {"power_key_press", 112},
255 {"hardware_reset", 113},
256 {"reboot_by_powerkey", 114},
257 {"reboot_verity", 115},
258 {"oem_rpm_undef_error", 116},
259 {"oem_crash_on_the_lk", 117},
260 {"oem_rpm_reset", 118},
261 {"oem_lpass_cfg", 119},
262 {"oem_xpu_ns_error", 120},
263 {"factory_cable", 121},
264 {"oem_ar6320_failed_to_powerup", 122},
265 {"watchdog_rpm_bite", 123},
266 {"power_on_cable", 124},
267 {"reboot_unknown", 125},
268 {"wireless_charger", 126},
269 {"0x776655ff", 127},
270 {"oem_thermal_bite_reset", 128},
271 {"charger", 129},
272 {"pon1", 130},
273 {"unknown", 131},
274 {"reboot_rtc", 132},
275 {"cold_boot", 133},
276 {"hard_rst", 134},
277 {"power-on", 135},
278 {"oem_adsp_resetting_the_soc", 136},
279 {"kpdpwr", 137},
280 {"oem_modem_timeout_waiting", 138},
281 {"usb_chg", 139},
282 {"warm_reset_0x02", 140},
283 {"warm_reset_0x80", 141},
284 {"pon_reason_0xb0", 142},
285 {"reboot_download", 143},
286 {"reboot_recovery_mode", 144},
287 {"oem_sdi_err_fatal", 145},
288 {"pmic_watchdog", 146},
289 {"software_master", 147},
290 };
291
292 // Converts a string value representing the reason the system booted to an
293 // integer representation. This is necessary for logging the boot_reason metric
294 // via Tron, which does not accept non-integer buckets in histograms.
BootReasonStrToEnum(const std::string & boot_reason)295 int32_t BootReasonStrToEnum(const std::string& boot_reason) {
296 auto mapping = kBootReasonMap.find(boot_reason);
297 if (mapping != kBootReasonMap.end()) {
298 return mapping->second;
299 }
300
301 if (boot_reason.empty()) {
302 return kEmptyBootReason;
303 }
304
305 LOG(INFO) << "Unknown boot reason: " << boot_reason;
306 return kUnknownBootReason;
307 }
308
309 // Canonical list of supported primary reboot reasons.
310 const std::vector<const std::string> knownReasons = {
311 // clang-format off
312 // kernel
313 "watchdog",
314 "kernel_panic",
315 // strong
316 "recovery", // Should not happen from ro.boot.bootreason
317 "bootloader", // Should not happen from ro.boot.bootreason
318 // blunt
319 "cold",
320 "hard",
321 "warm",
322 // super blunt
323 "shutdown", // Can not happen from ro.boot.bootreason
324 "reboot", // Default catch-all for anything unknown
325 // clang-format on
326 };
327
328 // Returns true if the supplied reason prefix is considered detailed enough.
isStrongRebootReason(const std::string & r)329 bool isStrongRebootReason(const std::string& r) {
330 for (auto& s : knownReasons) {
331 if (s == "cold") break;
332 // Prefix defined as terminated by a nul or comma (,).
333 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
334 return true;
335 }
336 }
337 return false;
338 }
339
340 // Returns true if the supplied reason prefix is associated with the kernel.
isKernelRebootReason(const std::string & r)341 bool isKernelRebootReason(const std::string& r) {
342 for (auto& s : knownReasons) {
343 if (s == "recovery") break;
344 // Prefix defined as terminated by a nul or comma (,).
345 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
346 return true;
347 }
348 }
349 return false;
350 }
351
352 // Returns true if the supplied reason prefix is considered known.
isKnownRebootReason(const std::string & r)353 bool isKnownRebootReason(const std::string& r) {
354 for (auto& s : knownReasons) {
355 // Prefix defined as terminated by a nul or comma (,).
356 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
357 return true;
358 }
359 }
360 return false;
361 }
362
363 // If the reboot reason should be improved, report true if is too blunt.
isBluntRebootReason(const std::string & r)364 bool isBluntRebootReason(const std::string& r) {
365 if (isStrongRebootReason(r)) return false;
366
367 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
368
369 size_t pos = 0;
370 while ((pos = r.find(',', pos)) != std::string::npos) {
371 ++pos;
372 std::string next(r.substr(pos));
373 if (next.length() == 0) break;
374 if (next[0] == ',') continue;
375 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
376 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
377 }
378 return true;
379 }
380
readPstoreConsole(std::string & console)381 bool readPstoreConsole(std::string& console) {
382 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
383 return true;
384 }
385 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
386 }
387
388 // Implement a variant of std::string::rfind that is resilient to errors in
389 // the data stream being inspected.
390 class pstoreConsole {
391 private:
392 const size_t kBitErrorRate = 8; // number of bits per error
393 const std::string& console;
394
395 // Number of bits that differ between the two arguments l and r.
396 // Returns zero if the values for l and r are identical.
numError(uint8_t l,uint8_t r) const397 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
398
399 // A string comparison function, reports the number of errors discovered
400 // in the match to a maximum of the bitLength / kBitErrorRate, at that
401 // point returning npos to indicate match is too poor.
402 //
403 // Since called in rfind which works backwards, expect cache locality will
404 // help if we check in reverse here as well for performance.
405 //
406 // Assumption: l (from console.c_str() + pos) is long enough to house
407 // _r.length(), checked in rfind caller below.
408 //
numError(size_t pos,const std::string & _r) const409 size_t numError(size_t pos, const std::string& _r) const {
410 const char* l = console.c_str() + pos;
411 const char* r = _r.c_str();
412 size_t n = _r.length();
413 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
414 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
415 size_t count = 0;
416 n = 0;
417 do {
418 // individual character bit error rate > threshold + slop
419 size_t num = numError(*--le, *--re);
420 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
421 // total bit error rate > threshold + slop
422 count += num;
423 ++n;
424 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
425 return std::string::npos;
426 }
427 } while (le != reinterpret_cast<const uint8_t*>(l));
428 return count;
429 }
430
431 public:
pstoreConsole(const std::string & console)432 explicit pstoreConsole(const std::string& console) : console(console) {}
433 // scope of argument must be equal to or greater than scope of pstoreConsole
434 explicit pstoreConsole(const std::string&& console) = delete;
435 explicit pstoreConsole(std::string&& console) = delete;
436
437 // Our implementation of rfind, use exact match first, then resort to fuzzy.
rfind(const std::string & needle) const438 size_t rfind(const std::string& needle) const {
439 size_t pos = console.rfind(needle); // exact match?
440 if (pos != std::string::npos) return pos;
441
442 // Check to make sure needle fits in console string.
443 pos = console.length();
444 if (needle.length() > pos) return std::string::npos;
445 pos -= needle.length();
446 // fuzzy match to maximum kBitErrorRate
447 for (;;) {
448 if (numError(pos, needle) != std::string::npos) return pos;
449 if (pos == 0) break;
450 --pos;
451 }
452 return std::string::npos;
453 }
454
455 // Our implementation of find, use only fuzzy match.
find(const std::string & needle,size_t start=0) const456 size_t find(const std::string& needle, size_t start = 0) const {
457 // Check to make sure needle fits in console string.
458 if (needle.length() > console.length()) return std::string::npos;
459 const size_t last_pos = console.length() - needle.length();
460 // fuzzy match to maximum kBitErrorRate
461 for (size_t pos = start; pos <= last_pos; ++pos) {
462 if (numError(pos, needle) != std::string::npos) return pos;
463 }
464 return std::string::npos;
465 }
466 };
467
468 // If bit error match to needle, correct it.
469 // Return true if any corrections were discovered and applied.
correctForBer(std::string & reason,const std::string & needle)470 bool correctForBer(std::string& reason, const std::string& needle) {
471 bool corrected = false;
472 if (reason.length() < needle.length()) return corrected;
473 const pstoreConsole console(reason);
474 const size_t last_pos = reason.length() - needle.length();
475 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
476 pos = console.find(needle, pos);
477 if (pos == std::string::npos) break;
478
479 // exact match has no malice
480 if (needle == reason.substr(pos, needle.length())) continue;
481
482 corrected = true;
483 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
484 }
485 return corrected;
486 }
487
addKernelPanicSubReason(const pstoreConsole & console,std::string & ret)488 bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
489 // Check for kernel panic types to refine information
490 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
491 // Can not happen, except on userdebug, during testing/debugging.
492 ret = "kernel_panic,sysrq";
493 return true;
494 }
495 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
496 std::string::npos) {
497 ret = "kernel_panic,NULL";
498 return true;
499 }
500 if (console.rfind("Kernel BUG at ") != std::string::npos) {
501 ret = "kernel_panic,BUG";
502 return true;
503 }
504 return false;
505 }
506
addKernelPanicSubReason(const std::string & content,std::string & ret)507 bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
508 return addKernelPanicSubReason(pstoreConsole(content), ret);
509 }
510
511 // std::transform Helper callback functions:
512 // Converts a string value representing the reason the system booted to a
513 // string complying with Android system standard reason.
tounderline(char c)514 char tounderline(char c) {
515 return ::isblank(c) ? '_' : c;
516 }
517
toprintable(char c)518 char toprintable(char c) {
519 return ::isprint(c) ? c : '?';
520 }
521
522 // Cleanup boot_reason regarding acceptable character set
transformReason(std::string & reason)523 void transformReason(std::string& reason) {
524 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
525 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
526 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
527 }
528
529 const char system_reboot_reason_property[] = "sys.boot.reason";
530 const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
531 const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
532
533 // Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
BootReasonStrToReason(const std::string & boot_reason)534 std::string BootReasonStrToReason(const std::string& boot_reason) {
535 static const size_t max_reason_length = 256;
536
537 std::string ret(GetProperty(system_reboot_reason_property));
538 std::string reason(boot_reason);
539 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
540 if (reason == ret) ret = "";
541
542 transformReason(reason);
543
544 // Is the current system boot reason sys.boot.reason valid?
545 if (!isKnownRebootReason(ret)) ret = "";
546
547 if (ret == "") {
548 // Is the bootloader boot reason ro.boot.bootreason known?
549 std::vector<std::string> words(android::base::Split(reason, ",_-"));
550 for (auto& s : knownReasons) {
551 std::string blunt;
552 for (auto& r : words) {
553 if (r == s) {
554 if (isBluntRebootReason(s)) {
555 blunt = s;
556 } else {
557 ret = s;
558 break;
559 }
560 }
561 }
562 if (ret == "") ret = blunt;
563 if (ret != "") break;
564 }
565 }
566
567 if (ret == "") {
568 // A series of checks to take some officially unsupported reasons
569 // reported by the bootloader and find some logical and canonical
570 // sense. In an ideal world, we would require those bootloaders
571 // to behave and follow our standards.
572 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
573 {"watchdog", "wdog"},
574 {"cold,powerkey", "powerkey"},
575 {"kernel_panic", "panic"},
576 {"shutdown,thermal", "thermal"},
577 {"warm,s3_wakeup", "s3_wakeup"},
578 {"hard,hw_reset", "hw_reset"},
579 {"reboot,2sec", "2sec_reboot"},
580 {"bootloader", ""},
581 };
582
583 // Either the primary or alias is found _somewhere_ in the reason string.
584 for (auto& s : aliasReasons) {
585 if (reason.find(s.first) != std::string::npos) {
586 ret = s.first;
587 break;
588 }
589 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
590 ret = s.first;
591 break;
592 }
593 }
594 }
595
596 // If watchdog is the reason, see if there is a security angle?
597 if (ret == "watchdog") {
598 if (reason.find("sec") != std::string::npos) {
599 ret += ",security";
600 }
601 }
602
603 if (ret == "kernel_panic") {
604 // Check to see if last klog has some refinement hints.
605 std::string content;
606 if (readPstoreConsole(content)) {
607 addKernelPanicSubReason(content, ret);
608 }
609 } else if (isBluntRebootReason(ret)) {
610 // Check the other available reason resources if the reason is still blunt.
611
612 // Check to see if last klog has some refinement hints.
613 std::string content;
614 if (readPstoreConsole(content)) {
615 const pstoreConsole console(content);
616 // The toybox reboot command used directly (unlikely)? But also
617 // catches init's response to Android's more controlled reboot command.
618 if (console.rfind("reboot: Power down") != std::string::npos) {
619 ret = "shutdown"; // Still too blunt, but more accurate.
620 // ToDo: init should record the shutdown reason to kernel messages ala:
621 // init: shutdown system with command 'last_reboot_reason'
622 // so that if pstore has persistence we can get some details
623 // that could be missing in last_reboot_reason_property.
624 }
625
626 static const char cmd[] = "reboot: Restarting system with command '";
627 size_t pos = console.rfind(cmd);
628 if (pos != std::string::npos) {
629 pos += strlen(cmd);
630 std::string subReason(content.substr(pos, max_reason_length));
631 // Correct against any known strings that Bit Error Match
632 for (const auto& s : knownReasons) {
633 correctForBer(subReason, s);
634 }
635 for (const auto& m : kBootReasonMap) {
636 if (m.first.length() <= strlen("cold")) continue; // too short?
637 if (correctForBer(subReason, m.first + "'")) continue;
638 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
639 if (!android::base::StartsWith(m.first, "reboot,")) continue;
640 correctForBer(subReason, m.first.substr(strlen("reboot,")) + "'");
641 }
642 for (pos = 0; pos < subReason.length(); ++pos) {
643 char c = subReason[pos];
644 // #, &, %, / are common single bit error for ' that we can block
645 if (!::isprint(c) || (c == '\'') || (c == '#') || (c == '&') || (c == '%') || (c == '/')) {
646 subReason.erase(pos);
647 break;
648 }
649 }
650 transformReason(subReason);
651 if (subReason != "") { // Will not land "reboot" as that is too blunt.
652 if (isKernelRebootReason(subReason)) {
653 ret = "reboot," + subReason; // User space can't talk kernel reasons.
654 } else if (isKnownRebootReason(subReason)) {
655 ret = subReason;
656 } else {
657 ret = "reboot," + subReason; // legitimize unknown reasons
658 }
659 }
660 }
661
662 // Check for kernel panics, allowed to override reboot command.
663 if (!addKernelPanicSubReason(console, ret) &&
664 // check for long-press power down
665 ((console.rfind("Power held for ") != std::string::npos) ||
666 (console.rfind("charger: [") != std::string::npos))) {
667 ret = "cold";
668 }
669 }
670
671 // The following battery test should migrate to a default system health HAL
672
673 // Let us not worry if the reboot command was issued, for the cases of
674 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
675 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
676 // battery could conceivably lead to these, so worthy of override.
677 if (isBluntRebootReason(ret)) {
678 // Heuristic to determine if shutdown possibly because of a dead battery?
679 // Really a hail-mary pass to find it in last klog content ...
680 static const int battery_dead_threshold = 2; // percent
681 static const char battery[] = "healthd: battery l=";
682 const pstoreConsole console(content);
683 size_t pos = console.rfind(battery); // last one
684 std::string digits;
685 if (pos != std::string::npos) {
686 digits = content.substr(pos + strlen(battery), strlen("100 "));
687 // correct common errors
688 correctForBer(digits, "100 ");
689 if (digits[0] == '!') digits[0] = '1';
690 if (digits[1] == '!') digits[1] = '1';
691 }
692 const char* endptr = digits.c_str();
693 unsigned level = 0;
694 while (::isdigit(*endptr)) {
695 level *= 10;
696 level += *endptr++ - '0';
697 // make sure no leading zeros, except zero itself, and range check.
698 if ((level == 0) || (level > 100)) break;
699 }
700 // example bit error rate issues for 10%
701 // 'l=10 ' no bits in error
702 // 'l=00 ' single bit error (fails above)
703 // 'l=1 ' single bit error
704 // 'l=0 ' double bit error
705 // There are others, not typically critical because of 2%
706 // battery_dead_threshold. KISS check, make sure second
707 // character after digit sequence is not a space.
708 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
709 LOG(INFO) << "Battery level at shutdown " << level << "%";
710 if (level <= battery_dead_threshold) {
711 ret = "shutdown,battery";
712 }
713 } else { // Most likely
714 digits = ""; // reset digits
715
716 // Content buffer no longer will have console data. Beware if more
717 // checks added below, that depend on parsing console content.
718 content = "";
719
720 LOG(DEBUG) << "Can not find last low battery in last console messages";
721 android_logcat_context ctx = create_android_logcat();
722 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
723 if (fp != nullptr) {
724 android::base::ReadFdToString(fileno(fp), &content);
725 }
726 android_logcat_pclose(&ctx, fp);
727 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
728 const char* match = logcat_battery;
729
730 if (content == "") {
731 // Service logd.klog not running, go to smaller buffer in the kernel.
732 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
733 if (rc > 0) {
734 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
735 std::unique_ptr<char[]> buf(new char[len]);
736 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
737 if (rc < len) {
738 len = rc + 1;
739 }
740 buf[--len] = '\0';
741 content = buf.get();
742 }
743 match = battery;
744 }
745
746 pos = content.find(match); // The first one it finds.
747 if (pos != std::string::npos) {
748 digits = content.substr(pos + strlen(match), strlen("100 "));
749 }
750 endptr = digits.c_str();
751 level = 0;
752 while (::isdigit(*endptr)) {
753 level *= 10;
754 level += *endptr++ - '0';
755 // make sure no leading zeros, except zero itself, and range check.
756 if ((level == 0) || (level > 100)) break;
757 }
758 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
759 LOG(INFO) << "Battery level at startup " << level << "%";
760 if (level <= battery_dead_threshold) {
761 ret = "shutdown,battery";
762 }
763 } else {
764 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
765 }
766 }
767 }
768
769 // Is there a controlled shutdown hint in last_reboot_reason_property?
770 if (isBluntRebootReason(ret)) {
771 // Content buffer no longer will have console data. Beware if more
772 // checks added below, that depend on parsing console content.
773 content = GetProperty(last_reboot_reason_property);
774 transformReason(content);
775
776 // Anything in last is better than 'super-blunt' reboot or shutdown.
777 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
778 ret = content;
779 }
780 }
781
782 // Other System Health HAL reasons?
783
784 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
785 // possibly offer hardware-specific clues from the PMIC.
786 }
787
788 // If unknown left over from above, make it "reboot,<boot_reason>"
789 if (ret == "") {
790 ret = "reboot";
791 if (android::base::StartsWith(reason, "reboot")) {
792 reason = reason.substr(strlen("reboot"));
793 while ((reason[0] == ',') || (reason[0] == '_')) {
794 reason = reason.substr(1);
795 }
796 }
797 if (reason != "") {
798 ret += ",";
799 ret += reason;
800 }
801 }
802
803 LOG(INFO) << "Canonical boot reason: " << ret;
804 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
805 // Rewrite as it must be old news, kernel reasons trump user space.
806 SetProperty(last_reboot_reason_property, ret);
807 }
808 return ret;
809 }
810
811 // Returns the appropriate metric key prefix for the boot_complete metric such
812 // that boot metrics after a system update are labeled as ota_boot_complete;
813 // otherwise, they are labeled as boot_complete. This method encapsulates the
814 // bookkeeping required to track when a system update has occurred by storing
815 // the UTC timestamp of the system build date and comparing against the current
816 // system build date.
CalculateBootCompletePrefix()817 std::string CalculateBootCompletePrefix() {
818 static const std::string kBuildDateKey = "build_date";
819 std::string boot_complete_prefix = "boot_complete";
820
821 std::string build_date_str = GetProperty("ro.build.date.utc");
822 int32_t build_date;
823 if (!android::base::ParseInt(build_date_str, &build_date)) {
824 return std::string();
825 }
826
827 BootEventRecordStore boot_event_store;
828 BootEventRecordStore::BootEventRecord record;
829 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
830 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
831 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
832 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
833 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
834 } else if (build_date != record.second) {
835 boot_complete_prefix = "ota_" + boot_complete_prefix;
836 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
837 LOG(INFO) << "Canonical boot reason: reboot,ota";
838 SetProperty(system_reboot_reason_property, "reboot,ota");
839 }
840
841 return boot_complete_prefix;
842 }
843
844 // Records the value of a given ro.boottime.init property in milliseconds.
RecordInitBootTimeProp(BootEventRecordStore * boot_event_store,const char * property)845 void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
846 std::string value = GetProperty(property);
847
848 int32_t time_in_ms;
849 if (android::base::ParseInt(value, &time_in_ms)) {
850 boot_event_store->AddBootEventWithValue(property, time_in_ms);
851 }
852 }
853
854 // A map from bootloader timing stage to the time that stage took during boot.
855 typedef std::map<std::string, int32_t> BootloaderTimingMap;
856
857 // Returns a mapping from bootloader stage names to the time those stages
858 // took to boot.
GetBootLoaderTimings()859 const BootloaderTimingMap GetBootLoaderTimings() {
860 BootloaderTimingMap timings;
861
862 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
863 // where timeN is in milliseconds.
864 std::string value = GetProperty("ro.boot.boottime");
865 if (value.empty()) {
866 // ro.boot.boottime is not reported on all devices.
867 return BootloaderTimingMap();
868 }
869
870 auto stages = android::base::Split(value, ",");
871 for (const auto& stageTiming : stages) {
872 // |stageTiming| is of the form 'stage:time'.
873 auto stageTimingValues = android::base::Split(stageTiming, ":");
874 DCHECK_EQ(2U, stageTimingValues.size());
875
876 std::string stageName = stageTimingValues[0];
877 int32_t time_ms;
878 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
879 timings[stageName] = time_ms;
880 }
881 }
882
883 return timings;
884 }
885
886 // Returns the total bootloader boot time from the ro.boot.boottime system property.
GetBootloaderTime(const BootloaderTimingMap & bootloader_timings)887 int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
888 int32_t total_time = 0;
889 for (const auto& timing : bootloader_timings) {
890 total_time += timing.second;
891 }
892
893 return total_time;
894 }
895
896 // Parses and records the set of bootloader stages and associated boot times
897 // from the ro.boot.boottime system property.
RecordBootloaderTimings(BootEventRecordStore * boot_event_store,const BootloaderTimingMap & bootloader_timings)898 void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
899 const BootloaderTimingMap& bootloader_timings) {
900 int32_t total_time = 0;
901 for (const auto& timing : bootloader_timings) {
902 total_time += timing.second;
903 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
904 }
905
906 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
907 }
908
909 // Returns the closest estimation to the absolute device boot time, i.e.,
910 // from power on to boot_complete, including bootloader times.
GetAbsoluteBootTime(const BootloaderTimingMap & bootloader_timings,std::chrono::milliseconds uptime)911 std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
912 std::chrono::milliseconds uptime) {
913 int32_t bootloader_time_ms = 0;
914
915 for (const auto& timing : bootloader_timings) {
916 if (timing.first.compare("SW") != 0) {
917 bootloader_time_ms += timing.second;
918 }
919 }
920
921 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
922 return bootloader_duration + uptime;
923 }
924
925 // Records the closest estimation to the absolute device boot time in seconds.
926 // i.e. from power on to boot_complete, including bootloader times.
RecordAbsoluteBootTime(BootEventRecordStore * boot_event_store,std::chrono::milliseconds absolute_total)927 void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
928 std::chrono::milliseconds absolute_total) {
929 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
930 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
931 }
932
933 // Logs the total boot time and reason to statsd.
LogBootInfoToStatsd(std::chrono::milliseconds end_time,std::chrono::milliseconds total_duration,int32_t bootloader_duration_ms,double time_since_last_boot_sec)934 void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
935 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
936 double time_since_last_boot_sec) {
937 const std::string reason(GetProperty(bootloader_reboot_reason_property));
938
939 if (reason.empty()) {
940 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
941 end_time.count(), total_duration.count(),
942 (int64_t)bootloader_duration_ms,
943 (int64_t)time_since_last_boot_sec * 1000);
944 return;
945 }
946
947 const std::string system_reason(GetProperty(system_reboot_reason_property));
948 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
949 system_reason.c_str(), end_time.count(), total_duration.count(),
950 (int64_t)bootloader_duration_ms,
951 (int64_t)time_since_last_boot_sec * 1000);
952 }
953
SetSystemBootReason()954 void SetSystemBootReason() {
955 const std::string bootloader_boot_reason(GetProperty(bootloader_reboot_reason_property));
956 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
957 // Record the scrubbed system_boot_reason to the property
958 SetProperty(system_reboot_reason_property, system_boot_reason);
959 }
960
961 // Gets the boot time offset. This is useful when Android is running in a
962 // container, because the boot_clock is not reset when Android reboots.
GetBootTimeOffset()963 std::chrono::nanoseconds GetBootTimeOffset() {
964 static const int64_t boottime_offset =
965 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
966 return std::chrono::nanoseconds(boottime_offset);
967 }
968
969 // Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
970 // clock.
GetUptime()971 android::base::boot_clock::duration GetUptime() {
972 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
973 }
974
975 // Records several metrics related to the time it takes to boot the device,
976 // including disambiguating boot time on encrypted or non-encrypted devices.
RecordBootComplete()977 void RecordBootComplete() {
978 BootEventRecordStore boot_event_store;
979 BootEventRecordStore::BootEventRecord record;
980
981 auto uptime_ns = GetUptime();
982 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
983 time_t current_time_utc = time(nullptr);
984 time_t time_since_last_boot = 0;
985
986 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
987 time_t last_boot_time_utc = record.second;
988 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
989 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
990 }
991
992 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
993
994 // The boot_complete metric has two variants: boot_complete and
995 // ota_boot_complete. The latter signifies that the device is booting after
996 // a system update.
997 std::string boot_complete_prefix = CalculateBootCompletePrefix();
998 if (boot_complete_prefix.empty()) {
999 // The system is hosed because the build date property could not be read.
1000 return;
1001 }
1002
1003 // post_decrypt_time_elapsed is only logged on encrypted devices.
1004 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1005 // Log the amount of time elapsed until the device is decrypted, which
1006 // includes the variable amount of time the user takes to enter the
1007 // decryption password.
1008 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
1009
1010 // Subtract the decryption time to normalize the boot cycle timing.
1011 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
1012 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
1013 boot_complete.count());
1014 } else {
1015 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1016 uptime_s.count());
1017 }
1018
1019 // Record the total time from device startup to boot complete, regardless of
1020 // encryption state.
1021 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
1022
1023 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1024 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1025 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
1026
1027 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
1028 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
1029 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1030
1031 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
1032 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1033 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1034
1035 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1036 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1037
1038 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1039 time_since_last_boot);
1040 }
1041
1042 // Records the boot_reason metric by querying the ro.boot.bootreason system
1043 // property.
RecordBootReason()1044 void RecordBootReason() {
1045 const std::string reason(GetProperty(bootloader_reboot_reason_property));
1046
1047 if (reason.empty()) {
1048 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1049 // (and not corruption anywhere else in the reporting pipeline).
1050 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1051 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1052 } else {
1053 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1054 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1055 }
1056
1057 // Log the raw bootloader_boot_reason property value.
1058 int32_t boot_reason = BootReasonStrToEnum(reason);
1059 BootEventRecordStore boot_event_store;
1060 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
1061
1062 // Log the scrubbed system_boot_reason.
1063 const std::string system_reason(GetProperty(system_reboot_reason_property));
1064 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1065 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1066
1067 if (reason == "") {
1068 SetProperty(bootloader_reboot_reason_property, system_reason);
1069 }
1070 }
1071
1072 // Records two metrics related to the user resetting a device: the time at
1073 // which the device is reset, and the time since the user last reset the
1074 // device. The former is only set once per-factory reset.
RecordFactoryReset()1075 void RecordFactoryReset() {
1076 BootEventRecordStore boot_event_store;
1077 BootEventRecordStore::BootEventRecord record;
1078
1079 time_t current_time_utc = time(nullptr);
1080
1081 if (current_time_utc < 0) {
1082 // UMA does not display negative values in buckets, so convert to positive.
1083 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1084 std::abs(current_time_utc));
1085
1086 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
1087 // is losing records somehow.
1088 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1089 std::abs(current_time_utc));
1090 return;
1091 } else {
1092 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
1093
1094 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
1095 // is losing records somehow.
1096 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
1097 }
1098
1099 // The factory_reset boot event does not exist after the device is reset, so
1100 // use this signal to mark the time of the factory reset.
1101 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1102 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
1103
1104 // Don't log the time_since_factory_reset until some time has elapsed.
1105 // The data is not meaningful yet and skews the histogram buckets.
1106 return;
1107 }
1108
1109 // Calculate and record the difference in time between now and the
1110 // factory_reset time.
1111 time_t factory_reset_utc = record.second;
1112 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
1113
1114 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
1115 // is losing records somehow.
1116 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
1117
1118 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1119 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
1120 }
1121
1122 } // namespace
1123
main(int argc,char ** argv)1124 int main(int argc, char** argv) {
1125 android::base::InitLogging(argv);
1126
1127 const std::string cmd_line = GetCommandLine(argc, argv);
1128 LOG(INFO) << "Service started: " << cmd_line;
1129
1130 int option_index = 0;
1131 static const char value_str[] = "value";
1132 static const char system_boot_reason_str[] = "set_system_boot_reason";
1133 static const char boot_complete_str[] = "record_boot_complete";
1134 static const char boot_reason_str[] = "record_boot_reason";
1135 static const char factory_reset_str[] = "record_time_since_factory_reset";
1136 static const struct option long_options[] = {
1137 // clang-format off
1138 { "help", no_argument, NULL, 'h' },
1139 { "log", no_argument, NULL, 'l' },
1140 { "print", no_argument, NULL, 'p' },
1141 { "record", required_argument, NULL, 'r' },
1142 { value_str, required_argument, NULL, 0 },
1143 { system_boot_reason_str, no_argument, NULL, 0 },
1144 { boot_complete_str, no_argument, NULL, 0 },
1145 { boot_reason_str, no_argument, NULL, 0 },
1146 { factory_reset_str, no_argument, NULL, 0 },
1147 { NULL, 0, NULL, 0 }
1148 // clang-format on
1149 };
1150
1151 std::string boot_event;
1152 std::string value;
1153 int opt = 0;
1154 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
1155 switch (opt) {
1156 // This case handles long options which have no single-character mapping.
1157 case 0: {
1158 const std::string option_name = long_options[option_index].name;
1159 if (option_name == value_str) {
1160 // |optarg| is an external variable set by getopt representing
1161 // the option argument.
1162 value = optarg;
1163 } else if (option_name == system_boot_reason_str) {
1164 SetSystemBootReason();
1165 } else if (option_name == boot_complete_str) {
1166 RecordBootComplete();
1167 } else if (option_name == boot_reason_str) {
1168 RecordBootReason();
1169 } else if (option_name == factory_reset_str) {
1170 RecordFactoryReset();
1171 } else {
1172 LOG(ERROR) << "Invalid option: " << option_name;
1173 }
1174 break;
1175 }
1176
1177 case 'h': {
1178 ShowHelp(argv[0]);
1179 break;
1180 }
1181
1182 case 'l': {
1183 LogBootEvents();
1184 break;
1185 }
1186
1187 case 'p': {
1188 PrintBootEvents();
1189 break;
1190 }
1191
1192 case 'r': {
1193 // |optarg| is an external variable set by getopt representing
1194 // the option argument.
1195 boot_event = optarg;
1196 break;
1197 }
1198
1199 default: {
1200 DCHECK_EQ(opt, '?');
1201
1202 // |optopt| is an external variable set by getopt representing
1203 // the value of the invalid option.
1204 LOG(ERROR) << "Invalid option: " << optopt;
1205 ShowHelp(argv[0]);
1206 return EXIT_FAILURE;
1207 }
1208 }
1209 }
1210
1211 if (!boot_event.empty()) {
1212 RecordBootEventFromCommandLine(boot_event, value);
1213 }
1214
1215 return 0;
1216 }
1217