blob: 4be102c717811683aefdea9a2623881a2931ac02 [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 Chavez583d34c2018-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>
Tej Singh4eacd382018-01-25 17:59:57 -080048#include <statslog.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070049
James Hawkinsabd73e62016-01-19 15:10:38 -080050#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080051
52namespace {
53
James Hawkinsabd73e62016-01-19 15:10:38 -080054// Scans the boot event record store for record files and logs each boot event
55// via EventLog.
56void LogBootEvents() {
57 BootEventRecordStore boot_event_store;
58
59 auto events = boot_event_store.GetAllBootEvents();
60 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080061 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080062 }
63}
64
James Hawkinsc6275582016-03-22 10:47:44 -070065// Records the named boot |event| to the record store. If |value| is non-empty
66// and is a proper string representation of an integer value, the converted
67// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070068void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070069 BootEventRecordStore boot_event_store;
70 if (!value_str.empty()) {
71 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070072 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070073 boot_event_store.AddBootEventWithValue(event, value);
74 }
James Hawkinsc6275582016-03-22 10:47:44 -070075 } else {
76 boot_event_store.AddBootEvent(event);
77 }
78}
79
James Hawkinsabd73e62016-01-19 15:10:38 -080080void PrintBootEvents() {
81 printf("Boot events:\n");
82 printf("------------\n");
83
84 BootEventRecordStore boot_event_store;
85 auto events = boot_event_store.GetAllBootEvents();
86 for (auto i = events.cbegin(); i != events.cend(); ++i) {
87 printf("%s\t%d\n", i->first.c_str(), i->second);
88 }
89}
90
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070091void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080092 fprintf(stderr, "Usage: %s [options]\n", cmd);
93 fprintf(stderr,
94 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080095 " -h, --help Show this help\n"
96 " -l, --log Log all metrics to logstorage\n"
97 " -p, --print Dump the boot event records to the console\n"
98 " -r, --record Record the timestamp of a named boot event\n"
99 " --value Optional value to associate with the boot event\n"
100 " --record_boot_complete Record metrics related to the time for the device boot\n"
101 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -0800102 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800103}
104
105// Constructs a readable, printable string from the givencommand line
106// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700107std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800108 std::string cmd;
109 for (int i = 0; i < argc; ++i) {
110 cmd += argv[i];
111 cmd += " ";
112 }
113
114 return cmd;
115}
116
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800117// Convenience wrapper over the property API that returns an
118// std::string.
119std::string GetProperty(const char* key) {
120 std::vector<char> temp(PROPERTY_VALUE_MAX);
121 const int len = property_get(key, &temp[0], nullptr);
122 if (len < 0) {
123 return "";
124 }
125 return std::string(&temp[0], len);
126}
127
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700128void SetProperty(const char* key, const std::string& val) {
129 property_set(key, val.c_str());
130}
131
132void SetProperty(const char* key, const char* val) {
133 property_set(key, val);
134}
135
James Hawkins25f71222017-10-10 16:37:05 -0700136constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800137constexpr int32_t kUnknownBootReason = 1;
138
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800139// A mapping from boot reason string, as read from the ro.boot.bootreason
140// system property, to a unique integer ID. Viewers of log data dashboards for
141// the boot_reason metric may refer to this mapping to discern the histogram
142// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800143const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700144 {"empty", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700145 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700146 {"normal", 2},
147 {"recovery", 3},
148 {"reboot", 4},
149 {"PowerKey", 5},
150 {"hard_reset", 6},
151 {"kernel_panic", 7},
152 {"rpm_err", 8},
153 {"hw_reset", 9},
154 {"tz_err", 10},
155 {"adsp_err", 11},
156 {"modem_err", 12},
157 {"mba_err", 13},
158 {"Watchdog", 14},
159 {"Panic", 15},
160 {"power_key", 16},
161 {"power_on", 17},
162 {"Reboot", 18},
163 {"rtc", 19},
164 {"edl", 20},
165 {"oem_pon1", 21},
166 {"oem_powerkey", 22},
167 {"oem_unknown_reset", 23},
168 {"srto: HWWDT reset SC", 24},
169 {"srto: HWWDT reset platform", 25},
170 {"srto: bootloader", 26},
171 {"srto: kernel panic", 27},
172 {"srto: kernel watchdog reset", 28},
173 {"srto: normal", 29},
174 {"srto: reboot", 30},
175 {"srto: reboot-bootloader", 31},
176 {"srto: security watchdog reset", 32},
177 {"srto: wakesrc", 33},
178 {"srto: watchdog", 34},
179 {"srto:1-1", 35},
180 {"srto:omap_hsmm", 36},
181 {"srto:phy0", 37},
182 {"srto:rtc0", 38},
183 {"srto:touchpad", 39},
184 {"watchdog", 40},
185 {"watchdogr", 41},
186 {"wdog_bark", 42},
187 {"wdog_bite", 43},
188 {"wdog_reset", 44},
189 {"shutdown,", 45}, // Trailing comma is intentional.
190 {"shutdown,userrequested", 46},
191 {"reboot,bootloader", 47},
192 {"reboot,cold", 48},
193 {"reboot,recovery", 49},
194 {"thermal_shutdown", 50},
195 {"s3_wakeup", 51},
196 {"kernel_panic,sysrq", 52},
197 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700198 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700199 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700200 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700201 {"bootloader", 55},
202 {"cold", 56},
203 {"hard", 57},
204 {"warm", 58},
Mark Salyzyn15199252018-03-16 09:26:05 -0700205 {"reboot,kernel_power_off_charging__reboot_system", 59}, // Can not happen
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700206 {"thermal-shutdown", 60},
207 {"shutdown,thermal", 61},
208 {"shutdown,battery", 62},
209 {"reboot,ota", 63},
210 {"reboot,factory_reset", 64},
211 {"reboot,", 65},
212 {"reboot,shell", 66},
213 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700214 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700215 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700216 {"cold,powerkey", 70},
217 {"warm,s3_wakeup", 71},
218 {"hard,hw_reset", 72},
219 {"shutdown,suspend", 73}, // Suspend to RAM
220 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700221 {"power_on_key", 75},
222 {"reboot_by_key", 76},
223 {"wdt_by_pass_pwk", 77},
224 {"reboot_longkey", 78},
225 {"powerkey", 79},
226 {"usb", 80},
227 {"wdt", 81},
228 {"tool_by_pass_pwk", 82},
229 {"2sec_reboot", 83},
230 {"reboot,by_key", 84},
231 {"reboot,longkey", 85},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700232 {"reboot,2sec", 86}, // Deprecate in two years, replaced with cold,rtc,2sec
Mark Salyzync89f9da2017-10-24 15:35:34 -0700233 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700234 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
235 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn75046892018-05-03 13:11:15 -0700236 {"reboot,rescueparty", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800237 {"charge", 91},
238 {"oem_tz_crash", 92},
239 {"uvlo", 93},
240 {"oem_ps_hold", 94},
241 {"abnormal_reset", 95},
242 {"oemerr_unknown", 96},
243 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800244 {"watchdog_apps_bite", 98},
245 {"xpu_err", 99},
246 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800247 {"watchdog_rpm", 101},
248 {"watchdog_nonsec", 102},
249 {"watchdog_apps_bark", 103},
250 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800251 {"reboot_smpl", 105},
252 {"watchdog_sdi_apps_reset", 106},
253 {"smpl", 107},
254 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800255 {"reboot_normal", 109},
256 {"oem_lpass_cfg", 110},
257 {"oem_xpu_ns_error", 111},
258 {"power_key_press", 112},
259 {"hardware_reset", 113},
260 {"reboot_by_powerkey", 114},
261 {"reboot_verity", 115},
262 {"oem_rpm_undef_error", 116},
263 {"oem_crash_on_the_lk", 117},
264 {"oem_rpm_reset", 118},
265 {"oem_lpass_cfg", 119},
266 {"oem_xpu_ns_error", 120},
267 {"factory_cable", 121},
268 {"oem_ar6320_failed_to_powerup", 122},
269 {"watchdog_rpm_bite", 123},
270 {"power_on_cable", 124},
271 {"reboot_unknown", 125},
272 {"wireless_charger", 126},
273 {"0x776655ff", 127},
274 {"oem_thermal_bite_reset", 128},
275 {"charger", 129},
276 {"pon1", 130},
277 {"unknown", 131},
278 {"reboot_rtc", 132},
279 {"cold_boot", 133},
280 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800281 {"power-on", 135},
282 {"oem_adsp_resetting_the_soc", 136},
283 {"kpdpwr", 137},
284 {"oem_modem_timeout_waiting", 138},
285 {"usb_chg", 139},
286 {"warm_reset_0x02", 140},
287 {"warm_reset_0x80", 141},
288 {"pon_reason_0xb0", 142},
289 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800290 {"reboot_recovery_mode", 144},
291 {"oem_sdi_err_fatal", 145},
292 {"pmic_watchdog", 146},
293 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700294 {"cold,charger", 148},
295 {"cold,rtc", 149},
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700296 {"cold,rtc,2sec", 150},
297 {"reboot,tool", 151},
298 {"reboot,wdt", 152},
299 {"reboot,unknown", 153},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700300 {"kernel_panic,audit", 154},
301 {"kernel_panic,atomic", 155},
302 {"kernel_panic,hung", 156},
303 {"kernel_panic,hung,rcu", 157},
304 {"kernel_panic,init", 158},
305 {"kernel_panic,oom", 159},
306 {"kernel_panic,stack", 160},
Mark Salyzynafd66f22018-03-19 15:16:29 -0700307 {"kernel_panic,sysrq,livelock,alarm", 161}, // llkd
308 {"kernel_panic,sysrq,livelock,driver", 162}, // llkd
309 {"kernel_panic,sysrq,livelock,zombie", 163}, // llkd
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700310 {"kernel_panic,modem", 164},
311 {"kernel_panic,adsp", 165},
312 {"kernel_panic,dsps", 166},
313 {"kernel_panic,wcnss", 167},
Mark Salyzyn78e54fd2018-06-08 10:19:16 -0700314 {"kernel_panic,_sde_encoder_phys_cmd_handle_ppdone_timeout", 168},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800315};
316
317// Converts a string value representing the reason the system booted to an
318// integer representation. This is necessary for logging the boot_reason metric
319// via Tron, which does not accept non-integer buckets in histograms.
320int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800321 auto mapping = kBootReasonMap.find(boot_reason);
322 if (mapping != kBootReasonMap.end()) {
323 return mapping->second;
324 }
325
James Hawkins25f71222017-10-10 16:37:05 -0700326 if (boot_reason.empty()) {
327 return kEmptyBootReason;
328 }
329
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800330 LOG(INFO) << "Unknown boot reason: " << boot_reason;
331 return kUnknownBootReason;
332}
333
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700334// Canonical list of supported primary reboot reasons.
335const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700336 // clang-format off
337 // kernel
338 "watchdog",
339 "kernel_panic",
340 // strong
341 "recovery", // Should not happen from ro.boot.bootreason
342 "bootloader", // Should not happen from ro.boot.bootreason
343 // blunt
344 "cold",
345 "hard",
346 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700347 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700348 "shutdown", // Can not happen from ro.boot.bootreason
349 "reboot", // Default catch-all for anything unknown
350 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700351};
352
353// Returns true if the supplied reason prefix is considered detailed enough.
354bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700355 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700356 if (s == "cold") break;
357 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800358 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700359 return true;
360 }
361 }
362 return false;
363}
364
365// Returns true if the supplied reason prefix is associated with the kernel.
366bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700367 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700368 if (s == "recovery") break;
369 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800370 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700371 return true;
372 }
373 }
374 return false;
375}
376
377// Returns true if the supplied reason prefix is considered known.
378bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700379 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700380 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800381 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700382 return true;
383 }
384 }
385 return false;
386}
387
388// If the reboot reason should be improved, report true if is too blunt.
389bool isBluntRebootReason(const std::string& r) {
390 if (isStrongRebootReason(r)) return false;
391
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700392 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700393
394 size_t pos = 0;
395 while ((pos = r.find(',', pos)) != std::string::npos) {
396 ++pos;
397 std::string next(r.substr(pos));
398 if (next.length() == 0) break;
399 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700400 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
401 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700402 }
403 return true;
404}
405
Mark Salyzyn64610892017-09-18 10:41:14 -0700406bool readPstoreConsole(std::string& console) {
407 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
408 return true;
409 }
410 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
411}
412
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700413// Implement a variant of std::string::rfind that is resilient to errors in
414// the data stream being inspected.
415class pstoreConsole {
416 private:
417 const size_t kBitErrorRate = 8; // number of bits per error
418 const std::string& console;
419
420 // Number of bits that differ between the two arguments l and r.
421 // Returns zero if the values for l and r are identical.
422 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
423
424 // A string comparison function, reports the number of errors discovered
425 // in the match to a maximum of the bitLength / kBitErrorRate, at that
426 // point returning npos to indicate match is too poor.
427 //
428 // Since called in rfind which works backwards, expect cache locality will
429 // help if we check in reverse here as well for performance.
430 //
431 // Assumption: l (from console.c_str() + pos) is long enough to house
432 // _r.length(), checked in rfind caller below.
433 //
434 size_t numError(size_t pos, const std::string& _r) const {
435 const char* l = console.c_str() + pos;
436 const char* r = _r.c_str();
437 size_t n = _r.length();
438 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
439 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
440 size_t count = 0;
441 n = 0;
442 do {
443 // individual character bit error rate > threshold + slop
444 size_t num = numError(*--le, *--re);
445 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
446 // total bit error rate > threshold + slop
447 count += num;
448 ++n;
449 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
450 return std::string::npos;
451 }
452 } while (le != reinterpret_cast<const uint8_t*>(l));
453 return count;
454 }
455
456 public:
457 explicit pstoreConsole(const std::string& console) : console(console) {}
458 // scope of argument must be equal to or greater than scope of pstoreConsole
459 explicit pstoreConsole(const std::string&& console) = delete;
460 explicit pstoreConsole(std::string&& console) = delete;
461
462 // Our implementation of rfind, use exact match first, then resort to fuzzy.
463 size_t rfind(const std::string& needle) const {
464 size_t pos = console.rfind(needle); // exact match?
465 if (pos != std::string::npos) return pos;
466
467 // Check to make sure needle fits in console string.
468 pos = console.length();
469 if (needle.length() > pos) return std::string::npos;
470 pos -= needle.length();
471 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800472 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700473 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800474 if (pos == 0) break;
475 --pos;
476 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700477 return std::string::npos;
478 }
479
480 // Our implementation of find, use only fuzzy match.
481 size_t find(const std::string& needle, size_t start = 0) const {
482 // Check to make sure needle fits in console string.
483 if (needle.length() > console.length()) return std::string::npos;
484 const size_t last_pos = console.length() - needle.length();
485 // fuzzy match to maximum kBitErrorRate
486 for (size_t pos = start; pos <= last_pos; ++pos) {
487 if (numError(pos, needle) != std::string::npos) return pos;
488 }
489 return std::string::npos;
490 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700491
492 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700493};
494
495// If bit error match to needle, correct it.
496// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700497bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700498 bool corrected = false;
499 if (reason.length() < needle.length()) return corrected;
500 const pstoreConsole console(reason);
501 const size_t last_pos = reason.length() - needle.length();
502 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
503 pos = console.find(needle, pos);
504 if (pos == std::string::npos) break;
505
506 // exact match has no malice
507 if (needle == reason.substr(pos, needle.length())) continue;
508
509 corrected = true;
510 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
511 }
512 return corrected;
513}
514
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700515// If bit error match to needle, correct it.
516// Return true if any corrections were discovered and applied.
517// Try again if we can replace underline with spaces.
518bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
519 bool corrected = correctForBitError(reason, needle);
520 std::string _needle(needle);
521 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
522 [](char c) { return (c == '_') ? ' ' : c; });
523 if (needle != _needle) {
524 corrected |= correctForBitError(reason, _needle);
525 }
526 return corrected;
527}
528
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700529// Converts a string value representing the reason the system booted to a
530// string complying with Android system standard reason.
531void transformReason(std::string& reason) {
532 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
533 std::transform(reason.begin(), reason.end(), reason.begin(),
534 [](char c) { return ::isblank(c) ? '_' : c; });
535 std::transform(reason.begin(), reason.end(), reason.begin(),
536 [](char c) { return ::isprint(c) ? c : '?'; });
537}
538
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700539// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
540// kernel_panic,<subreason>.
541//
542// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
543// or unprintable character terminated subreason, pos is supplied just beyond
544// first quote. if quoted false, pull out and correct newline (\n) or
545// unprintable character terminated subreason.
546//
547// Heuristics to find termination is painted into a corner:
548
549// single bit error for quote ' that we can block. It is acceptable for
550// the others 7, g in reason. 2/9 chance will miss the terminating quote,
551// but there is always the terminating newline that usually immediately
552// follows to fortify our chances.
553bool likely_single_quote(char c) {
554 switch (static_cast<uint8_t>(c)) {
555 case '\'': // '\''
556 case '\'' ^ 0x01: // '&'
557 case '\'' ^ 0x02: // '%'
558 case '\'' ^ 0x04: // '#'
559 case '\'' ^ 0x08: // '/'
560 return true;
561 case '\'' ^ 0x10: // '7'
562 break;
563 case '\'' ^ 0x20: // '\a' (unprintable)
564 return true;
565 case '\'' ^ 0x40: // 'g'
566 break;
567 case '\'' ^ 0x80: // 0xA7 (unprintable)
568 return true;
569 }
570 return false;
571}
572
573// ::isprint(c) and likely_space() will prevent us from being called for
574// fundamentally printable entries, except for '\r' and '\b'.
575//
576// Except for * and J, single bit errors for \n, all others are non-
577// printable so easy catch. It is _acceptable_ for *, J or j to exist in
578// the reason string, so 2/9 chance we will miss the terminating newline.
579//
580// NB: J might not be acceptable, except if at the beginning or preceded
581// with a space, '(' or any of the quotes and their BER aliases.
582// NB: * might not be acceptable, except if at the beginning or preceded
583// with a space, another *, or any of the quotes or their BER aliases.
584//
585// To reduce the chances to closer to 1/9 is too complicated for the gain.
586bool likely_newline(char c) {
587 switch (static_cast<uint8_t>(c)) {
588 case '\n': // '\n' (unprintable)
589 case '\n' ^ 0x01: // '\r' (unprintable)
590 case '\n' ^ 0x02: // '\b' (unprintable)
591 case '\n' ^ 0x04: // 0x0E (unprintable)
592 case '\n' ^ 0x08: // 0x02 (unprintable)
593 case '\n' ^ 0x10: // 0x1A (unprintable)
594 return true;
595 case '\n' ^ 0x20: // '*'
596 case '\n' ^ 0x40: // 'J'
597 break;
598 case '\n' ^ 0x80: // 0x8A (unprintable)
599 return true;
600 }
601 return false;
602}
603
604// ::isprint(c) will prevent us from being called for all the printable
605// matches below. If we let unprintables through because of this, they
606// get converted to underscore (_) by the validation phase.
607bool likely_space(char c) {
608 switch (static_cast<uint8_t>(c)) {
609 case ' ': // ' '
610 case ' ' ^ 0x01: // '!'
611 case ' ' ^ 0x02: // '"'
612 case ' ' ^ 0x04: // '$'
613 case ' ' ^ 0x08: // '('
614 case ' ' ^ 0x10: // '0'
615 case ' ' ^ 0x20: // '\0' (unprintable)
616 case ' ' ^ 0x40: // 'P'
617 case ' ' ^ 0x80: // 0xA0 (unprintable)
618 case '\t': // '\t'
619 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
620 case '\t' ^ 0x02: // '\v' (unprintable)
621 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
622 case '\t' ^ 0x08: // 0x01 (unprintable)
623 case '\t' ^ 0x10: // 0x19 (unprintable)
624 case '\t' ^ 0x20: // ')'
625 case '\t' ^ 0x40: // '1'
626 case '\t' ^ 0x80: // 0x89 (unprintable)
627 return true;
628 }
629 return false;
630}
631
632std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700633 static constexpr size_t max_reason_length = 256;
634
635 std::string subReason(content.substr(pos, max_reason_length));
636 // Correct against any known strings that Bit Error Match
637 for (const auto& s : knownReasons) {
638 correctForBitErrorOrUnderline(subReason, s);
639 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700640 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700641 for (const auto& m : kBootReasonMap) {
642 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700643 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700644 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
645 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700646 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700647 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700648 correctForBitErrorOrUnderline(subReason,
649 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
650 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
651 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700652 }
653 }
654 for (pos = 0; pos < subReason.length(); ++pos) {
655 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700656 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
657 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700658 subReason.erase(pos);
659 break;
660 }
661 }
662 transformReason(subReason);
663 return subReason;
664}
665
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700666bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700667 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700668 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
669 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700670 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700671 // Invented for Android to allow daemons that specifically trigger sysrq
672 // to communicate more accurate boot subreasons via last console messages.
673 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
674 auto pos = console.rfind(sysrqSubreason);
675 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700676 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700677 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700678 return true;
679 }
680 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
681 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700682 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700683 return true;
684 }
685 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700686 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700687 return true;
688 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700689
690 std::string panic("Kernel panic - not syncing: ");
691 auto pos = console.rfind(panic);
692 if (pos != std::string::npos) {
693 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
694 {"Out of memory", "oom"},
695 {"out of memory", "oom"},
696 {"Oh boy, that early out of memory", "oom"}, // omg
697 {"BUG!", "bug"},
698 {"hung_task: blocked tasks", "hung"},
699 {"audit: ", "audit"},
700 {"scheduling while atomic", "atomic"},
701 {"Attempted to kill init!", "init"},
702 {"Requested init", "init"},
703 {"No working init", "init"},
704 {"Could not decompress init", "init"},
705 {"RCU Stall", "hung,rcu"},
706 {"stack-protector", "stack"},
707 {"kernel stack overflow", "stack"},
708 {"Corrupt kernel stack", "stack"},
709 {"low stack detected", "stack"},
710 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700711 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
712 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
713 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
714 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700715 };
716
717 ret = "kernel_panic";
718 for (auto& s : panicReasons) {
719 if (console.find(panic + s.first, pos) != std::string::npos) {
720 ret += "," + s.second;
721 return true;
722 }
723 }
724 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
725 if (reason.length() > 3) {
726 ret += "," + reason;
727 }
728 return true;
729 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700730 return false;
731}
732
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700733bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
734 return addKernelPanicSubReason(pstoreConsole(content), ret);
735}
736
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700737const char system_reboot_reason_property[] = "sys.boot.reason";
738const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
Mark Salyzynadc433d2018-06-05 08:17:35 -0700739const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700740const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
741
742// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
743std::string BootReasonStrToReason(const std::string& boot_reason) {
744 std::string ret(GetProperty(system_reboot_reason_property));
745 std::string reason(boot_reason);
746 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
747 if (reason == ret) ret = "";
748
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700749 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700750
751 // Is the current system boot reason sys.boot.reason valid?
752 if (!isKnownRebootReason(ret)) ret = "";
753
754 if (ret == "") {
755 // Is the bootloader boot reason ro.boot.bootreason known?
756 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700757 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700758 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700759 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700760 if (r == s) {
761 if (isBluntRebootReason(s)) {
762 blunt = s;
763 } else {
764 ret = s;
765 break;
766 }
767 }
768 }
769 if (ret == "") ret = blunt;
770 if (ret != "") break;
771 }
772 }
773
774 if (ret == "") {
775 // A series of checks to take some officially unsupported reasons
776 // reported by the bootloader and find some logical and canonical
777 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700778 // to behave and follow our CTS standards.
779 //
780 // first member is the output
781 // second member is an unanchored regex for an alias
782 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700783 // If output has a prefix of <bang> '!', we do not use it as a
784 // match needle (and drop the <bang> prefix when landing in output),
785 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700786 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700787 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700788 {"watchdog", "wdog"},
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700789 {"cold,powerkey", "powerkey|power_key|PowerKey"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700790 {"kernel_panic", "panic"},
791 {"shutdown,thermal", "thermal"},
792 {"warm,s3_wakeup", "s3_wakeup"},
793 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700794 {"cold,charger", "usb"},
795 {"cold,rtc", "rtc"},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700796 {"cold,rtc,2sec", "2sec_reboot"},
797 {"!warm", "wdt_by_pass_pwk"}, // change flavour of blunt
798 {"!reboot", "^wdt$"}, // change flavour of blunt
799 {"reboot,tool", "tool_by_pass_pwk"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700800 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700801 };
802
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700803 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700804 size_t firstHasNot = s.first[0] == '!';
805 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700806 ret = s.first;
807 break;
808 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700809 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700810 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700811 break;
812 }
813 }
814 }
815
816 // If watchdog is the reason, see if there is a security angle?
817 if (ret == "watchdog") {
818 if (reason.find("sec") != std::string::npos) {
819 ret += ",security";
820 }
821 }
822
Mark Salyzyn64610892017-09-18 10:41:14 -0700823 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700824 // Check to see if last klog has some refinement hints.
825 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700826 if (readPstoreConsole(content)) {
827 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700828 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700829 } else if (isBluntRebootReason(ret)) {
830 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700831
Mark Salyzyn64610892017-09-18 10:41:14 -0700832 // Check to see if last klog has some refinement hints.
833 std::string content;
834 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700835 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700836 // The toybox reboot command used directly (unlikely)? But also
837 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700838 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700839 ret = "shutdown"; // Still too blunt, but more accurate.
840 // ToDo: init should record the shutdown reason to kernel messages ala:
841 // init: shutdown system with command 'last_reboot_reason'
842 // so that if pstore has persistence we can get some details
843 // that could be missing in last_reboot_reason_property.
844 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700845
Mark Salyzyn64610892017-09-18 10:41:14 -0700846 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700847 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700848 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700849 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700850 if (subReason != "") { // Will not land "reboot" as that is too blunt.
851 if (isKernelRebootReason(subReason)) {
852 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700853 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700854 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700855 } else {
856 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700857 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700858 }
Mark Salyzyn15199252018-03-16 09:26:05 -0700859 // Some bootloaders shutdown results record in last kernel message.
860 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
861 ret = "shutdown";
862 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700863 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700864
Mark Salyzyn64610892017-09-18 10:41:14 -0700865 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700866 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700867 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700868 ((console.rfind("Power held for ") != std::string::npos) ||
869 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700870 ret = "cold";
871 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700872 }
873
874 // The following battery test should migrate to a default system health HAL
875
876 // Let us not worry if the reboot command was issued, for the cases of
877 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
878 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
879 // battery could conceivably lead to these, so worthy of override.
880 if (isBluntRebootReason(ret)) {
881 // Heuristic to determine if shutdown possibly because of a dead battery?
882 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700883 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700884 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700885 const pstoreConsole console(content);
886 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700887 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700888 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700889 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700890 // correct common errors
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700891 correctForBitError(digits, "100 ");
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700892 if (digits[0] == '!') digits[0] = '1';
893 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700894 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700895 const char* endptr = digits.c_str();
896 unsigned level = 0;
897 while (::isdigit(*endptr)) {
898 level *= 10;
899 level += *endptr++ - '0';
900 // make sure no leading zeros, except zero itself, and range check.
901 if ((level == 0) || (level > 100)) break;
902 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700903 // example bit error rate issues for 10%
904 // 'l=10 ' no bits in error
905 // 'l=00 ' single bit error (fails above)
906 // 'l=1 ' single bit error
907 // 'l=0 ' double bit error
908 // There are others, not typically critical because of 2%
909 // battery_dead_threshold. KISS check, make sure second
910 // character after digit sequence is not a space.
911 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700912 LOG(INFO) << "Battery level at shutdown " << level << "%";
913 if (level <= battery_dead_threshold) {
914 ret = "shutdown,battery";
915 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700916 } else { // Most likely
917 digits = ""; // reset digits
918
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700919 // Content buffer no longer will have console data. Beware if more
920 // checks added below, that depend on parsing console content.
921 content = "";
922
923 LOG(DEBUG) << "Can not find last low battery in last console messages";
924 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700925 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700926 if (fp != nullptr) {
927 android::base::ReadFdToString(fileno(fp), &content);
928 }
929 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700930 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700931
Luis Hector Chavez0becca32018-06-08 15:02:40 -0700932 pos = content.find(logcat_battery); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700933 if (pos != std::string::npos) {
Luis Hector Chavez0becca32018-06-08 15:02:40 -0700934 digits = content.substr(pos + strlen(logcat_battery), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700935 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700936 endptr = digits.c_str();
937 level = 0;
938 while (::isdigit(*endptr)) {
939 level *= 10;
940 level += *endptr++ - '0';
941 // make sure no leading zeros, except zero itself, and range check.
942 if ((level == 0) || (level > 100)) break;
943 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700944 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700945 LOG(INFO) << "Battery level at startup " << level << "%";
946 if (level <= battery_dead_threshold) {
947 ret = "shutdown,battery";
948 }
949 } else {
950 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
951 }
952 }
953 }
954
955 // Is there a controlled shutdown hint in last_reboot_reason_property?
956 if (isBluntRebootReason(ret)) {
957 // Content buffer no longer will have console data. Beware if more
958 // checks added below, that depend on parsing console content.
959 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700960 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700961
Mark Salyzyn62909822017-10-09 09:27:16 -0700962 // Anything in last is better than 'super-blunt' reboot or shutdown.
963 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
964 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700965 }
966 }
967
968 // Other System Health HAL reasons?
969
970 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
971 // possibly offer hardware-specific clues from the PMIC.
972 }
973
974 // If unknown left over from above, make it "reboot,<boot_reason>"
975 if (ret == "") {
976 ret = "reboot";
977 if (android::base::StartsWith(reason, "reboot")) {
978 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700979 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700980 reason = reason.substr(1);
981 }
982 }
983 if (reason != "") {
984 ret += ",";
985 ret += reason;
986 }
987 }
988
989 LOG(INFO) << "Canonical boot reason: " << ret;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700990 return ret;
991}
992
James Hawkinsb9cf7712016-04-08 15:32:19 -0700993// Returns the appropriate metric key prefix for the boot_complete metric such
994// that boot metrics after a system update are labeled as ota_boot_complete;
995// otherwise, they are labeled as boot_complete. This method encapsulates the
996// bookkeeping required to track when a system update has occurred by storing
997// the UTC timestamp of the system build date and comparing against the current
998// system build date.
999std::string CalculateBootCompletePrefix() {
1000 static const std::string kBuildDateKey = "build_date";
1001 std::string boot_complete_prefix = "boot_complete";
1002
1003 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -07001004 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -07001005 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -07001006 return std::string();
1007 }
James Hawkinsb9cf7712016-04-08 15:32:19 -07001008
1009 BootEventRecordStore boot_event_store;
1010 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -07001011 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1012 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1013 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001014 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001015 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001016 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001017 boot_complete_prefix = "ota_" + boot_complete_prefix;
1018 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001019 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001020 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001021 }
1022
1023 return boot_complete_prefix;
1024}
1025
James Hawkinsef0a0902017-01-06 14:38:23 -08001026// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001027void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001028 std::string value = GetProperty(property);
1029
James Hawkins27c05222017-01-26 11:55:44 -08001030 int32_t time_in_ms;
1031 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001032 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1033 }
1034}
1035
James Hawkins1bfcaec2017-05-19 14:27:27 -07001036// A map from bootloader timing stage to the time that stage took during boot.
1037typedef std::map<std::string, int32_t> BootloaderTimingMap;
1038
1039// Returns a mapping from bootloader stage names to the time those stages
1040// took to boot.
1041const BootloaderTimingMap GetBootLoaderTimings() {
1042 BootloaderTimingMap timings;
1043
1044 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1045 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -08001046 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001047 if (value.empty()) {
1048 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001049 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001050 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001051
1052 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001053 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001054 // |stageTiming| is of the form 'stage:time'.
1055 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001056 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001057
1058 std::string stageName = stageTimingValues[0];
1059 int32_t time_ms;
1060 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001061 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001062 }
1063 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001064
James Hawkins1bfcaec2017-05-19 14:27:27 -07001065 return timings;
1066}
1067
Tej Singh4eacd382018-01-25 17:59:57 -08001068// Returns the total bootloader boot time from the ro.boot.boottime system property.
1069int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1070 int32_t total_time = 0;
1071 for (const auto& timing : bootloader_timings) {
1072 total_time += timing.second;
1073 }
1074
1075 return total_time;
1076}
1077
James Hawkins1bfcaec2017-05-19 14:27:27 -07001078// Parses and records the set of bootloader stages and associated boot times
1079// from the ro.boot.boottime system property.
1080void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1081 const BootloaderTimingMap& bootloader_timings) {
1082 int32_t total_time = 0;
1083 for (const auto& timing : bootloader_timings) {
1084 total_time += timing.second;
1085 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1086 }
1087
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001088 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001089}
1090
Tej Singh4eacd382018-01-25 17:59:57 -08001091// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001092// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001093std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1094 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001095 int32_t bootloader_time_ms = 0;
1096
1097 for (const auto& timing : bootloader_timings) {
1098 if (timing.first.compare("SW") != 0) {
1099 bootloader_time_ms += timing.second;
1100 }
1101 }
1102
1103 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001104 return bootloader_duration + uptime;
1105}
1106
1107// Records the closest estimation to the absolute device boot time in seconds.
1108// i.e. from power on to boot_complete, including bootloader times.
1109void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1110 std::chrono::milliseconds absolute_total) {
1111 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1112 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1113}
1114
1115// Logs the total boot time and reason to statsd.
1116void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1117 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1118 double time_since_last_boot_sec) {
1119 const std::string reason(GetProperty(bootloader_reboot_reason_property));
1120
1121 if (reason.empty()) {
1122 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
1123 end_time.count(), total_duration.count(),
1124 (int64_t)bootloader_duration_ms,
1125 (int64_t)time_since_last_boot_sec * 1000);
1126 return;
1127 }
1128
Tej Singhfe3e7622018-02-06 15:57:38 -08001129 const std::string system_reason(GetProperty(system_reboot_reason_property));
Tej Singh4eacd382018-01-25 17:59:57 -08001130 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1131 system_reason.c_str(), end_time.count(), total_duration.count(),
1132 (int64_t)bootloader_duration_ms,
1133 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001134}
1135
Tej Singhfe3e7622018-02-06 15:57:38 -08001136void SetSystemBootReason() {
1137 const std::string bootloader_boot_reason(GetProperty(bootloader_reboot_reason_property));
1138 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1139 // Record the scrubbed system_boot_reason to the property
1140 SetProperty(system_reboot_reason_property, system_boot_reason);
Mark Salyzynadc433d2018-06-05 08:17:35 -07001141 // Shift last_reboot_reason_property to last_last_reboot_reason_property
1142 std::string last_boot_reason(GetProperty(last_reboot_reason_property));
1143 if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1144 last_boot_reason = system_boot_reason;
1145 } else {
1146 transformReason(last_boot_reason);
1147 }
1148 SetProperty(last_last_reboot_reason_property, last_boot_reason);
1149 SetProperty(last_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001150}
1151
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001152// Gets the boot time offset. This is useful when Android is running in a
1153// container, because the boot_clock is not reset when Android reboots.
1154std::chrono::nanoseconds GetBootTimeOffset() {
1155 static const int64_t boottime_offset =
1156 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1157 return std::chrono::nanoseconds(boottime_offset);
1158}
1159
1160// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1161// clock.
1162android::base::boot_clock::duration GetUptime() {
1163 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1164}
1165
James Hawkinsc08e9962016-03-11 14:59:50 -08001166// Records several metrics related to the time it takes to boot the device,
1167// including disambiguating boot time on encrypted or non-encrypted devices.
1168void RecordBootComplete() {
1169 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001170 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001171
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001172 auto uptime_ns = GetUptime();
1173 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001174 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001175 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001176
1177 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1178 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001179 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001180 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001181 }
1182
1183 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001184
James Hawkinsb9cf7712016-04-08 15:32:19 -07001185 // The boot_complete metric has two variants: boot_complete and
1186 // ota_boot_complete. The latter signifies that the device is booting after
1187 // a system update.
1188 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001189 if (boot_complete_prefix.empty()) {
1190 // The system is hosed because the build date property could not be read.
1191 return;
1192 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001193
1194 // post_decrypt_time_elapsed is only logged on encrypted devices.
1195 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1196 // Log the amount of time elapsed until the device is decrypted, which
1197 // includes the variable amount of time the user takes to enter the
1198 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001199 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001200
1201 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001202 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001203 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001204 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001205 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001206 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1207 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001208 }
1209
1210 // Record the total time from device startup to boot complete, regardless of
1211 // encryption state.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001212 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001213
1214 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1215 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1216 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001217
James Hawkins1bfcaec2017-05-19 14:27:27 -07001218 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001219 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001220 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1221
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001222 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001223 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1224 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1225
1226 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1227 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1228
1229 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1230 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001231}
1232
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001233// Records the boot_reason metric by querying the ro.boot.bootreason system
1234// property.
1235void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001236 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -07001237
1238 if (reason.empty()) {
1239 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1240 // (and not corruption anywhere else in the reporting pipeline).
1241 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1242 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1243 } else {
1244 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1245 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1246 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001247
1248 // Log the raw bootloader_boot_reason property value.
1249 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001250 BootEventRecordStore boot_event_store;
1251 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001252
1253 // Log the scrubbed system_boot_reason.
Tej Singhfe3e7622018-02-06 15:57:38 -08001254 const std::string system_reason(GetProperty(system_reboot_reason_property));
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001255 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1256 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1257
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001258 if (reason == "") {
1259 SetProperty(bootloader_reboot_reason_property, system_reason);
1260 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001261}
1262
James Hawkins500d7152016-02-16 15:05:54 -08001263// Records two metrics related to the user resetting a device: the time at
1264// which the device is reset, and the time since the user last reset the
1265// device. The former is only set once per-factory reset.
1266void RecordFactoryReset() {
1267 BootEventRecordStore boot_event_store;
1268 BootEventRecordStore::BootEventRecord record;
1269
1270 time_t current_time_utc = time(nullptr);
1271
James Hawkins0660b302016-03-08 16:18:15 -08001272 if (current_time_utc < 0) {
1273 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001274 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1275 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001276
James Hawkins9aec9262017-01-31 11:42:24 -08001277 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001278 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001279 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1280 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001281 return;
1282 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001283 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001284
James Hawkins9aec9262017-01-31 11:42:24 -08001285 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001286 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001287 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001288 }
1289
James Hawkins500d7152016-02-16 15:05:54 -08001290 // The factory_reset boot event does not exist after the device is reset, so
1291 // use this signal to mark the time of the factory reset.
1292 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1293 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001294
1295 // Don't log the time_since_factory_reset until some time has elapsed.
1296 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001297 return;
1298 }
1299
1300 // Calculate and record the difference in time between now and the
1301 // factory_reset time.
1302 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001303 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001304
James Hawkins9aec9262017-01-31 11:42:24 -08001305 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001306 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001307 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001308
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001309 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1310 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001311}
1312
James Hawkinsabd73e62016-01-19 15:10:38 -08001313} // namespace
1314
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001315int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001316 android::base::InitLogging(argv);
1317
1318 const std::string cmd_line = GetCommandLine(argc, argv);
1319 LOG(INFO) << "Service started: " << cmd_line;
1320
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001321 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001322 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001323 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001324 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001325 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001326 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001327 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001328 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001329 { "help", no_argument, NULL, 'h' },
1330 { "log", no_argument, NULL, 'l' },
1331 { "print", no_argument, NULL, 'p' },
1332 { "record", required_argument, NULL, 'r' },
1333 { value_str, required_argument, NULL, 0 },
1334 { system_boot_reason_str, no_argument, NULL, 0 },
1335 { boot_complete_str, no_argument, NULL, 0 },
1336 { boot_reason_str, no_argument, NULL, 0 },
1337 { factory_reset_str, no_argument, NULL, 0 },
1338 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001339 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001340 };
1341
James Hawkinsc6275582016-03-22 10:47:44 -07001342 std::string boot_event;
1343 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001344 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001345 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001346 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001347 // This case handles long options which have no single-character mapping.
1348 case 0: {
1349 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001350 if (option_name == value_str) {
1351 // |optarg| is an external variable set by getopt representing
1352 // the option argument.
1353 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001354 } else if (option_name == system_boot_reason_str) {
1355 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001356 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001357 RecordBootComplete();
1358 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001359 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001360 } else if (option_name == factory_reset_str) {
1361 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001362 } else {
1363 LOG(ERROR) << "Invalid option: " << option_name;
1364 }
1365 break;
1366 }
1367
James Hawkinsabd73e62016-01-19 15:10:38 -08001368 case 'h': {
1369 ShowHelp(argv[0]);
1370 break;
1371 }
1372
1373 case 'l': {
1374 LogBootEvents();
1375 break;
1376 }
1377
1378 case 'p': {
1379 PrintBootEvents();
1380 break;
1381 }
1382
1383 case 'r': {
1384 // |optarg| is an external variable set by getopt representing
1385 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001386 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001387 break;
1388 }
1389
1390 default: {
1391 DCHECK_EQ(opt, '?');
1392
1393 // |optopt| is an external variable set by getopt representing
1394 // the value of the invalid option.
1395 LOG(ERROR) << "Invalid option: " << optopt;
1396 ShowHelp(argv[0]);
1397 return EXIT_FAILURE;
1398 }
1399 }
1400 }
1401
James Hawkinsc6275582016-03-22 10:47:44 -07001402 if (!boot_event.empty()) {
1403 RecordBootEventFromCommandLine(boot_event, value);
1404 }
1405
James Hawkinsabd73e62016-01-19 15:10:38 -08001406 return 0;
1407}