blob: fb0423a6e0c2468f97320dcea307789c372d831f [file] [log] [blame]
James Hawkinsabd73e62016-01-19 15:10:38 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// The bootstat command provides options to persist boot events with the current
18// timestamp, dump the persisted events, and log all events to EventLog to be
19// uploaded to Android log storage via Tron.
20
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080021#include <getopt.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070022#include <sys/klog.h>
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070023#include <unistd.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070024
James Hawkinse78ea772017-03-24 11:43:02 -070025#include <chrono>
James Hawkins0660b302016-03-08 16:18:15 -080026#include <cmath>
James Hawkinsabd73e62016-01-19 15:10:38 -080027#include <cstddef>
28#include <cstdio>
James Hawkins500d7152016-02-16 15:05:54 -080029#include <ctime>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080030#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080031#include <memory>
Mark Salyzyn25900dd2018-03-16 09:05:59 -070032#include <regex>
James Hawkinsabd73e62016-01-19 15:10:38 -080033#include <string>
Mark Salyzyn853bb802018-03-16 08:44:56 -070034#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080035#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070036
James Hawkinse78ea772017-03-24 11:43:02 -070037#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070038#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080039#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070040#include <android-base/parseint.h>
Luis Hector Chavez03aae152018-04-12 15:25:15 -070041#include <android-base/properties.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080042#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070043#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070044#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080045#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070046#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080047#include <metricslogger/metrics_logger.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070048
James Hawkinsabd73e62016-01-19 15:10:38 -080049#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080050
51namespace {
52
James Hawkinsabd73e62016-01-19 15:10:38 -080053// Scans the boot event record store for record files and logs each boot event
54// via EventLog.
55void LogBootEvents() {
56 BootEventRecordStore boot_event_store;
57
58 auto events = boot_event_store.GetAllBootEvents();
59 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080060 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080061 }
62}
63
James Hawkinsc6275582016-03-22 10:47:44 -070064// Records the named boot |event| to the record store. If |value| is non-empty
65// and is a proper string representation of an integer value, the converted
66// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070067void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070068 BootEventRecordStore boot_event_store;
69 if (!value_str.empty()) {
70 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070071 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070072 boot_event_store.AddBootEventWithValue(event, value);
73 }
James Hawkinsc6275582016-03-22 10:47:44 -070074 } else {
75 boot_event_store.AddBootEvent(event);
76 }
77}
78
James Hawkinsabd73e62016-01-19 15:10:38 -080079void PrintBootEvents() {
80 printf("Boot events:\n");
81 printf("------------\n");
82
83 BootEventRecordStore boot_event_store;
84 auto events = boot_event_store.GetAllBootEvents();
85 for (auto i = events.cbegin(); i != events.cend(); ++i) {
86 printf("%s\t%d\n", i->first.c_str(), i->second);
87 }
88}
89
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070090void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080091 fprintf(stderr, "Usage: %s [options]\n", cmd);
92 fprintf(stderr,
93 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080094 " -h, --help Show this help\n"
95 " -l, --log Log all metrics to logstorage\n"
96 " -p, --print Dump the boot event records to the console\n"
97 " -r, --record Record the timestamp of a named boot event\n"
98 " --value Optional value to associate with the boot event\n"
99 " --record_boot_complete Record metrics related to the time for the device boot\n"
100 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -0800101 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800102}
103
104// Constructs a readable, printable string from the givencommand line
105// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700106std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800107 std::string cmd;
108 for (int i = 0; i < argc; ++i) {
109 cmd += argv[i];
110 cmd += " ";
111 }
112
113 return cmd;
114}
115
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800116// Convenience wrapper over the property API that returns an
117// std::string.
118std::string GetProperty(const char* key) {
119 std::vector<char> temp(PROPERTY_VALUE_MAX);
120 const int len = property_get(key, &temp[0], nullptr);
121 if (len < 0) {
122 return "";
123 }
124 return std::string(&temp[0], len);
125}
126
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700127void SetProperty(const char* key, const std::string& val) {
128 property_set(key, val.c_str());
129}
130
131void SetProperty(const char* key, const char* val) {
132 property_set(key, val);
133}
134
James Hawkins25f71222017-10-10 16:37:05 -0700135constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800136constexpr int32_t kUnknownBootReason = 1;
137
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800138// A mapping from boot reason string, as read from the ro.boot.bootreason
139// system property, to a unique integer ID. Viewers of log data dashboards for
140// the boot_reason metric may refer to this mapping to discern the histogram
141// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800142const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700143 {"empty", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700144 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700145 {"normal", 2},
146 {"recovery", 3},
147 {"reboot", 4},
148 {"PowerKey", 5},
149 {"hard_reset", 6},
150 {"kernel_panic", 7},
151 {"rpm_err", 8},
152 {"hw_reset", 9},
153 {"tz_err", 10},
154 {"adsp_err", 11},
155 {"modem_err", 12},
156 {"mba_err", 13},
157 {"Watchdog", 14},
158 {"Panic", 15},
159 {"power_key", 16},
160 {"power_on", 17},
161 {"Reboot", 18},
162 {"rtc", 19},
163 {"edl", 20},
164 {"oem_pon1", 21},
165 {"oem_powerkey", 22},
166 {"oem_unknown_reset", 23},
167 {"srto: HWWDT reset SC", 24},
168 {"srto: HWWDT reset platform", 25},
169 {"srto: bootloader", 26},
170 {"srto: kernel panic", 27},
171 {"srto: kernel watchdog reset", 28},
172 {"srto: normal", 29},
173 {"srto: reboot", 30},
174 {"srto: reboot-bootloader", 31},
175 {"srto: security watchdog reset", 32},
176 {"srto: wakesrc", 33},
177 {"srto: watchdog", 34},
178 {"srto:1-1", 35},
179 {"srto:omap_hsmm", 36},
180 {"srto:phy0", 37},
181 {"srto:rtc0", 38},
182 {"srto:touchpad", 39},
183 {"watchdog", 40},
184 {"watchdogr", 41},
185 {"wdog_bark", 42},
186 {"wdog_bite", 43},
187 {"wdog_reset", 44},
188 {"shutdown,", 45}, // Trailing comma is intentional.
189 {"shutdown,userrequested", 46},
190 {"reboot,bootloader", 47},
191 {"reboot,cold", 48},
192 {"reboot,recovery", 49},
193 {"thermal_shutdown", 50},
194 {"s3_wakeup", 51},
195 {"kernel_panic,sysrq", 52},
196 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700197 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700198 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700199 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700200 {"bootloader", 55},
201 {"cold", 56},
202 {"hard", 57},
203 {"warm", 58},
Mark Salyzyn15199252018-03-16 09:26:05 -0700204 {"reboot,kernel_power_off_charging__reboot_system", 59}, // Can not happen
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700205 {"thermal-shutdown", 60},
206 {"shutdown,thermal", 61},
207 {"shutdown,battery", 62},
208 {"reboot,ota", 63},
209 {"reboot,factory_reset", 64},
210 {"reboot,", 65},
211 {"reboot,shell", 66},
212 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700213 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700214 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700215 {"cold,powerkey", 70},
216 {"warm,s3_wakeup", 71},
217 {"hard,hw_reset", 72},
218 {"shutdown,suspend", 73}, // Suspend to RAM
219 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700220 {"power_on_key", 75},
221 {"reboot_by_key", 76},
222 {"wdt_by_pass_pwk", 77},
223 {"reboot_longkey", 78},
224 {"powerkey", 79},
225 {"usb", 80},
226 {"wdt", 81},
227 {"tool_by_pass_pwk", 82},
228 {"2sec_reboot", 83},
229 {"reboot,by_key", 84},
230 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700231 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700232 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700233 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
234 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn75046892018-05-03 13:11:15 -0700235 {"reboot,rescueparty", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800236 {"charge", 91},
237 {"oem_tz_crash", 92},
238 {"uvlo", 93},
239 {"oem_ps_hold", 94},
240 {"abnormal_reset", 95},
241 {"oemerr_unknown", 96},
242 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800243 {"watchdog_apps_bite", 98},
244 {"xpu_err", 99},
245 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800246 {"watchdog_rpm", 101},
247 {"watchdog_nonsec", 102},
248 {"watchdog_apps_bark", 103},
249 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800250 {"reboot_smpl", 105},
251 {"watchdog_sdi_apps_reset", 106},
252 {"smpl", 107},
253 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800254 {"reboot_normal", 109},
255 {"oem_lpass_cfg", 110},
256 {"oem_xpu_ns_error", 111},
257 {"power_key_press", 112},
258 {"hardware_reset", 113},
259 {"reboot_by_powerkey", 114},
260 {"reboot_verity", 115},
261 {"oem_rpm_undef_error", 116},
262 {"oem_crash_on_the_lk", 117},
263 {"oem_rpm_reset", 118},
264 {"oem_lpass_cfg", 119},
265 {"oem_xpu_ns_error", 120},
266 {"factory_cable", 121},
267 {"oem_ar6320_failed_to_powerup", 122},
268 {"watchdog_rpm_bite", 123},
269 {"power_on_cable", 124},
270 {"reboot_unknown", 125},
271 {"wireless_charger", 126},
272 {"0x776655ff", 127},
273 {"oem_thermal_bite_reset", 128},
274 {"charger", 129},
275 {"pon1", 130},
276 {"unknown", 131},
277 {"reboot_rtc", 132},
278 {"cold_boot", 133},
279 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800280 {"power-on", 135},
281 {"oem_adsp_resetting_the_soc", 136},
282 {"kpdpwr", 137},
283 {"oem_modem_timeout_waiting", 138},
284 {"usb_chg", 139},
285 {"warm_reset_0x02", 140},
286 {"warm_reset_0x80", 141},
287 {"pon_reason_0xb0", 142},
288 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800289 {"reboot_recovery_mode", 144},
290 {"oem_sdi_err_fatal", 145},
291 {"pmic_watchdog", 146},
292 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700293 {"cold,charger", 148},
294 {"cold,rtc", 149},
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700295 {"cold,rtc,2sec", 150},
296 {"reboot,tool", 151},
297 {"reboot,wdt", 152},
298 {"reboot,unknown", 153},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700299 {"kernel_panic,audit", 154},
300 {"kernel_panic,atomic", 155},
301 {"kernel_panic,hung", 156},
302 {"kernel_panic,hung,rcu", 157},
303 {"kernel_panic,init", 158},
304 {"kernel_panic,oom", 159},
305 {"kernel_panic,stack", 160},
Mark Salyzynafd66f22018-03-19 15:16:29 -0700306 {"kernel_panic,sysrq,livelock,alarm", 161}, // llkd
307 {"kernel_panic,sysrq,livelock,driver", 162}, // llkd
308 {"kernel_panic,sysrq,livelock,zombie", 163}, // llkd
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700309 {"kernel_panic,modem", 164},
310 {"kernel_panic,adsp", 165},
311 {"kernel_panic,dsps", 166},
312 {"kernel_panic,wcnss", 167},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800313};
314
315// Converts a string value representing the reason the system booted to an
316// integer representation. This is necessary for logging the boot_reason metric
317// via Tron, which does not accept non-integer buckets in histograms.
318int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800319 auto mapping = kBootReasonMap.find(boot_reason);
320 if (mapping != kBootReasonMap.end()) {
321 return mapping->second;
322 }
323
James Hawkins25f71222017-10-10 16:37:05 -0700324 if (boot_reason.empty()) {
325 return kEmptyBootReason;
326 }
327
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800328 LOG(INFO) << "Unknown boot reason: " << boot_reason;
329 return kUnknownBootReason;
330}
331
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700332// Canonical list of supported primary reboot reasons.
333const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700334 // clang-format off
335 // kernel
336 "watchdog",
337 "kernel_panic",
338 // strong
339 "recovery", // Should not happen from ro.boot.bootreason
340 "bootloader", // Should not happen from ro.boot.bootreason
341 // blunt
342 "cold",
343 "hard",
344 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700345 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700346 "shutdown", // Can not happen from ro.boot.bootreason
347 "reboot", // Default catch-all for anything unknown
348 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700349};
350
351// Returns true if the supplied reason prefix is considered detailed enough.
352bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700353 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700354 if (s == "cold") break;
355 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800356 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700357 return true;
358 }
359 }
360 return false;
361}
362
363// Returns true if the supplied reason prefix is associated with the kernel.
364bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700365 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700366 if (s == "recovery") break;
367 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800368 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700369 return true;
370 }
371 }
372 return false;
373}
374
375// Returns true if the supplied reason prefix is considered known.
376bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700377 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700378 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800379 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700380 return true;
381 }
382 }
383 return false;
384}
385
386// If the reboot reason should be improved, report true if is too blunt.
387bool isBluntRebootReason(const std::string& r) {
388 if (isStrongRebootReason(r)) return false;
389
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700390 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700391
392 size_t pos = 0;
393 while ((pos = r.find(',', pos)) != std::string::npos) {
394 ++pos;
395 std::string next(r.substr(pos));
396 if (next.length() == 0) break;
397 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700398 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
399 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700400 }
401 return true;
402}
403
Mark Salyzyn64610892017-09-18 10:41:14 -0700404bool readPstoreConsole(std::string& console) {
405 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
406 return true;
407 }
408 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
409}
410
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700411// Implement a variant of std::string::rfind that is resilient to errors in
412// the data stream being inspected.
413class pstoreConsole {
414 private:
415 const size_t kBitErrorRate = 8; // number of bits per error
416 const std::string& console;
417
418 // Number of bits that differ between the two arguments l and r.
419 // Returns zero if the values for l and r are identical.
420 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
421
422 // A string comparison function, reports the number of errors discovered
423 // in the match to a maximum of the bitLength / kBitErrorRate, at that
424 // point returning npos to indicate match is too poor.
425 //
426 // Since called in rfind which works backwards, expect cache locality will
427 // help if we check in reverse here as well for performance.
428 //
429 // Assumption: l (from console.c_str() + pos) is long enough to house
430 // _r.length(), checked in rfind caller below.
431 //
432 size_t numError(size_t pos, const std::string& _r) const {
433 const char* l = console.c_str() + pos;
434 const char* r = _r.c_str();
435 size_t n = _r.length();
436 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
437 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
438 size_t count = 0;
439 n = 0;
440 do {
441 // individual character bit error rate > threshold + slop
442 size_t num = numError(*--le, *--re);
443 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
444 // total bit error rate > threshold + slop
445 count += num;
446 ++n;
447 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
448 return std::string::npos;
449 }
450 } while (le != reinterpret_cast<const uint8_t*>(l));
451 return count;
452 }
453
454 public:
455 explicit pstoreConsole(const std::string& console) : console(console) {}
456 // scope of argument must be equal to or greater than scope of pstoreConsole
457 explicit pstoreConsole(const std::string&& console) = delete;
458 explicit pstoreConsole(std::string&& console) = delete;
459
460 // Our implementation of rfind, use exact match first, then resort to fuzzy.
461 size_t rfind(const std::string& needle) const {
462 size_t pos = console.rfind(needle); // exact match?
463 if (pos != std::string::npos) return pos;
464
465 // Check to make sure needle fits in console string.
466 pos = console.length();
467 if (needle.length() > pos) return std::string::npos;
468 pos -= needle.length();
469 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800470 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700471 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800472 if (pos == 0) break;
473 --pos;
474 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700475 return std::string::npos;
476 }
477
478 // Our implementation of find, use only fuzzy match.
479 size_t find(const std::string& needle, size_t start = 0) const {
480 // Check to make sure needle fits in console string.
481 if (needle.length() > console.length()) return std::string::npos;
482 const size_t last_pos = console.length() - needle.length();
483 // fuzzy match to maximum kBitErrorRate
484 for (size_t pos = start; pos <= last_pos; ++pos) {
485 if (numError(pos, needle) != std::string::npos) return pos;
486 }
487 return std::string::npos;
488 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700489
490 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700491};
492
493// If bit error match to needle, correct it.
494// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700495bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700496 bool corrected = false;
497 if (reason.length() < needle.length()) return corrected;
498 const pstoreConsole console(reason);
499 const size_t last_pos = reason.length() - needle.length();
500 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
501 pos = console.find(needle, pos);
502 if (pos == std::string::npos) break;
503
504 // exact match has no malice
505 if (needle == reason.substr(pos, needle.length())) continue;
506
507 corrected = true;
508 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
509 }
510 return corrected;
511}
512
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700513// If bit error match to needle, correct it.
514// Return true if any corrections were discovered and applied.
515// Try again if we can replace underline with spaces.
516bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
517 bool corrected = correctForBitError(reason, needle);
518 std::string _needle(needle);
519 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
520 [](char c) { return (c == '_') ? ' ' : c; });
521 if (needle != _needle) {
522 corrected |= correctForBitError(reason, _needle);
523 }
524 return corrected;
525}
526
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700527// Converts a string value representing the reason the system booted to a
528// string complying with Android system standard reason.
529void transformReason(std::string& reason) {
530 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
531 std::transform(reason.begin(), reason.end(), reason.begin(),
532 [](char c) { return ::isblank(c) ? '_' : c; });
533 std::transform(reason.begin(), reason.end(), reason.begin(),
534 [](char c) { return ::isprint(c) ? c : '?'; });
535}
536
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700537// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
538// kernel_panic,<subreason>.
539//
540// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
541// or unprintable character terminated subreason, pos is supplied just beyond
542// first quote. if quoted false, pull out and correct newline (\n) or
543// unprintable character terminated subreason.
544//
545// Heuristics to find termination is painted into a corner:
546
547// single bit error for quote ' that we can block. It is acceptable for
548// the others 7, g in reason. 2/9 chance will miss the terminating quote,
549// but there is always the terminating newline that usually immediately
550// follows to fortify our chances.
551bool likely_single_quote(char c) {
552 switch (static_cast<uint8_t>(c)) {
553 case '\'': // '\''
554 case '\'' ^ 0x01: // '&'
555 case '\'' ^ 0x02: // '%'
556 case '\'' ^ 0x04: // '#'
557 case '\'' ^ 0x08: // '/'
558 return true;
559 case '\'' ^ 0x10: // '7'
560 break;
561 case '\'' ^ 0x20: // '\a' (unprintable)
562 return true;
563 case '\'' ^ 0x40: // 'g'
564 break;
565 case '\'' ^ 0x80: // 0xA7 (unprintable)
566 return true;
567 }
568 return false;
569}
570
571// ::isprint(c) and likely_space() will prevent us from being called for
572// fundamentally printable entries, except for '\r' and '\b'.
573//
574// Except for * and J, single bit errors for \n, all others are non-
575// printable so easy catch. It is _acceptable_ for *, J or j to exist in
576// the reason string, so 2/9 chance we will miss the terminating newline.
577//
578// NB: J might not be acceptable, except if at the beginning or preceded
579// with a space, '(' or any of the quotes and their BER aliases.
580// NB: * might not be acceptable, except if at the beginning or preceded
581// with a space, another *, or any of the quotes or their BER aliases.
582//
583// To reduce the chances to closer to 1/9 is too complicated for the gain.
584bool likely_newline(char c) {
585 switch (static_cast<uint8_t>(c)) {
586 case '\n': // '\n' (unprintable)
587 case '\n' ^ 0x01: // '\r' (unprintable)
588 case '\n' ^ 0x02: // '\b' (unprintable)
589 case '\n' ^ 0x04: // 0x0E (unprintable)
590 case '\n' ^ 0x08: // 0x02 (unprintable)
591 case '\n' ^ 0x10: // 0x1A (unprintable)
592 return true;
593 case '\n' ^ 0x20: // '*'
594 case '\n' ^ 0x40: // 'J'
595 break;
596 case '\n' ^ 0x80: // 0x8A (unprintable)
597 return true;
598 }
599 return false;
600}
601
602// ::isprint(c) will prevent us from being called for all the printable
603// matches below. If we let unprintables through because of this, they
604// get converted to underscore (_) by the validation phase.
605bool likely_space(char c) {
606 switch (static_cast<uint8_t>(c)) {
607 case ' ': // ' '
608 case ' ' ^ 0x01: // '!'
609 case ' ' ^ 0x02: // '"'
610 case ' ' ^ 0x04: // '$'
611 case ' ' ^ 0x08: // '('
612 case ' ' ^ 0x10: // '0'
613 case ' ' ^ 0x20: // '\0' (unprintable)
614 case ' ' ^ 0x40: // 'P'
615 case ' ' ^ 0x80: // 0xA0 (unprintable)
616 case '\t': // '\t'
617 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
618 case '\t' ^ 0x02: // '\v' (unprintable)
619 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
620 case '\t' ^ 0x08: // 0x01 (unprintable)
621 case '\t' ^ 0x10: // 0x19 (unprintable)
622 case '\t' ^ 0x20: // ')'
623 case '\t' ^ 0x40: // '1'
624 case '\t' ^ 0x80: // 0x89 (unprintable)
625 return true;
626 }
627 return false;
628}
629
630std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700631 static constexpr size_t max_reason_length = 256;
632
633 std::string subReason(content.substr(pos, max_reason_length));
634 // Correct against any known strings that Bit Error Match
635 for (const auto& s : knownReasons) {
636 correctForBitErrorOrUnderline(subReason, s);
637 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700638 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700639 for (const auto& m : kBootReasonMap) {
640 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700641 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700642 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
643 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700644 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700645 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700646 correctForBitErrorOrUnderline(subReason,
647 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
648 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
649 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700650 }
651 }
652 for (pos = 0; pos < subReason.length(); ++pos) {
653 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700654 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
655 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700656 subReason.erase(pos);
657 break;
658 }
659 }
660 transformReason(subReason);
661 return subReason;
662}
663
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700664bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700665 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700666 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
667 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700668 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700669 // Invented for Android to allow daemons that specifically trigger sysrq
670 // to communicate more accurate boot subreasons via last console messages.
671 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
672 auto pos = console.rfind(sysrqSubreason);
673 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700674 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700675 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700676 return true;
677 }
678 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
679 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700680 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700681 return true;
682 }
683 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700684 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700685 return true;
686 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700687
688 std::string panic("Kernel panic - not syncing: ");
689 auto pos = console.rfind(panic);
690 if (pos != std::string::npos) {
691 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
692 {"Out of memory", "oom"},
693 {"out of memory", "oom"},
694 {"Oh boy, that early out of memory", "oom"}, // omg
695 {"BUG!", "bug"},
696 {"hung_task: blocked tasks", "hung"},
697 {"audit: ", "audit"},
698 {"scheduling while atomic", "atomic"},
699 {"Attempted to kill init!", "init"},
700 {"Requested init", "init"},
701 {"No working init", "init"},
702 {"Could not decompress init", "init"},
703 {"RCU Stall", "hung,rcu"},
704 {"stack-protector", "stack"},
705 {"kernel stack overflow", "stack"},
706 {"Corrupt kernel stack", "stack"},
707 {"low stack detected", "stack"},
708 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700709 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
710 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
711 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
712 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700713 };
714
715 ret = "kernel_panic";
716 for (auto& s : panicReasons) {
717 if (console.find(panic + s.first, pos) != std::string::npos) {
718 ret += "," + s.second;
719 return true;
720 }
721 }
722 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
723 if (reason.length() > 3) {
724 ret += "," + reason;
725 }
726 return true;
727 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700728 return false;
729}
730
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700731bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
732 return addKernelPanicSubReason(pstoreConsole(content), ret);
733}
734
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700735const char system_reboot_reason_property[] = "sys.boot.reason";
736const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
737const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
738
739// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
740std::string BootReasonStrToReason(const std::string& boot_reason) {
741 std::string ret(GetProperty(system_reboot_reason_property));
742 std::string reason(boot_reason);
743 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
744 if (reason == ret) ret = "";
745
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700746 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700747
748 // Is the current system boot reason sys.boot.reason valid?
749 if (!isKnownRebootReason(ret)) ret = "";
750
751 if (ret == "") {
752 // Is the bootloader boot reason ro.boot.bootreason known?
753 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700754 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700755 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700756 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700757 if (r == s) {
758 if (isBluntRebootReason(s)) {
759 blunt = s;
760 } else {
761 ret = s;
762 break;
763 }
764 }
765 }
766 if (ret == "") ret = blunt;
767 if (ret != "") break;
768 }
769 }
770
771 if (ret == "") {
772 // A series of checks to take some officially unsupported reasons
773 // reported by the bootloader and find some logical and canonical
774 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700775 // to behave and follow our CTS standards.
776 //
777 // first member is the output
778 // second member is an unanchored regex for an alias
779 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700780 // If output has a prefix of <bang> '!', we do not use it as a
781 // match needle (and drop the <bang> prefix when landing in output),
782 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700783 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700784 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700785 {"watchdog", "wdog"},
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700786 {"cold,powerkey", "powerkey|power_key|PowerKey"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700787 {"kernel_panic", "panic"},
788 {"shutdown,thermal", "thermal"},
789 {"warm,s3_wakeup", "s3_wakeup"},
790 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700791 {"cold,charger", "usb"},
792 {"cold,rtc", "rtc"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700793 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700794 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700795 };
796
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700797 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700798 size_t firstHasNot = s.first[0] == '!';
799 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700800 ret = s.first;
801 break;
802 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700803 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700804 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700805 break;
806 }
807 }
808 }
809
810 // If watchdog is the reason, see if there is a security angle?
811 if (ret == "watchdog") {
812 if (reason.find("sec") != std::string::npos) {
813 ret += ",security";
814 }
815 }
816
Mark Salyzyn64610892017-09-18 10:41:14 -0700817 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700818 // Check to see if last klog has some refinement hints.
819 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700820 if (readPstoreConsole(content)) {
821 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700822 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700823 } else if (isBluntRebootReason(ret)) {
824 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700825
Mark Salyzyn64610892017-09-18 10:41:14 -0700826 // Check to see if last klog has some refinement hints.
827 std::string content;
828 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700829 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700830 // The toybox reboot command used directly (unlikely)? But also
831 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700832 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700833 ret = "shutdown"; // Still too blunt, but more accurate.
834 // ToDo: init should record the shutdown reason to kernel messages ala:
835 // init: shutdown system with command 'last_reboot_reason'
836 // so that if pstore has persistence we can get some details
837 // that could be missing in last_reboot_reason_property.
838 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700839
Mark Salyzyn64610892017-09-18 10:41:14 -0700840 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700841 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700842 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700843 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700844 if (subReason != "") { // Will not land "reboot" as that is too blunt.
845 if (isKernelRebootReason(subReason)) {
846 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700847 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700848 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700849 } else {
850 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700851 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700852 }
Mark Salyzyn15199252018-03-16 09:26:05 -0700853 // Some bootloaders shutdown results record in last kernel message.
854 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
855 ret = "shutdown";
856 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700857 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700858
Mark Salyzyn64610892017-09-18 10:41:14 -0700859 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700860 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700861 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700862 ((console.rfind("Power held for ") != std::string::npos) ||
863 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700864 ret = "cold";
865 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700866 }
867
868 // The following battery test should migrate to a default system health HAL
869
870 // Let us not worry if the reboot command was issued, for the cases of
871 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
872 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
873 // battery could conceivably lead to these, so worthy of override.
874 if (isBluntRebootReason(ret)) {
875 // Heuristic to determine if shutdown possibly because of a dead battery?
876 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700877 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700878 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700879 const pstoreConsole console(content);
880 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700881 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700882 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700883 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700884 // correct common errors
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700885 correctForBitError(digits, "100 ");
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700886 if (digits[0] == '!') digits[0] = '1';
887 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700888 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700889 const char* endptr = digits.c_str();
890 unsigned level = 0;
891 while (::isdigit(*endptr)) {
892 level *= 10;
893 level += *endptr++ - '0';
894 // make sure no leading zeros, except zero itself, and range check.
895 if ((level == 0) || (level > 100)) break;
896 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700897 // example bit error rate issues for 10%
898 // 'l=10 ' no bits in error
899 // 'l=00 ' single bit error (fails above)
900 // 'l=1 ' single bit error
901 // 'l=0 ' double bit error
902 // There are others, not typically critical because of 2%
903 // battery_dead_threshold. KISS check, make sure second
904 // character after digit sequence is not a space.
905 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700906 LOG(INFO) << "Battery level at shutdown " << level << "%";
907 if (level <= battery_dead_threshold) {
908 ret = "shutdown,battery";
909 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700910 } else { // Most likely
911 digits = ""; // reset digits
912
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700913 // Content buffer no longer will have console data. Beware if more
914 // checks added below, that depend on parsing console content.
915 content = "";
916
917 LOG(DEBUG) << "Can not find last low battery in last console messages";
918 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700919 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700920 if (fp != nullptr) {
921 android::base::ReadFdToString(fileno(fp), &content);
922 }
923 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700924 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
925 const char* match = logcat_battery;
926
927 if (content == "") {
928 // Service logd.klog not running, go to smaller buffer in the kernel.
929 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
930 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700931 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700932 std::unique_ptr<char[]> buf(new char[len]);
933 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
934 if (rc < len) {
935 len = rc + 1;
936 }
937 buf[--len] = '\0';
938 content = buf.get();
939 }
940 match = battery;
941 }
942
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700943 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700944 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700945 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700946 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700947 endptr = digits.c_str();
948 level = 0;
949 while (::isdigit(*endptr)) {
950 level *= 10;
951 level += *endptr++ - '0';
952 // make sure no leading zeros, except zero itself, and range check.
953 if ((level == 0) || (level > 100)) break;
954 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700955 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700956 LOG(INFO) << "Battery level at startup " << level << "%";
957 if (level <= battery_dead_threshold) {
958 ret = "shutdown,battery";
959 }
960 } else {
961 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
962 }
963 }
964 }
965
966 // Is there a controlled shutdown hint in last_reboot_reason_property?
967 if (isBluntRebootReason(ret)) {
968 // Content buffer no longer will have console data. Beware if more
969 // checks added below, that depend on parsing console content.
970 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700971 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700972
Mark Salyzyn62909822017-10-09 09:27:16 -0700973 // Anything in last is better than 'super-blunt' reboot or shutdown.
974 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
975 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700976 }
977 }
978
979 // Other System Health HAL reasons?
980
981 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
982 // possibly offer hardware-specific clues from the PMIC.
983 }
984
985 // If unknown left over from above, make it "reboot,<boot_reason>"
986 if (ret == "") {
987 ret = "reboot";
988 if (android::base::StartsWith(reason, "reboot")) {
989 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700990 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700991 reason = reason.substr(1);
992 }
993 }
994 if (reason != "") {
995 ret += ",";
996 ret += reason;
997 }
998 }
999
1000 LOG(INFO) << "Canonical boot reason: " << ret;
1001 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
1002 // Rewrite as it must be old news, kernel reasons trump user space.
1003 SetProperty(last_reboot_reason_property, ret);
1004 }
1005 return ret;
1006}
1007
James Hawkinsb9cf7712016-04-08 15:32:19 -07001008// Returns the appropriate metric key prefix for the boot_complete metric such
1009// that boot metrics after a system update are labeled as ota_boot_complete;
1010// otherwise, they are labeled as boot_complete. This method encapsulates the
1011// bookkeeping required to track when a system update has occurred by storing
1012// the UTC timestamp of the system build date and comparing against the current
1013// system build date.
1014std::string CalculateBootCompletePrefix() {
1015 static const std::string kBuildDateKey = "build_date";
1016 std::string boot_complete_prefix = "boot_complete";
1017
1018 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -07001019 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -07001020 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -07001021 return std::string();
1022 }
James Hawkinsb9cf7712016-04-08 15:32:19 -07001023
1024 BootEventRecordStore boot_event_store;
1025 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -07001026 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1027 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1028 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001029 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001030 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001031 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001032 boot_complete_prefix = "ota_" + boot_complete_prefix;
1033 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001034 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001035 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001036 }
1037
1038 return boot_complete_prefix;
1039}
1040
James Hawkinsef0a0902017-01-06 14:38:23 -08001041// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001042void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001043 std::string value = GetProperty(property);
1044
James Hawkins27c05222017-01-26 11:55:44 -08001045 int32_t time_in_ms;
1046 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001047 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1048 }
1049}
1050
James Hawkins1bfcaec2017-05-19 14:27:27 -07001051// A map from bootloader timing stage to the time that stage took during boot.
1052typedef std::map<std::string, int32_t> BootloaderTimingMap;
1053
1054// Returns a mapping from bootloader stage names to the time those stages
1055// took to boot.
1056const BootloaderTimingMap GetBootLoaderTimings() {
1057 BootloaderTimingMap timings;
1058
1059 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1060 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -08001061 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001062 if (value.empty()) {
1063 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001064 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001065 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001066
1067 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001068 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001069 // |stageTiming| is of the form 'stage:time'.
1070 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001071 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001072
1073 std::string stageName = stageTimingValues[0];
1074 int32_t time_ms;
1075 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001076 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001077 }
1078 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001079
James Hawkins1bfcaec2017-05-19 14:27:27 -07001080 return timings;
1081}
1082
1083// Parses and records the set of bootloader stages and associated boot times
1084// from the ro.boot.boottime system property.
1085void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1086 const BootloaderTimingMap& bootloader_timings) {
1087 int32_t total_time = 0;
1088 for (const auto& timing : bootloader_timings) {
1089 total_time += timing.second;
1090 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1091 }
1092
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001093 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001094}
1095
James Hawkins1bfcaec2017-05-19 14:27:27 -07001096// Records the closest estimation to the absolute device boot time, i.e.,
1097// from power on to boot_complete, including bootloader times.
1098void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1099 const BootloaderTimingMap& bootloader_timings,
1100 std::chrono::milliseconds uptime) {
1101 int32_t bootloader_time_ms = 0;
1102
1103 for (const auto& timing : bootloader_timings) {
1104 if (timing.first.compare("SW") != 0) {
1105 bootloader_time_ms += timing.second;
1106 }
1107 }
1108
1109 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
1110 auto absolute_total =
1111 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
1112 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
1113}
1114
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001115// Gets the boot time offset. This is useful when Android is running in a
1116// container, because the boot_clock is not reset when Android reboots.
1117std::chrono::nanoseconds GetBootTimeOffset() {
1118 static const int64_t boottime_offset =
1119 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1120 return std::chrono::nanoseconds(boottime_offset);
1121}
1122
1123// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1124// clock.
1125android::base::boot_clock::duration GetUptime() {
1126 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1127}
1128
James Hawkinsc08e9962016-03-11 14:59:50 -08001129// Records several metrics related to the time it takes to boot the device,
1130// including disambiguating boot time on encrypted or non-encrypted devices.
1131void RecordBootComplete() {
1132 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001133 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001134
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001135 auto uptime_ns = GetUptime();
1136 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001137 time_t current_time_utc = time(nullptr);
1138
1139 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1140 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001141 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
1142 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001143 }
1144
1145 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001146
James Hawkinsb9cf7712016-04-08 15:32:19 -07001147 // The boot_complete metric has two variants: boot_complete and
1148 // ota_boot_complete. The latter signifies that the device is booting after
1149 // a system update.
1150 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001151 if (boot_complete_prefix.empty()) {
1152 // The system is hosed because the build date property could not be read.
1153 return;
1154 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001155
1156 // post_decrypt_time_elapsed is only logged on encrypted devices.
1157 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1158 // Log the amount of time elapsed until the device is decrypted, which
1159 // includes the variable amount of time the user takes to enter the
1160 // decryption password.
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001161 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001162
1163 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001164 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001165 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001166 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001167 } else {
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001168 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1169 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001170 }
1171
1172 // Record the total time from device startup to boot complete, regardless of
1173 // encryption state.
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001174 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001175
1176 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1177 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1178 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001179
James Hawkins1bfcaec2017-05-19 14:27:27 -07001180 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
1181 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1182
Luis Hector Chavez03aae152018-04-12 15:25:15 -07001183 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001184 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -08001185}
1186
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001187// Records the boot_reason metric by querying the ro.boot.bootreason system
1188// property.
1189void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001190 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -07001191
1192 if (reason.empty()) {
1193 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1194 // (and not corruption anywhere else in the reporting pipeline).
1195 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1196 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1197 } else {
1198 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1199 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1200 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001201
1202 // Log the raw bootloader_boot_reason property value.
1203 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001204 BootEventRecordStore boot_event_store;
1205 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001206
1207 // Log the scrubbed system_boot_reason.
1208 const std::string system_reason(BootReasonStrToReason(reason));
1209 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1210 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1211
1212 // Record the scrubbed system_boot_reason to the property
1213 SetProperty(system_reboot_reason_property, system_reason);
1214 if (reason == "") {
1215 SetProperty(bootloader_reboot_reason_property, system_reason);
1216 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001217}
1218
James Hawkins500d7152016-02-16 15:05:54 -08001219// Records two metrics related to the user resetting a device: the time at
1220// which the device is reset, and the time since the user last reset the
1221// device. The former is only set once per-factory reset.
1222void RecordFactoryReset() {
1223 BootEventRecordStore boot_event_store;
1224 BootEventRecordStore::BootEventRecord record;
1225
1226 time_t current_time_utc = time(nullptr);
1227
James Hawkins0660b302016-03-08 16:18:15 -08001228 if (current_time_utc < 0) {
1229 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001230 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1231 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001232
James Hawkins9aec9262017-01-31 11:42:24 -08001233 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001234 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001235 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1236 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001237 return;
1238 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001239 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001240
James Hawkins9aec9262017-01-31 11:42:24 -08001241 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001242 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001243 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001244 }
1245
James Hawkins500d7152016-02-16 15:05:54 -08001246 // The factory_reset boot event does not exist after the device is reset, so
1247 // use this signal to mark the time of the factory reset.
1248 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1249 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001250
1251 // Don't log the time_since_factory_reset until some time has elapsed.
1252 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001253 return;
1254 }
1255
1256 // Calculate and record the difference in time between now and the
1257 // factory_reset time.
1258 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001259 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001260
James Hawkins9aec9262017-01-31 11:42:24 -08001261 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001262 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001263 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001264
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001265 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1266 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001267}
1268
James Hawkinsabd73e62016-01-19 15:10:38 -08001269} // namespace
1270
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001271int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001272 android::base::InitLogging(argv);
1273
1274 const std::string cmd_line = GetCommandLine(argc, argv);
1275 LOG(INFO) << "Service started: " << cmd_line;
1276
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001277 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001278 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -08001279 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001280 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001281 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001282 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001283 // clang-format off
1284 { "help", no_argument, NULL, 'h' },
1285 { "log", no_argument, NULL, 'l' },
1286 { "print", no_argument, NULL, 'p' },
1287 { "record", required_argument, NULL, 'r' },
1288 { value_str, required_argument, NULL, 0 },
1289 { boot_complete_str, no_argument, NULL, 0 },
1290 { boot_reason_str, no_argument, NULL, 0 },
1291 { factory_reset_str, no_argument, NULL, 0 },
1292 { NULL, 0, NULL, 0 }
1293 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001294 };
1295
James Hawkinsc6275582016-03-22 10:47:44 -07001296 std::string boot_event;
1297 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001298 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001299 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001300 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001301 // This case handles long options which have no single-character mapping.
1302 case 0: {
1303 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001304 if (option_name == value_str) {
1305 // |optarg| is an external variable set by getopt representing
1306 // the option argument.
1307 value = optarg;
1308 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001309 RecordBootComplete();
1310 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001311 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001312 } else if (option_name == factory_reset_str) {
1313 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001314 } else {
1315 LOG(ERROR) << "Invalid option: " << option_name;
1316 }
1317 break;
1318 }
1319
James Hawkinsabd73e62016-01-19 15:10:38 -08001320 case 'h': {
1321 ShowHelp(argv[0]);
1322 break;
1323 }
1324
1325 case 'l': {
1326 LogBootEvents();
1327 break;
1328 }
1329
1330 case 'p': {
1331 PrintBootEvents();
1332 break;
1333 }
1334
1335 case 'r': {
1336 // |optarg| is an external variable set by getopt representing
1337 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001338 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001339 break;
1340 }
1341
1342 default: {
1343 DCHECK_EQ(opt, '?');
1344
1345 // |optopt| is an external variable set by getopt representing
1346 // the value of the invalid option.
1347 LOG(ERROR) << "Invalid option: " << optopt;
1348 ShowHelp(argv[0]);
1349 return EXIT_FAILURE;
1350 }
1351 }
1352 }
1353
James Hawkinsc6275582016-03-22 10:47:44 -07001354 if (!boot_event.empty()) {
1355 RecordBootEventFromCommandLine(boot_event, value);
1356 }
1357
James Hawkinsabd73e62016-01-19 15:10:38 -08001358 return 0;
1359}