blob: f8eaa1cd3c281301a03427adc4f88d54e3effa90 [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 Hawkins25f71222017-10-10 16:37:05 -0700132constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800133constexpr int32_t kUnknownBootReason = 1;
134
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800135// A mapping from boot reason string, as read from the ro.boot.bootreason
136// system property, to a unique integer ID. Viewers of log data dashboards for
137// the boot_reason metric may refer to this mapping to discern the histogram
138// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800139const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700140 {"empty", kEmptyBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700141 {"unknown", kUnknownBootReason},
142 {"normal", 2},
143 {"recovery", 3},
144 {"reboot", 4},
145 {"PowerKey", 5},
146 {"hard_reset", 6},
147 {"kernel_panic", 7},
148 {"rpm_err", 8},
149 {"hw_reset", 9},
150 {"tz_err", 10},
151 {"adsp_err", 11},
152 {"modem_err", 12},
153 {"mba_err", 13},
154 {"Watchdog", 14},
155 {"Panic", 15},
156 {"power_key", 16},
157 {"power_on", 17},
158 {"Reboot", 18},
159 {"rtc", 19},
160 {"edl", 20},
161 {"oem_pon1", 21},
162 {"oem_powerkey", 22},
163 {"oem_unknown_reset", 23},
164 {"srto: HWWDT reset SC", 24},
165 {"srto: HWWDT reset platform", 25},
166 {"srto: bootloader", 26},
167 {"srto: kernel panic", 27},
168 {"srto: kernel watchdog reset", 28},
169 {"srto: normal", 29},
170 {"srto: reboot", 30},
171 {"srto: reboot-bootloader", 31},
172 {"srto: security watchdog reset", 32},
173 {"srto: wakesrc", 33},
174 {"srto: watchdog", 34},
175 {"srto:1-1", 35},
176 {"srto:omap_hsmm", 36},
177 {"srto:phy0", 37},
178 {"srto:rtc0", 38},
179 {"srto:touchpad", 39},
180 {"watchdog", 40},
181 {"watchdogr", 41},
182 {"wdog_bark", 42},
183 {"wdog_bite", 43},
184 {"wdog_reset", 44},
185 {"shutdown,", 45}, // Trailing comma is intentional.
186 {"shutdown,userrequested", 46},
187 {"reboot,bootloader", 47},
188 {"reboot,cold", 48},
189 {"reboot,recovery", 49},
190 {"thermal_shutdown", 50},
191 {"s3_wakeup", 51},
192 {"kernel_panic,sysrq", 52},
193 {"kernel_panic,NULL", 53},
194 {"kernel_panic,BUG", 54},
195 {"bootloader", 55},
196 {"cold", 56},
197 {"hard", 57},
198 {"warm", 58},
199 {"recovery", 59},
200 {"thermal-shutdown", 60},
201 {"shutdown,thermal", 61},
202 {"shutdown,battery", 62},
203 {"reboot,ota", 63},
204 {"reboot,factory_reset", 64},
205 {"reboot,", 65},
206 {"reboot,shell", 66},
207 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700208 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700209 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700210 {"cold,powerkey", 70},
211 {"warm,s3_wakeup", 71},
212 {"hard,hw_reset", 72},
213 {"shutdown,suspend", 73}, // Suspend to RAM
214 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800215};
216
217// Converts a string value representing the reason the system booted to an
218// integer representation. This is necessary for logging the boot_reason metric
219// via Tron, which does not accept non-integer buckets in histograms.
220int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800221 auto mapping = kBootReasonMap.find(boot_reason);
222 if (mapping != kBootReasonMap.end()) {
223 return mapping->second;
224 }
225
James Hawkins25f71222017-10-10 16:37:05 -0700226 if (boot_reason.empty()) {
227 return kEmptyBootReason;
228 }
229
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800230 LOG(INFO) << "Unknown boot reason: " << boot_reason;
231 return kUnknownBootReason;
232}
233
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700234// Canonical list of supported primary reboot reasons.
235const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700236 // clang-format off
237 // kernel
238 "watchdog",
239 "kernel_panic",
240 // strong
241 "recovery", // Should not happen from ro.boot.bootreason
242 "bootloader", // Should not happen from ro.boot.bootreason
243 // blunt
244 "cold",
245 "hard",
246 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700247 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700248 "shutdown", // Can not happen from ro.boot.bootreason
249 "reboot", // Default catch-all for anything unknown
250 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700251};
252
253// Returns true if the supplied reason prefix is considered detailed enough.
254bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700255 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700256 if (s == "cold") break;
257 // Prefix defined as terminated by a nul or comma (,).
258 if (android::base::StartsWith(r, s.c_str()) &&
259 ((r.length() == s.length()) || (r[s.length()] == ','))) {
260 return true;
261 }
262 }
263 return false;
264}
265
266// Returns true if the supplied reason prefix is associated with the kernel.
267bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700268 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700269 if (s == "recovery") break;
270 // 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// Returns true if the supplied reason prefix is considered known.
280bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700281 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700282 // Prefix defined as terminated by a nul or comma (,).
283 if (android::base::StartsWith(r, s.c_str()) &&
284 ((r.length() == s.length()) || (r[s.length()] == ','))) {
285 return true;
286 }
287 }
288 return false;
289}
290
291// If the reboot reason should be improved, report true if is too blunt.
292bool isBluntRebootReason(const std::string& r) {
293 if (isStrongRebootReason(r)) return false;
294
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700295 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700296
297 size_t pos = 0;
298 while ((pos = r.find(',', pos)) != std::string::npos) {
299 ++pos;
300 std::string next(r.substr(pos));
301 if (next.length() == 0) break;
302 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700303 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
304 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700305 }
306 return true;
307}
308
Mark Salyzyn64610892017-09-18 10:41:14 -0700309bool readPstoreConsole(std::string& console) {
310 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
311 return true;
312 }
313 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
314}
315
316bool addKernelPanicSubReason(const std::string& console, std::string& ret) {
317 // Check for kernel panic types to refine information
318 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
319 // Can not happen, except on userdebug, during testing/debugging.
320 ret = "kernel_panic,sysrq";
321 return true;
322 }
323 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
324 std::string::npos) {
325 ret = "kernel_panic,NULL";
326 return true;
327 }
328 if (console.rfind("Kernel BUG at ") != std::string::npos) {
329 ret = "kernel_panic,BUG";
330 return true;
331 }
332 return false;
333}
334
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700335// std::transform Helper callback functions:
336// Converts a string value representing the reason the system booted to a
337// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700338char tounderline(char c) {
339 return ::isblank(c) ? '_' : c;
340}
341char toprintable(char c) {
342 return ::isprint(c) ? c : '?';
343}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700344
345const char system_reboot_reason_property[] = "sys.boot.reason";
346const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
347const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
348
349// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
350std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700351 static const size_t max_reason_length = 256;
352
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700353 std::string ret(GetProperty(system_reboot_reason_property));
354 std::string reason(boot_reason);
355 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
356 if (reason == ret) ret = "";
357
358 // Cleanup boot_reason regarding acceptable character set
359 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
360 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
361 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
362
363 // Is the current system boot reason sys.boot.reason valid?
364 if (!isKnownRebootReason(ret)) ret = "";
365
366 if (ret == "") {
367 // Is the bootloader boot reason ro.boot.bootreason known?
368 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700369 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700370 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700371 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700372 if (r == s) {
373 if (isBluntRebootReason(s)) {
374 blunt = s;
375 } else {
376 ret = s;
377 break;
378 }
379 }
380 }
381 if (ret == "") ret = blunt;
382 if (ret != "") break;
383 }
384 }
385
386 if (ret == "") {
387 // A series of checks to take some officially unsupported reasons
388 // reported by the bootloader and find some logical and canonical
389 // sense. In an ideal world, we would require those bootloaders
390 // to behave and follow our standards.
391 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700392 {"watchdog", "wdog"},
393 {"cold,powerkey", "powerkey"},
394 {"kernel_panic", "panic"},
395 {"shutdown,thermal", "thermal"},
396 {"warm,s3_wakeup", "s3_wakeup"},
397 {"hard,hw_reset", "hw_reset"},
398 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700399 };
400
401 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700402 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700403 if (reason.find(s.first) != std::string::npos) {
404 ret = s.first;
405 break;
406 }
407 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
408 ret = s.first;
409 break;
410 }
411 }
412 }
413
414 // If watchdog is the reason, see if there is a security angle?
415 if (ret == "watchdog") {
416 if (reason.find("sec") != std::string::npos) {
417 ret += ",security";
418 }
419 }
420
Mark Salyzyn64610892017-09-18 10:41:14 -0700421 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700422 // Check to see if last klog has some refinement hints.
423 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700424 if (readPstoreConsole(content)) {
425 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700426 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700427 } else if (isBluntRebootReason(ret)) {
428 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700429
Mark Salyzyn64610892017-09-18 10:41:14 -0700430 // Check to see if last klog has some refinement hints.
431 std::string content;
432 if (readPstoreConsole(content)) {
433 // The toybox reboot command used directly (unlikely)? But also
434 // catches init's response to Android's more controlled reboot command.
435 if (content.rfind("reboot: Power down") != std::string::npos) {
436 ret = "shutdown"; // Still too blunt, but more accurate.
437 // ToDo: init should record the shutdown reason to kernel messages ala:
438 // init: shutdown system with command 'last_reboot_reason'
439 // so that if pstore has persistence we can get some details
440 // that could be missing in last_reboot_reason_property.
441 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700442
Mark Salyzyn64610892017-09-18 10:41:14 -0700443 static const char cmd[] = "reboot: Restarting system with command '";
444 size_t pos = content.rfind(cmd);
445 if (pos != std::string::npos) {
446 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700447 std::string subReason(content.substr(pos, max_reason_length));
448 for (pos = 0; pos < subReason.length(); ++pos) {
449 char c = tounderline(subReason[pos]);
450 if (!::isprint(c) || (c == '\'')) {
451 subReason.erase(pos);
452 break;
453 }
454 subReason[pos] = ::tolower(c);
455 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700456 if (subReason != "") { // Will not land "reboot" as that is too blunt.
457 if (isKernelRebootReason(subReason)) {
458 ret = "reboot," + subReason; // User space can't talk kernel reasons.
459 } else {
460 ret = subReason;
461 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700462 }
463 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700464
Mark Salyzyn64610892017-09-18 10:41:14 -0700465 // Check for kernel panics, allowed to override reboot command.
466 if (!addKernelPanicSubReason(content, ret) &&
467 // check for long-press power down
468 ((content.rfind("Power held for ") != std::string::npos) ||
469 (content.rfind("charger: [") != std::string::npos))) {
470 ret = "cold";
471 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700472 }
473
474 // The following battery test should migrate to a default system health HAL
475
476 // Let us not worry if the reboot command was issued, for the cases of
477 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
478 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
479 // battery could conceivably lead to these, so worthy of override.
480 if (isBluntRebootReason(ret)) {
481 // Heuristic to determine if shutdown possibly because of a dead battery?
482 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700483 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700484 static const char battery[] = "healthd: battery l=";
Mark Salyzyn64610892017-09-18 10:41:14 -0700485 size_t pos = content.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700486 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700487 if (pos != std::string::npos) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700488 digits = content.substr(pos + strlen(battery));
489 }
490 char* endptr = NULL;
491 unsigned long long level = strtoull(digits.c_str(), &endptr, 10);
492 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700493 LOG(INFO) << "Battery level at shutdown " << level << "%";
494 if (level <= battery_dead_threshold) {
495 ret = "shutdown,battery";
496 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700497 } else { // Most likely
498 digits = ""; // reset digits
499
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700500 // Content buffer no longer will have console data. Beware if more
501 // checks added below, that depend on parsing console content.
502 content = "";
503
504 LOG(DEBUG) << "Can not find last low battery in last console messages";
505 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700506 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700507 if (fp != nullptr) {
508 android::base::ReadFdToString(fileno(fp), &content);
509 }
510 android_logcat_pclose(&ctx, fp);
511 android_logcat_destroy(&ctx);
512 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
513 const char* match = logcat_battery;
514
515 if (content == "") {
516 // Service logd.klog not running, go to smaller buffer in the kernel.
517 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
518 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700519 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700520 std::unique_ptr<char[]> buf(new char[len]);
521 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
522 if (rc < len) {
523 len = rc + 1;
524 }
525 buf[--len] = '\0';
526 content = buf.get();
527 }
528 match = battery;
529 }
530
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700531 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700532 if (pos != std::string::npos) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700533 digits = content.substr(pos + strlen(match));
534 }
535 endptr = NULL;
536 level = strtoull(digits.c_str(), &endptr, 10);
537 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700538 LOG(INFO) << "Battery level at startup " << level << "%";
539 if (level <= battery_dead_threshold) {
540 ret = "shutdown,battery";
541 }
542 } else {
543 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
544 }
545 }
546 }
547
548 // Is there a controlled shutdown hint in last_reboot_reason_property?
549 if (isBluntRebootReason(ret)) {
550 // Content buffer no longer will have console data. Beware if more
551 // checks added below, that depend on parsing console content.
552 content = GetProperty(last_reboot_reason_property);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700553 // Cleanup last_boot_reason regarding acceptable character set
554 std::transform(content.begin(), content.end(), content.begin(), ::tolower);
555 std::transform(content.begin(), content.end(), content.begin(), tounderline);
556 std::transform(content.begin(), content.end(), content.begin(), toprintable);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700557
Mark Salyzyn62909822017-10-09 09:27:16 -0700558 // Anything in last is better than 'super-blunt' reboot or shutdown.
559 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
560 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700561 }
562 }
563
564 // Other System Health HAL reasons?
565
566 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
567 // possibly offer hardware-specific clues from the PMIC.
568 }
569
570 // If unknown left over from above, make it "reboot,<boot_reason>"
571 if (ret == "") {
572 ret = "reboot";
573 if (android::base::StartsWith(reason, "reboot")) {
574 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700575 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700576 reason = reason.substr(1);
577 }
578 }
579 if (reason != "") {
580 ret += ",";
581 ret += reason;
582 }
583 }
584
585 LOG(INFO) << "Canonical boot reason: " << ret;
586 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
587 // Rewrite as it must be old news, kernel reasons trump user space.
588 SetProperty(last_reboot_reason_property, ret);
589 }
590 return ret;
591}
592
James Hawkinsb9cf7712016-04-08 15:32:19 -0700593// Returns the appropriate metric key prefix for the boot_complete metric such
594// that boot metrics after a system update are labeled as ota_boot_complete;
595// otherwise, they are labeled as boot_complete. This method encapsulates the
596// bookkeeping required to track when a system update has occurred by storing
597// the UTC timestamp of the system build date and comparing against the current
598// system build date.
599std::string CalculateBootCompletePrefix() {
600 static const std::string kBuildDateKey = "build_date";
601 std::string boot_complete_prefix = "boot_complete";
602
603 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700604 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700605 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700606 return std::string();
607 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700608
609 BootEventRecordStore boot_event_store;
610 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700611 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
612 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
613 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700614 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700615 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700616 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700617 boot_complete_prefix = "ota_" + boot_complete_prefix;
618 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700619 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700620 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700621 }
622
623 return boot_complete_prefix;
624}
625
James Hawkinsef0a0902017-01-06 14:38:23 -0800626// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700627void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800628 std::string value = GetProperty(property);
629
James Hawkins27c05222017-01-26 11:55:44 -0800630 int32_t time_in_ms;
631 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800632 boot_event_store->AddBootEventWithValue(property, time_in_ms);
633 }
634}
635
James Hawkins1bfcaec2017-05-19 14:27:27 -0700636// A map from bootloader timing stage to the time that stage took during boot.
637typedef std::map<std::string, int32_t> BootloaderTimingMap;
638
639// Returns a mapping from bootloader stage names to the time those stages
640// took to boot.
641const BootloaderTimingMap GetBootLoaderTimings() {
642 BootloaderTimingMap timings;
643
644 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
645 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800646 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800647 if (value.empty()) {
648 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700649 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800650 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800651
652 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700653 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800654 // |stageTiming| is of the form 'stage:time'.
655 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700656 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800657
658 std::string stageName = stageTimingValues[0];
659 int32_t time_ms;
660 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700661 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800662 }
663 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800664
James Hawkins1bfcaec2017-05-19 14:27:27 -0700665 return timings;
666}
667
668// Parses and records the set of bootloader stages and associated boot times
669// from the ro.boot.boottime system property.
670void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
671 const BootloaderTimingMap& bootloader_timings) {
672 int32_t total_time = 0;
673 for (const auto& timing : bootloader_timings) {
674 total_time += timing.second;
675 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
676 }
677
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800678 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800679}
680
James Hawkins1bfcaec2017-05-19 14:27:27 -0700681// Records the closest estimation to the absolute device boot time, i.e.,
682// from power on to boot_complete, including bootloader times.
683void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
684 const BootloaderTimingMap& bootloader_timings,
685 std::chrono::milliseconds uptime) {
686 int32_t bootloader_time_ms = 0;
687
688 for (const auto& timing : bootloader_timings) {
689 if (timing.first.compare("SW") != 0) {
690 bootloader_time_ms += timing.second;
691 }
692 }
693
694 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
695 auto absolute_total =
696 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
697 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
698}
699
James Hawkinsc08e9962016-03-11 14:59:50 -0800700// Records several metrics related to the time it takes to boot the device,
701// including disambiguating boot time on encrypted or non-encrypted devices.
702void RecordBootComplete() {
703 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700704 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700705
James Hawkins1bfcaec2017-05-19 14:27:27 -0700706 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
707 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700708 time_t current_time_utc = time(nullptr);
709
710 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
711 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700712 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
713 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700714 }
715
716 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800717
James Hawkinsb9cf7712016-04-08 15:32:19 -0700718 // The boot_complete metric has two variants: boot_complete and
719 // ota_boot_complete. The latter signifies that the device is booting after
720 // a system update.
721 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700722 if (boot_complete_prefix.empty()) {
723 // The system is hosed because the build date property could not be read.
724 return;
725 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800726
727 // post_decrypt_time_elapsed is only logged on encrypted devices.
728 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
729 // Log the amount of time elapsed until the device is decrypted, which
730 // includes the variable amount of time the user takes to enter the
731 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700732 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800733
734 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700735 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700736 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700737 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800738 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700739 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800740 }
741
742 // Record the total time from device startup to boot complete, regardless of
743 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700744 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800745
746 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
747 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
748 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -0800749
James Hawkins1bfcaec2017-05-19 14:27:27 -0700750 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
751 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
752
753 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
754 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -0800755}
756
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800757// Records the boot_reason metric by querying the ro.boot.bootreason system
758// property.
759void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700760 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -0700761
762 if (reason.empty()) {
763 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
764 // (and not corruption anywhere else in the reporting pipeline).
765 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
766 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
767 } else {
768 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
769 android::metricslogger::FIELD_PLATFORM_REASON, reason);
770 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700771
772 // Log the raw bootloader_boot_reason property value.
773 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800774 BootEventRecordStore boot_event_store;
775 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700776
777 // Log the scrubbed system_boot_reason.
778 const std::string system_reason(BootReasonStrToReason(reason));
779 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
780 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
781
782 // Record the scrubbed system_boot_reason to the property
783 SetProperty(system_reboot_reason_property, system_reason);
784 if (reason == "") {
785 SetProperty(bootloader_reboot_reason_property, system_reason);
786 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800787}
788
James Hawkins500d7152016-02-16 15:05:54 -0800789// Records two metrics related to the user resetting a device: the time at
790// which the device is reset, and the time since the user last reset the
791// device. The former is only set once per-factory reset.
792void RecordFactoryReset() {
793 BootEventRecordStore boot_event_store;
794 BootEventRecordStore::BootEventRecord record;
795
796 time_t current_time_utc = time(nullptr);
797
James Hawkins0660b302016-03-08 16:18:15 -0800798 if (current_time_utc < 0) {
799 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700800 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
801 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -0700802
James Hawkins9aec9262017-01-31 11:42:24 -0800803 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700804 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700805 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
806 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -0800807 return;
808 } else {
James Hawkins9aec9262017-01-31 11:42:24 -0800809 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700810
James Hawkins9aec9262017-01-31 11:42:24 -0800811 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700812 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700813 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -0800814 }
815
James Hawkins500d7152016-02-16 15:05:54 -0800816 // The factory_reset boot event does not exist after the device is reset, so
817 // use this signal to mark the time of the factory reset.
818 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
819 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -0800820
821 // Don't log the time_since_factory_reset until some time has elapsed.
822 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -0800823 return;
824 }
825
826 // Calculate and record the difference in time between now and the
827 // factory_reset time.
828 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -0800829 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700830
James Hawkins9aec9262017-01-31 11:42:24 -0800831 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700832 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700833 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700834
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700835 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
836 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -0800837}
838
James Hawkinsabd73e62016-01-19 15:10:38 -0800839} // namespace
840
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700841int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800842 android::base::InitLogging(argv);
843
844 const std::string cmd_line = GetCommandLine(argc, argv);
845 LOG(INFO) << "Service started: " << cmd_line;
846
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800847 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -0700848 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -0800849 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800850 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -0800851 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800852 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700853 // clang-format off
854 { "help", no_argument, NULL, 'h' },
855 { "log", no_argument, NULL, 'l' },
856 { "print", no_argument, NULL, 'p' },
857 { "record", required_argument, NULL, 'r' },
858 { value_str, required_argument, NULL, 0 },
859 { boot_complete_str, no_argument, NULL, 0 },
860 { boot_reason_str, no_argument, NULL, 0 },
861 { factory_reset_str, no_argument, NULL, 0 },
862 { NULL, 0, NULL, 0 }
863 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800864 };
865
James Hawkinsc6275582016-03-22 10:47:44 -0700866 std::string boot_event;
867 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -0800868 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800869 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800870 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800871 // This case handles long options which have no single-character mapping.
872 case 0: {
873 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -0700874 if (option_name == value_str) {
875 // |optarg| is an external variable set by getopt representing
876 // the option argument.
877 value = optarg;
878 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -0800879 RecordBootComplete();
880 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800881 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -0800882 } else if (option_name == factory_reset_str) {
883 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800884 } else {
885 LOG(ERROR) << "Invalid option: " << option_name;
886 }
887 break;
888 }
889
James Hawkinsabd73e62016-01-19 15:10:38 -0800890 case 'h': {
891 ShowHelp(argv[0]);
892 break;
893 }
894
895 case 'l': {
896 LogBootEvents();
897 break;
898 }
899
900 case 'p': {
901 PrintBootEvents();
902 break;
903 }
904
905 case 'r': {
906 // |optarg| is an external variable set by getopt representing
907 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -0700908 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -0800909 break;
910 }
911
912 default: {
913 DCHECK_EQ(opt, '?');
914
915 // |optopt| is an external variable set by getopt representing
916 // the value of the invalid option.
917 LOG(ERROR) << "Invalid option: " << optopt;
918 ShowHelp(argv[0]);
919 return EXIT_FAILURE;
920 }
921 }
922 }
923
James Hawkinsc6275582016-03-22 10:47:44 -0700924 if (!boot_event.empty()) {
925 RecordBootEventFromCommandLine(boot_event, value);
926 }
927
James Hawkinsabd73e62016-01-19 15:10:38 -0800928 return 0;
929}