blob: d26cf856fa5bdfe53f3fa924a3c888c12ac71b16 [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>
32#include <string>
James Hawkinsbe46fd12017-02-02 16:21:25 -080033#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070034
James Hawkinse78ea772017-03-24 11:43:02 -070035#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070036#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080037#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070038#include <android-base/parseint.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080039#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070040#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070041#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080042#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070043#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080044#include <metricslogger/metrics_logger.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045
James Hawkinsabd73e62016-01-19 15:10:38 -080046#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080047
48namespace {
49
James Hawkinsabd73e62016-01-19 15:10:38 -080050// Scans the boot event record store for record files and logs each boot event
51// via EventLog.
52void LogBootEvents() {
53 BootEventRecordStore boot_event_store;
54
55 auto events = boot_event_store.GetAllBootEvents();
56 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080057 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080058 }
59}
60
James Hawkinsc6275582016-03-22 10:47:44 -070061// Records the named boot |event| to the record store. If |value| is non-empty
62// and is a proper string representation of an integer value, the converted
63// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070064void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070065 BootEventRecordStore boot_event_store;
66 if (!value_str.empty()) {
67 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070068 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070069 boot_event_store.AddBootEventWithValue(event, value);
70 }
James Hawkinsc6275582016-03-22 10:47:44 -070071 } else {
72 boot_event_store.AddBootEvent(event);
73 }
74}
75
James Hawkinsabd73e62016-01-19 15:10:38 -080076void PrintBootEvents() {
77 printf("Boot events:\n");
78 printf("------------\n");
79
80 BootEventRecordStore boot_event_store;
81 auto events = boot_event_store.GetAllBootEvents();
82 for (auto i = events.cbegin(); i != events.cend(); ++i) {
83 printf("%s\t%d\n", i->first.c_str(), i->second);
84 }
85}
86
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070087void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080088 fprintf(stderr, "Usage: %s [options]\n", cmd);
89 fprintf(stderr,
90 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080091 " -h, --help Show this help\n"
92 " -l, --log Log all metrics to logstorage\n"
93 " -p, --print Dump the boot event records to the console\n"
94 " -r, --record Record the timestamp of a named boot event\n"
95 " --value Optional value to associate with the boot event\n"
96 " --record_boot_complete Record metrics related to the time for the device boot\n"
97 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -080098 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -080099}
100
101// Constructs a readable, printable string from the givencommand line
102// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700103std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800104 std::string cmd;
105 for (int i = 0; i < argc; ++i) {
106 cmd += argv[i];
107 cmd += " ";
108 }
109
110 return cmd;
111}
112
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800113// Convenience wrapper over the property API that returns an
114// std::string.
115std::string GetProperty(const char* key) {
116 std::vector<char> temp(PROPERTY_VALUE_MAX);
117 const int len = property_get(key, &temp[0], nullptr);
118 if (len < 0) {
119 return "";
120 }
121 return std::string(&temp[0], len);
122}
123
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700124void SetProperty(const char* key, const std::string& val) {
125 property_set(key, val.c_str());
126}
127
128void SetProperty(const char* key, const char* val) {
129 property_set(key, val);
130}
131
James Hawkins6f74c0b2016-02-12 15:49:16 -0800132constexpr int32_t kUnknownBootReason = 1;
133
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800134// A mapping from boot reason string, as read from the ro.boot.bootreason
135// system property, to a unique integer ID. Viewers of log data dashboards for
136// the boot_reason metric may refer to this mapping to discern the histogram
137// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800138const std::map<std::string, int32_t> kBootReasonMap = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700139 {"unknown", kUnknownBootReason},
140 {"normal", 2},
141 {"recovery", 3},
142 {"reboot", 4},
143 {"PowerKey", 5},
144 {"hard_reset", 6},
145 {"kernel_panic", 7},
146 {"rpm_err", 8},
147 {"hw_reset", 9},
148 {"tz_err", 10},
149 {"adsp_err", 11},
150 {"modem_err", 12},
151 {"mba_err", 13},
152 {"Watchdog", 14},
153 {"Panic", 15},
154 {"power_key", 16},
155 {"power_on", 17},
156 {"Reboot", 18},
157 {"rtc", 19},
158 {"edl", 20},
159 {"oem_pon1", 21},
160 {"oem_powerkey", 22},
161 {"oem_unknown_reset", 23},
162 {"srto: HWWDT reset SC", 24},
163 {"srto: HWWDT reset platform", 25},
164 {"srto: bootloader", 26},
165 {"srto: kernel panic", 27},
166 {"srto: kernel watchdog reset", 28},
167 {"srto: normal", 29},
168 {"srto: reboot", 30},
169 {"srto: reboot-bootloader", 31},
170 {"srto: security watchdog reset", 32},
171 {"srto: wakesrc", 33},
172 {"srto: watchdog", 34},
173 {"srto:1-1", 35},
174 {"srto:omap_hsmm", 36},
175 {"srto:phy0", 37},
176 {"srto:rtc0", 38},
177 {"srto:touchpad", 39},
178 {"watchdog", 40},
179 {"watchdogr", 41},
180 {"wdog_bark", 42},
181 {"wdog_bite", 43},
182 {"wdog_reset", 44},
183 {"shutdown,", 45}, // Trailing comma is intentional.
184 {"shutdown,userrequested", 46},
185 {"reboot,bootloader", 47},
186 {"reboot,cold", 48},
187 {"reboot,recovery", 49},
188 {"thermal_shutdown", 50},
189 {"s3_wakeup", 51},
190 {"kernel_panic,sysrq", 52},
191 {"kernel_panic,NULL", 53},
192 {"kernel_panic,BUG", 54},
193 {"bootloader", 55},
194 {"cold", 56},
195 {"hard", 57},
196 {"warm", 58},
197 {"recovery", 59},
198 {"thermal-shutdown", 60},
199 {"shutdown,thermal", 61},
200 {"shutdown,battery", 62},
201 {"reboot,ota", 63},
202 {"reboot,factory_reset", 64},
203 {"reboot,", 65},
204 {"reboot,shell", 66},
205 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700206 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700207 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800208};
209
210// Converts a string value representing the reason the system booted to an
211// integer representation. This is necessary for logging the boot_reason metric
212// via Tron, which does not accept non-integer buckets in histograms.
213int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800214 auto mapping = kBootReasonMap.find(boot_reason);
215 if (mapping != kBootReasonMap.end()) {
216 return mapping->second;
217 }
218
219 LOG(INFO) << "Unknown boot reason: " << boot_reason;
220 return kUnknownBootReason;
221}
222
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700223// Canonical list of supported primary reboot reasons.
224const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700225 // clang-format off
226 // kernel
227 "watchdog",
228 "kernel_panic",
229 // strong
230 "recovery", // Should not happen from ro.boot.bootreason
231 "bootloader", // Should not happen from ro.boot.bootreason
232 // blunt
233 "cold",
234 "hard",
235 "warm",
236 "shutdown", // Can not happen from ro.boot.bootreason
237 "reboot", // Default catch-all for anything unknown
238 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700239};
240
241// Returns true if the supplied reason prefix is considered detailed enough.
242bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700243 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700244 if (s == "cold") break;
245 // Prefix defined as terminated by a nul or comma (,).
246 if (android::base::StartsWith(r, s.c_str()) &&
247 ((r.length() == s.length()) || (r[s.length()] == ','))) {
248 return true;
249 }
250 }
251 return false;
252}
253
254// Returns true if the supplied reason prefix is associated with the kernel.
255bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700256 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700257 if (s == "recovery") break;
258 // Prefix defined as terminated by a nul or comma (,).
259 if (android::base::StartsWith(r, s.c_str()) &&
260 ((r.length() == s.length()) || (r[s.length()] == ','))) {
261 return true;
262 }
263 }
264 return false;
265}
266
267// Returns true if the supplied reason prefix is considered known.
268bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700269 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700270 // Prefix defined as terminated by a nul or comma (,).
271 if (android::base::StartsWith(r, s.c_str()) &&
272 ((r.length() == s.length()) || (r[s.length()] == ','))) {
273 return true;
274 }
275 }
276 return false;
277}
278
279// If the reboot reason should be improved, report true if is too blunt.
280bool isBluntRebootReason(const std::string& r) {
281 if (isStrongRebootReason(r)) return false;
282
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700283 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700284
285 size_t pos = 0;
286 while ((pos = r.find(',', pos)) != std::string::npos) {
287 ++pos;
288 std::string next(r.substr(pos));
289 if (next.length() == 0) break;
290 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700291 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
292 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700293 }
294 return true;
295}
296
Mark Salyzyn64610892017-09-18 10:41:14 -0700297bool readPstoreConsole(std::string& console) {
298 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
299 return true;
300 }
301 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
302}
303
304bool addKernelPanicSubReason(const std::string& console, std::string& ret) {
305 // Check for kernel panic types to refine information
306 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
307 // Can not happen, except on userdebug, during testing/debugging.
308 ret = "kernel_panic,sysrq";
309 return true;
310 }
311 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
312 std::string::npos) {
313 ret = "kernel_panic,NULL";
314 return true;
315 }
316 if (console.rfind("Kernel BUG at ") != std::string::npos) {
317 ret = "kernel_panic,BUG";
318 return true;
319 }
320 return false;
321}
322
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700323// std::transform Helper callback functions:
324// Converts a string value representing the reason the system booted to a
325// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700326char tounderline(char c) {
327 return ::isblank(c) ? '_' : c;
328}
329char toprintable(char c) {
330 return ::isprint(c) ? c : '?';
331}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700332
333const char system_reboot_reason_property[] = "sys.boot.reason";
334const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
335const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
336
337// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
338std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700339 static const size_t max_reason_length = 256;
340
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700341 std::string ret(GetProperty(system_reboot_reason_property));
342 std::string reason(boot_reason);
343 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
344 if (reason == ret) ret = "";
345
346 // Cleanup boot_reason regarding acceptable character set
347 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
348 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
349 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
350
351 // Is the current system boot reason sys.boot.reason valid?
352 if (!isKnownRebootReason(ret)) ret = "";
353
354 if (ret == "") {
355 // Is the bootloader boot reason ro.boot.bootreason known?
356 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700357 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700358 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700359 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700360 if (r == s) {
361 if (isBluntRebootReason(s)) {
362 blunt = s;
363 } else {
364 ret = s;
365 break;
366 }
367 }
368 }
369 if (ret == "") ret = blunt;
370 if (ret != "") break;
371 }
372 }
373
374 if (ret == "") {
375 // A series of checks to take some officially unsupported reasons
376 // reported by the bootloader and find some logical and canonical
377 // sense. In an ideal world, we would require those bootloaders
378 // to behave and follow our standards.
379 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700380 {"watchdog", "wdog"},
381 {"cold,powerkey", "powerkey"},
382 {"kernel_panic", "panic"},
383 {"shutdown,thermal", "thermal"},
384 {"warm,s3_wakeup", "s3_wakeup"},
385 {"hard,hw_reset", "hw_reset"},
386 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700387 };
388
389 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700390 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700391 if (reason.find(s.first) != std::string::npos) {
392 ret = s.first;
393 break;
394 }
395 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
396 ret = s.first;
397 break;
398 }
399 }
400 }
401
402 // If watchdog is the reason, see if there is a security angle?
403 if (ret == "watchdog") {
404 if (reason.find("sec") != std::string::npos) {
405 ret += ",security";
406 }
407 }
408
Mark Salyzyn64610892017-09-18 10:41:14 -0700409 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700410 // Check to see if last klog has some refinement hints.
411 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700412 if (readPstoreConsole(content)) {
413 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700414 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700415 } else if (isBluntRebootReason(ret)) {
416 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700417
Mark Salyzyn64610892017-09-18 10:41:14 -0700418 // Check to see if last klog has some refinement hints.
419 std::string content;
420 if (readPstoreConsole(content)) {
421 // The toybox reboot command used directly (unlikely)? But also
422 // catches init's response to Android's more controlled reboot command.
423 if (content.rfind("reboot: Power down") != std::string::npos) {
424 ret = "shutdown"; // Still too blunt, but more accurate.
425 // ToDo: init should record the shutdown reason to kernel messages ala:
426 // init: shutdown system with command 'last_reboot_reason'
427 // so that if pstore has persistence we can get some details
428 // that could be missing in last_reboot_reason_property.
429 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700430
Mark Salyzyn64610892017-09-18 10:41:14 -0700431 static const char cmd[] = "reboot: Restarting system with command '";
432 size_t pos = content.rfind(cmd);
433 if (pos != std::string::npos) {
434 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700435 std::string subReason(content.substr(pos, max_reason_length));
436 for (pos = 0; pos < subReason.length(); ++pos) {
437 char c = tounderline(subReason[pos]);
438 if (!::isprint(c) || (c == '\'')) {
439 subReason.erase(pos);
440 break;
441 }
442 subReason[pos] = ::tolower(c);
443 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700444 if (subReason != "") { // Will not land "reboot" as that is too blunt.
445 if (isKernelRebootReason(subReason)) {
446 ret = "reboot," + subReason; // User space can't talk kernel reasons.
447 } else {
448 ret = subReason;
449 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700450 }
451 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700452
Mark Salyzyn64610892017-09-18 10:41:14 -0700453 // Check for kernel panics, allowed to override reboot command.
454 if (!addKernelPanicSubReason(content, ret) &&
455 // check for long-press power down
456 ((content.rfind("Power held for ") != std::string::npos) ||
457 (content.rfind("charger: [") != std::string::npos))) {
458 ret = "cold";
459 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700460 }
461
462 // The following battery test should migrate to a default system health HAL
463
464 // Let us not worry if the reboot command was issued, for the cases of
465 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
466 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
467 // battery could conceivably lead to these, so worthy of override.
468 if (isBluntRebootReason(ret)) {
469 // Heuristic to determine if shutdown possibly because of a dead battery?
470 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700471 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700472 static const char battery[] = "healthd: battery l=";
Mark Salyzyn64610892017-09-18 10:41:14 -0700473 size_t pos = content.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700474 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700475 if (pos != std::string::npos) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700476 digits = content.substr(pos + strlen(battery));
477 }
478 char* endptr = NULL;
479 unsigned long long level = strtoull(digits.c_str(), &endptr, 10);
480 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700481 LOG(INFO) << "Battery level at shutdown " << level << "%";
482 if (level <= battery_dead_threshold) {
483 ret = "shutdown,battery";
484 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700485 } else { // Most likely
486 digits = ""; // reset digits
487
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700488 // Content buffer no longer will have console data. Beware if more
489 // checks added below, that depend on parsing console content.
490 content = "";
491
492 LOG(DEBUG) << "Can not find last low battery in last console messages";
493 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700494 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700495 if (fp != nullptr) {
496 android::base::ReadFdToString(fileno(fp), &content);
497 }
498 android_logcat_pclose(&ctx, fp);
499 android_logcat_destroy(&ctx);
500 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
501 const char* match = logcat_battery;
502
503 if (content == "") {
504 // Service logd.klog not running, go to smaller buffer in the kernel.
505 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
506 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700507 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700508 std::unique_ptr<char[]> buf(new char[len]);
509 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
510 if (rc < len) {
511 len = rc + 1;
512 }
513 buf[--len] = '\0';
514 content = buf.get();
515 }
516 match = battery;
517 }
518
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700519 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700520 if (pos != std::string::npos) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700521 digits = content.substr(pos + strlen(match));
522 }
523 endptr = NULL;
524 level = strtoull(digits.c_str(), &endptr, 10);
525 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700526 LOG(INFO) << "Battery level at startup " << level << "%";
527 if (level <= battery_dead_threshold) {
528 ret = "shutdown,battery";
529 }
530 } else {
531 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
532 }
533 }
534 }
535
536 // Is there a controlled shutdown hint in last_reboot_reason_property?
537 if (isBluntRebootReason(ret)) {
538 // Content buffer no longer will have console data. Beware if more
539 // checks added below, that depend on parsing console content.
540 content = GetProperty(last_reboot_reason_property);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700541 // Cleanup last_boot_reason regarding acceptable character set
542 std::transform(content.begin(), content.end(), content.begin(), ::tolower);
543 std::transform(content.begin(), content.end(), content.begin(), tounderline);
544 std::transform(content.begin(), content.end(), content.begin(), toprintable);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700545
546 // String is either "reboot,<reason>" or "shutdown,<reason>".
547 // We will set if default reasons, only override with detail if thermal.
Mark Salyzyn08b02562017-09-18 10:07:07 -0700548 if ((android::base::StartsWith(content, ret.c_str()) && (content[ret.length()] == ',')) ||
549 !isBluntRebootReason(content)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700550 // Ok, we want it, let's squash it if secondReason is known.
Mark Salyzyn64610892017-09-18 10:41:14 -0700551 size_t pos = content.find(',');
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700552 if (pos != std::string::npos) {
553 ++pos;
554 std::string secondReason(content.substr(pos));
555 ret = isKnownRebootReason(secondReason) ? secondReason : content;
556 } else {
557 ret = content;
558 }
559 }
560 }
561
562 // Other System Health HAL reasons?
563
564 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
565 // possibly offer hardware-specific clues from the PMIC.
566 }
567
568 // If unknown left over from above, make it "reboot,<boot_reason>"
569 if (ret == "") {
570 ret = "reboot";
571 if (android::base::StartsWith(reason, "reboot")) {
572 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700573 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700574 reason = reason.substr(1);
575 }
576 }
577 if (reason != "") {
578 ret += ",";
579 ret += reason;
580 }
581 }
582
583 LOG(INFO) << "Canonical boot reason: " << ret;
584 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
585 // Rewrite as it must be old news, kernel reasons trump user space.
586 SetProperty(last_reboot_reason_property, ret);
587 }
588 return ret;
589}
590
James Hawkinsb9cf7712016-04-08 15:32:19 -0700591// Returns the appropriate metric key prefix for the boot_complete metric such
592// that boot metrics after a system update are labeled as ota_boot_complete;
593// otherwise, they are labeled as boot_complete. This method encapsulates the
594// bookkeeping required to track when a system update has occurred by storing
595// the UTC timestamp of the system build date and comparing against the current
596// system build date.
597std::string CalculateBootCompletePrefix() {
598 static const std::string kBuildDateKey = "build_date";
599 std::string boot_complete_prefix = "boot_complete";
600
601 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700602 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700603 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700604 return std::string();
605 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700606
607 BootEventRecordStore boot_event_store;
608 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700609 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
610 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
611 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700612 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700613 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
614 if (GetProperty(bootloader_reboot_reason_property) == "") {
615 SetProperty(bootloader_reboot_reason_property, "reboot,factory_reset");
616 }
James Hawkins0bc4ad42017-05-30 15:03:15 -0700617 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700618 boot_complete_prefix = "ota_" + boot_complete_prefix;
619 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700620 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700621 SetProperty(system_reboot_reason_property, "reboot,ota");
622 if (GetProperty(bootloader_reboot_reason_property) == "") {
623 SetProperty(bootloader_reboot_reason_property, "reboot,ota");
624 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700625 }
626
627 return boot_complete_prefix;
628}
629
James Hawkinsef0a0902017-01-06 14:38:23 -0800630// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700631void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800632 std::string value = GetProperty(property);
633
James Hawkins27c05222017-01-26 11:55:44 -0800634 int32_t time_in_ms;
635 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800636 boot_event_store->AddBootEventWithValue(property, time_in_ms);
637 }
638}
639
James Hawkins1bfcaec2017-05-19 14:27:27 -0700640// A map from bootloader timing stage to the time that stage took during boot.
641typedef std::map<std::string, int32_t> BootloaderTimingMap;
642
643// Returns a mapping from bootloader stage names to the time those stages
644// took to boot.
645const BootloaderTimingMap GetBootLoaderTimings() {
646 BootloaderTimingMap timings;
647
648 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
649 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800650 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800651 if (value.empty()) {
652 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700653 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800654 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800655
656 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700657 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800658 // |stageTiming| is of the form 'stage:time'.
659 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700660 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800661
662 std::string stageName = stageTimingValues[0];
663 int32_t time_ms;
664 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700665 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800666 }
667 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800668
James Hawkins1bfcaec2017-05-19 14:27:27 -0700669 return timings;
670}
671
672// Parses and records the set of bootloader stages and associated boot times
673// from the ro.boot.boottime system property.
674void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
675 const BootloaderTimingMap& bootloader_timings) {
676 int32_t total_time = 0;
677 for (const auto& timing : bootloader_timings) {
678 total_time += timing.second;
679 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
680 }
681
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800682 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800683}
684
James Hawkins1bfcaec2017-05-19 14:27:27 -0700685// Records the closest estimation to the absolute device boot time, i.e.,
686// from power on to boot_complete, including bootloader times.
687void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
688 const BootloaderTimingMap& bootloader_timings,
689 std::chrono::milliseconds uptime) {
690 int32_t bootloader_time_ms = 0;
691
692 for (const auto& timing : bootloader_timings) {
693 if (timing.first.compare("SW") != 0) {
694 bootloader_time_ms += timing.second;
695 }
696 }
697
698 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
699 auto absolute_total =
700 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
701 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
702}
703
James Hawkinsc08e9962016-03-11 14:59:50 -0800704// Records several metrics related to the time it takes to boot the device,
705// including disambiguating boot time on encrypted or non-encrypted devices.
706void RecordBootComplete() {
707 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700708 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700709
James Hawkins1bfcaec2017-05-19 14:27:27 -0700710 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
711 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700712 time_t current_time_utc = time(nullptr);
713
714 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
715 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700716 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
717 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700718 }
719
720 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800721
James Hawkinsb9cf7712016-04-08 15:32:19 -0700722 // The boot_complete metric has two variants: boot_complete and
723 // ota_boot_complete. The latter signifies that the device is booting after
724 // a system update.
725 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700726 if (boot_complete_prefix.empty()) {
727 // The system is hosed because the build date property could not be read.
728 return;
729 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800730
731 // post_decrypt_time_elapsed is only logged on encrypted devices.
732 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
733 // Log the amount of time elapsed until the device is decrypted, which
734 // includes the variable amount of time the user takes to enter the
735 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700736 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800737
738 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700739 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700740 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700741 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800742 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700743 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800744 }
745
746 // Record the total time from device startup to boot complete, regardless of
747 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700748 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800749
750 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
751 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
752 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -0800753
James Hawkins1bfcaec2017-05-19 14:27:27 -0700754 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
755 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
756
757 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
758 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -0800759}
760
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800761// Records the boot_reason metric by querying the ro.boot.bootreason system
762// property.
763void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700764 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins5240f202017-09-15 16:01:57 -0700765 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700766 android::metricslogger::FIELD_PLATFORM_REASON, reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700767
768 // Log the raw bootloader_boot_reason property value.
769 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800770 BootEventRecordStore boot_event_store;
771 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700772
773 // Log the scrubbed system_boot_reason.
774 const std::string system_reason(BootReasonStrToReason(reason));
775 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
776 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
777
778 // Record the scrubbed system_boot_reason to the property
779 SetProperty(system_reboot_reason_property, system_reason);
780 if (reason == "") {
781 SetProperty(bootloader_reboot_reason_property, system_reason);
782 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800783}
784
James Hawkins500d7152016-02-16 15:05:54 -0800785// Records two metrics related to the user resetting a device: the time at
786// which the device is reset, and the time since the user last reset the
787// device. The former is only set once per-factory reset.
788void RecordFactoryReset() {
789 BootEventRecordStore boot_event_store;
790 BootEventRecordStore::BootEventRecord record;
791
792 time_t current_time_utc = time(nullptr);
793
James Hawkins0660b302016-03-08 16:18:15 -0800794 if (current_time_utc < 0) {
795 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700796 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
797 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -0700798
James Hawkins9aec9262017-01-31 11:42:24 -0800799 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700800 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700801 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
802 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -0800803 return;
804 } else {
James Hawkins9aec9262017-01-31 11:42:24 -0800805 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700806
James Hawkins9aec9262017-01-31 11:42:24 -0800807 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700808 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700809 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -0800810 }
811
James Hawkins500d7152016-02-16 15:05:54 -0800812 // The factory_reset boot event does not exist after the device is reset, so
813 // use this signal to mark the time of the factory reset.
814 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
815 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -0800816
817 // Don't log the time_since_factory_reset until some time has elapsed.
818 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -0800819 return;
820 }
821
822 // Calculate and record the difference in time between now and the
823 // factory_reset time.
824 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -0800825 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700826
James Hawkins9aec9262017-01-31 11:42:24 -0800827 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700828 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700829 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700830
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700831 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
832 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -0800833}
834
James Hawkinsabd73e62016-01-19 15:10:38 -0800835} // namespace
836
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700837int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800838 android::base::InitLogging(argv);
839
840 const std::string cmd_line = GetCommandLine(argc, argv);
841 LOG(INFO) << "Service started: " << cmd_line;
842
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800843 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -0700844 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -0800845 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800846 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -0800847 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800848 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700849 // clang-format off
850 { "help", no_argument, NULL, 'h' },
851 { "log", no_argument, NULL, 'l' },
852 { "print", no_argument, NULL, 'p' },
853 { "record", required_argument, NULL, 'r' },
854 { value_str, required_argument, NULL, 0 },
855 { boot_complete_str, no_argument, NULL, 0 },
856 { boot_reason_str, no_argument, NULL, 0 },
857 { factory_reset_str, no_argument, NULL, 0 },
858 { NULL, 0, NULL, 0 }
859 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800860 };
861
James Hawkinsc6275582016-03-22 10:47:44 -0700862 std::string boot_event;
863 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -0800864 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800865 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800866 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800867 // This case handles long options which have no single-character mapping.
868 case 0: {
869 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -0700870 if (option_name == value_str) {
871 // |optarg| is an external variable set by getopt representing
872 // the option argument.
873 value = optarg;
874 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -0800875 RecordBootComplete();
876 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800877 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -0800878 } else if (option_name == factory_reset_str) {
879 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800880 } else {
881 LOG(ERROR) << "Invalid option: " << option_name;
882 }
883 break;
884 }
885
James Hawkinsabd73e62016-01-19 15:10:38 -0800886 case 'h': {
887 ShowHelp(argv[0]);
888 break;
889 }
890
891 case 'l': {
892 LogBootEvents();
893 break;
894 }
895
896 case 'p': {
897 PrintBootEvents();
898 break;
899 }
900
901 case 'r': {
902 // |optarg| is an external variable set by getopt representing
903 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -0700904 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -0800905 break;
906 }
907
908 default: {
909 DCHECK_EQ(opt, '?');
910
911 // |optopt| is an external variable set by getopt representing
912 // the value of the invalid option.
913 LOG(ERROR) << "Invalid option: " << optopt;
914 ShowHelp(argv[0]);
915 return EXIT_FAILURE;
916 }
917 }
918 }
919
James Hawkinsc6275582016-03-22 10:47:44 -0700920 if (!boot_event.empty()) {
921 RecordBootEventFromCommandLine(boot_event, value);
922 }
923
James Hawkinsabd73e62016-01-19 15:10:38 -0800924 return 0;
925}