blob: 1ce0ec4c29d42ae72e9a1b8fc86657d8e636d474 [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>
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -070030#include <iterator>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080031#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080032#include <memory>
Mark Salyzyn25900dd2018-03-16 09:05:59 -070033#include <regex>
James Hawkinsabd73e62016-01-19 15:10:38 -080034#include <string>
Mark Salyzyn853bb802018-03-16 08:44:56 -070035#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080036#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070037
James Hawkinse78ea772017-03-24 11:43:02 -070038#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070039#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080040#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070041#include <android-base/parseint.h>
Luis Hector Chavez583d34c2018-04-12 15:25:15 -070042#include <android-base/properties.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080043#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070044#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070045#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080046#include <cutils/properties.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 Hawkins25f71222017-10-10 16:37:05 -0700117constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800118constexpr int32_t kUnknownBootReason = 1;
119
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800120// A mapping from boot reason string, as read from the ro.boot.bootreason
121// system property, to a unique integer ID. Viewers of log data dashboards for
122// the boot_reason metric may refer to this mapping to discern the histogram
123// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800124const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700125 {"empty", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700126 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700127 {"normal", 2},
128 {"recovery", 3},
129 {"reboot", 4},
130 {"PowerKey", 5},
131 {"hard_reset", 6},
132 {"kernel_panic", 7},
133 {"rpm_err", 8},
134 {"hw_reset", 9},
135 {"tz_err", 10},
136 {"adsp_err", 11},
137 {"modem_err", 12},
138 {"mba_err", 13},
139 {"Watchdog", 14},
140 {"Panic", 15},
141 {"power_key", 16},
142 {"power_on", 17},
143 {"Reboot", 18},
144 {"rtc", 19},
145 {"edl", 20},
146 {"oem_pon1", 21},
147 {"oem_powerkey", 22},
148 {"oem_unknown_reset", 23},
149 {"srto: HWWDT reset SC", 24},
150 {"srto: HWWDT reset platform", 25},
151 {"srto: bootloader", 26},
152 {"srto: kernel panic", 27},
153 {"srto: kernel watchdog reset", 28},
154 {"srto: normal", 29},
155 {"srto: reboot", 30},
156 {"srto: reboot-bootloader", 31},
157 {"srto: security watchdog reset", 32},
158 {"srto: wakesrc", 33},
159 {"srto: watchdog", 34},
160 {"srto:1-1", 35},
161 {"srto:omap_hsmm", 36},
162 {"srto:phy0", 37},
163 {"srto:rtc0", 38},
164 {"srto:touchpad", 39},
165 {"watchdog", 40},
166 {"watchdogr", 41},
167 {"wdog_bark", 42},
168 {"wdog_bite", 43},
169 {"wdog_reset", 44},
Mark Salyzyn274b5442018-08-07 08:45:13 -0700170 {"shutdown,", 45}, // Trailing comma is intentional. Do NOT use.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700171 {"shutdown,userrequested", 46},
172 {"reboot,bootloader", 47},
173 {"reboot,cold", 48},
174 {"reboot,recovery", 49},
175 {"thermal_shutdown", 50},
176 {"s3_wakeup", 51},
177 {"kernel_panic,sysrq", 52},
178 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700179 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700180 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700181 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700182 {"bootloader", 55},
183 {"cold", 56},
184 {"hard", 57},
185 {"warm", 58},
Mark Salyzyn15199252018-03-16 09:26:05 -0700186 {"reboot,kernel_power_off_charging__reboot_system", 59}, // Can not happen
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700187 {"thermal-shutdown", 60},
188 {"shutdown,thermal", 61},
189 {"shutdown,battery", 62},
190 {"reboot,ota", 63},
191 {"reboot,factory_reset", 64},
192 {"reboot,", 65},
193 {"reboot,shell", 66},
194 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700195 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700196 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700197 {"cold,powerkey", 70},
198 {"warm,s3_wakeup", 71},
199 {"hard,hw_reset", 72},
200 {"shutdown,suspend", 73}, // Suspend to RAM
201 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700202 {"power_on_key", 75},
203 {"reboot_by_key", 76},
204 {"wdt_by_pass_pwk", 77},
205 {"reboot_longkey", 78},
206 {"powerkey", 79},
207 {"usb", 80},
208 {"wdt", 81},
209 {"tool_by_pass_pwk", 82},
210 {"2sec_reboot", 83},
211 {"reboot,by_key", 84},
212 {"reboot,longkey", 85},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700213 {"reboot,2sec", 86}, // Deprecate in two years, replaced with cold,rtc,2sec
Mark Salyzync89f9da2017-10-24 15:35:34 -0700214 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700215 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
216 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn75046892018-05-03 13:11:15 -0700217 {"reboot,rescueparty", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800218 {"charge", 91},
219 {"oem_tz_crash", 92},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700220 {"uvlo", 93}, // aliasReasons converts to reboot,undervoltage
James Hawkins74b17582017-11-20 14:13:41 -0800221 {"oem_ps_hold", 94},
222 {"abnormal_reset", 95},
223 {"oemerr_unknown", 96},
224 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800225 {"watchdog_apps_bite", 98},
226 {"xpu_err", 99},
227 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800228 {"watchdog_rpm", 101},
229 {"watchdog_nonsec", 102},
230 {"watchdog_apps_bark", 103},
231 {"reboot_dmverity_corrupted", 104},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700232 {"reboot_smpl", 105}, // aliasReasons converts to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800233 {"watchdog_sdi_apps_reset", 106},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700234 {"smpl", 107}, // aliasReasons converts to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800235 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800236 {"reboot_normal", 109},
237 {"oem_lpass_cfg", 110},
238 {"oem_xpu_ns_error", 111},
239 {"power_key_press", 112},
240 {"hardware_reset", 113},
241 {"reboot_by_powerkey", 114},
242 {"reboot_verity", 115},
243 {"oem_rpm_undef_error", 116},
244 {"oem_crash_on_the_lk", 117},
245 {"oem_rpm_reset", 118},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700246 {"reboot,powerloss", 119},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700247 {"reboot,undervoltage", 120},
James Hawkinse2c27242017-12-18 13:40:27 -0800248 {"factory_cable", 121},
249 {"oem_ar6320_failed_to_powerup", 122},
250 {"watchdog_rpm_bite", 123},
251 {"power_on_cable", 124},
252 {"reboot_unknown", 125},
253 {"wireless_charger", 126},
254 {"0x776655ff", 127},
255 {"oem_thermal_bite_reset", 128},
256 {"charger", 129},
257 {"pon1", 130},
258 {"unknown", 131},
259 {"reboot_rtc", 132},
260 {"cold_boot", 133},
261 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800262 {"power-on", 135},
263 {"oem_adsp_resetting_the_soc", 136},
264 {"kpdpwr", 137},
265 {"oem_modem_timeout_waiting", 138},
266 {"usb_chg", 139},
267 {"warm_reset_0x02", 140},
268 {"warm_reset_0x80", 141},
269 {"pon_reason_0xb0", 142},
270 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800271 {"reboot_recovery_mode", 144},
272 {"oem_sdi_err_fatal", 145},
273 {"pmic_watchdog", 146},
274 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700275 {"cold,charger", 148},
276 {"cold,rtc", 149},
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700277 {"cold,rtc,2sec", 150},
278 {"reboot,tool", 151},
279 {"reboot,wdt", 152},
280 {"reboot,unknown", 153},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700281 {"kernel_panic,audit", 154},
282 {"kernel_panic,atomic", 155},
283 {"kernel_panic,hung", 156},
284 {"kernel_panic,hung,rcu", 157},
285 {"kernel_panic,init", 158},
286 {"kernel_panic,oom", 159},
287 {"kernel_panic,stack", 160},
Mark Salyzynafd66f22018-03-19 15:16:29 -0700288 {"kernel_panic,sysrq,livelock,alarm", 161}, // llkd
289 {"kernel_panic,sysrq,livelock,driver", 162}, // llkd
290 {"kernel_panic,sysrq,livelock,zombie", 163}, // llkd
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700291 {"kernel_panic,modem", 164},
292 {"kernel_panic,adsp", 165},
293 {"kernel_panic,dsps", 166},
294 {"kernel_panic,wcnss", 167},
Mark Salyzyn78e54fd2018-06-08 10:19:16 -0700295 {"kernel_panic,_sde_encoder_phys_cmd_handle_ppdone_timeout", 168},
Mark Salyzyn6fc08292019-03-11 10:06:36 -0700296 {"recovery,quiescent", 169},
297 {"reboot,quiescent", 170},
Jone Choud51036d2019-03-20 19:38:05 +0800298 {"reboot,rtc", 171},
299 {"reboot,dm-verity_device_corrupted", 172},
300 {"reboot,dm-verity_enforcing", 173},
301 {"reboot,keys_clear", 174},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800302};
303
304// Converts a string value representing the reason the system booted to an
305// integer representation. This is necessary for logging the boot_reason metric
306// via Tron, which does not accept non-integer buckets in histograms.
307int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800308 auto mapping = kBootReasonMap.find(boot_reason);
309 if (mapping != kBootReasonMap.end()) {
310 return mapping->second;
311 }
312
James Hawkins25f71222017-10-10 16:37:05 -0700313 if (boot_reason.empty()) {
314 return kEmptyBootReason;
315 }
316
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800317 LOG(INFO) << "Unknown boot reason: " << boot_reason;
318 return kUnknownBootReason;
319}
320
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700321// Canonical list of supported primary reboot reasons.
322const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700323 // clang-format off
324 // kernel
325 "watchdog",
326 "kernel_panic",
327 // strong
328 "recovery", // Should not happen from ro.boot.bootreason
329 "bootloader", // Should not happen from ro.boot.bootreason
330 // blunt
331 "cold",
332 "hard",
333 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700334 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700335 "shutdown", // Can not happen from ro.boot.bootreason
336 "reboot", // Default catch-all for anything unknown
337 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700338};
339
340// Returns true if the supplied reason prefix is considered detailed enough.
341bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700342 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700343 if (s == "cold") break;
344 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800345 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700346 return true;
347 }
348 }
349 return false;
350}
351
352// Returns true if the supplied reason prefix is associated with the kernel.
353bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700354 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700355 if (s == "recovery") break;
356 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800357 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700358 return true;
359 }
360 }
361 return false;
362}
363
364// Returns true if the supplied reason prefix is considered known.
365bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700366 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700367 // 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// If the reboot reason should be improved, report true if is too blunt.
376bool isBluntRebootReason(const std::string& r) {
377 if (isStrongRebootReason(r)) return false;
378
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700379 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700380
381 size_t pos = 0;
382 while ((pos = r.find(',', pos)) != std::string::npos) {
383 ++pos;
384 std::string next(r.substr(pos));
385 if (next.length() == 0) break;
386 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700387 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
388 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700389 }
390 return true;
391}
392
Mark Salyzyn64610892017-09-18 10:41:14 -0700393bool readPstoreConsole(std::string& console) {
394 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
395 return true;
396 }
397 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
398}
399
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700400// Implement a variant of std::string::rfind that is resilient to errors in
401// the data stream being inspected.
402class pstoreConsole {
403 private:
404 const size_t kBitErrorRate = 8; // number of bits per error
405 const std::string& console;
406
407 // Number of bits that differ between the two arguments l and r.
408 // Returns zero if the values for l and r are identical.
409 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
410
411 // A string comparison function, reports the number of errors discovered
412 // in the match to a maximum of the bitLength / kBitErrorRate, at that
413 // point returning npos to indicate match is too poor.
414 //
415 // Since called in rfind which works backwards, expect cache locality will
416 // help if we check in reverse here as well for performance.
417 //
418 // Assumption: l (from console.c_str() + pos) is long enough to house
419 // _r.length(), checked in rfind caller below.
420 //
421 size_t numError(size_t pos, const std::string& _r) const {
422 const char* l = console.c_str() + pos;
423 const char* r = _r.c_str();
424 size_t n = _r.length();
425 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
426 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
427 size_t count = 0;
428 n = 0;
429 do {
430 // individual character bit error rate > threshold + slop
431 size_t num = numError(*--le, *--re);
432 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
433 // total bit error rate > threshold + slop
434 count += num;
435 ++n;
436 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
437 return std::string::npos;
438 }
439 } while (le != reinterpret_cast<const uint8_t*>(l));
440 return count;
441 }
442
443 public:
444 explicit pstoreConsole(const std::string& console) : console(console) {}
445 // scope of argument must be equal to or greater than scope of pstoreConsole
446 explicit pstoreConsole(const std::string&& console) = delete;
447 explicit pstoreConsole(std::string&& console) = delete;
448
449 // Our implementation of rfind, use exact match first, then resort to fuzzy.
450 size_t rfind(const std::string& needle) const {
451 size_t pos = console.rfind(needle); // exact match?
452 if (pos != std::string::npos) return pos;
453
454 // Check to make sure needle fits in console string.
455 pos = console.length();
456 if (needle.length() > pos) return std::string::npos;
457 pos -= needle.length();
458 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800459 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700460 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800461 if (pos == 0) break;
462 --pos;
463 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700464 return std::string::npos;
465 }
466
467 // Our implementation of find, use only fuzzy match.
468 size_t find(const std::string& needle, size_t start = 0) const {
469 // Check to make sure needle fits in console string.
470 if (needle.length() > console.length()) return std::string::npos;
471 const size_t last_pos = console.length() - needle.length();
472 // fuzzy match to maximum kBitErrorRate
473 for (size_t pos = start; pos <= last_pos; ++pos) {
474 if (numError(pos, needle) != std::string::npos) return pos;
475 }
476 return std::string::npos;
477 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700478
479 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700480};
481
482// If bit error match to needle, correct it.
483// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700484bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700485 bool corrected = false;
486 if (reason.length() < needle.length()) return corrected;
487 const pstoreConsole console(reason);
488 const size_t last_pos = reason.length() - needle.length();
489 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
490 pos = console.find(needle, pos);
491 if (pos == std::string::npos) break;
492
493 // exact match has no malice
494 if (needle == reason.substr(pos, needle.length())) continue;
495
496 corrected = true;
497 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
498 }
499 return corrected;
500}
501
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700502// If bit error match to needle, correct it.
503// Return true if any corrections were discovered and applied.
504// Try again if we can replace underline with spaces.
505bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
506 bool corrected = correctForBitError(reason, needle);
507 std::string _needle(needle);
508 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
509 [](char c) { return (c == '_') ? ' ' : c; });
510 if (needle != _needle) {
511 corrected |= correctForBitError(reason, _needle);
512 }
513 return corrected;
514}
515
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700516// Converts a string value representing the reason the system booted to a
517// string complying with Android system standard reason.
518void transformReason(std::string& reason) {
519 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
520 std::transform(reason.begin(), reason.end(), reason.begin(),
521 [](char c) { return ::isblank(c) ? '_' : c; });
522 std::transform(reason.begin(), reason.end(), reason.begin(),
523 [](char c) { return ::isprint(c) ? c : '?'; });
524}
525
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700526// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
527// kernel_panic,<subreason>.
528//
529// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
530// or unprintable character terminated subreason, pos is supplied just beyond
531// first quote. if quoted false, pull out and correct newline (\n) or
532// unprintable character terminated subreason.
533//
534// Heuristics to find termination is painted into a corner:
535
536// single bit error for quote ' that we can block. It is acceptable for
537// the others 7, g in reason. 2/9 chance will miss the terminating quote,
538// but there is always the terminating newline that usually immediately
539// follows to fortify our chances.
540bool likely_single_quote(char c) {
541 switch (static_cast<uint8_t>(c)) {
542 case '\'': // '\''
543 case '\'' ^ 0x01: // '&'
544 case '\'' ^ 0x02: // '%'
545 case '\'' ^ 0x04: // '#'
546 case '\'' ^ 0x08: // '/'
547 return true;
548 case '\'' ^ 0x10: // '7'
549 break;
550 case '\'' ^ 0x20: // '\a' (unprintable)
551 return true;
552 case '\'' ^ 0x40: // 'g'
553 break;
554 case '\'' ^ 0x80: // 0xA7 (unprintable)
555 return true;
556 }
557 return false;
558}
559
560// ::isprint(c) and likely_space() will prevent us from being called for
561// fundamentally printable entries, except for '\r' and '\b'.
562//
563// Except for * and J, single bit errors for \n, all others are non-
564// printable so easy catch. It is _acceptable_ for *, J or j to exist in
565// the reason string, so 2/9 chance we will miss the terminating newline.
566//
567// NB: J might not be acceptable, except if at the beginning or preceded
568// with a space, '(' or any of the quotes and their BER aliases.
569// NB: * might not be acceptable, except if at the beginning or preceded
570// with a space, another *, or any of the quotes or their BER aliases.
571//
572// To reduce the chances to closer to 1/9 is too complicated for the gain.
573bool likely_newline(char c) {
574 switch (static_cast<uint8_t>(c)) {
575 case '\n': // '\n' (unprintable)
576 case '\n' ^ 0x01: // '\r' (unprintable)
577 case '\n' ^ 0x02: // '\b' (unprintable)
578 case '\n' ^ 0x04: // 0x0E (unprintable)
579 case '\n' ^ 0x08: // 0x02 (unprintable)
580 case '\n' ^ 0x10: // 0x1A (unprintable)
581 return true;
582 case '\n' ^ 0x20: // '*'
583 case '\n' ^ 0x40: // 'J'
584 break;
585 case '\n' ^ 0x80: // 0x8A (unprintable)
586 return true;
587 }
588 return false;
589}
590
591// ::isprint(c) will prevent us from being called for all the printable
592// matches below. If we let unprintables through because of this, they
593// get converted to underscore (_) by the validation phase.
594bool likely_space(char c) {
595 switch (static_cast<uint8_t>(c)) {
596 case ' ': // ' '
597 case ' ' ^ 0x01: // '!'
598 case ' ' ^ 0x02: // '"'
599 case ' ' ^ 0x04: // '$'
600 case ' ' ^ 0x08: // '('
601 case ' ' ^ 0x10: // '0'
602 case ' ' ^ 0x20: // '\0' (unprintable)
603 case ' ' ^ 0x40: // 'P'
604 case ' ' ^ 0x80: // 0xA0 (unprintable)
605 case '\t': // '\t'
606 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
607 case '\t' ^ 0x02: // '\v' (unprintable)
608 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
609 case '\t' ^ 0x08: // 0x01 (unprintable)
610 case '\t' ^ 0x10: // 0x19 (unprintable)
611 case '\t' ^ 0x20: // ')'
612 case '\t' ^ 0x40: // '1'
613 case '\t' ^ 0x80: // 0x89 (unprintable)
614 return true;
615 }
616 return false;
617}
618
619std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700620 static constexpr size_t max_reason_length = 256;
621
622 std::string subReason(content.substr(pos, max_reason_length));
623 // Correct against any known strings that Bit Error Match
624 for (const auto& s : knownReasons) {
625 correctForBitErrorOrUnderline(subReason, s);
626 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700627 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700628 for (const auto& m : kBootReasonMap) {
629 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700630 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700631 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
632 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700633 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700634 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700635 correctForBitErrorOrUnderline(subReason,
636 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
637 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
638 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700639 }
640 }
641 for (pos = 0; pos < subReason.length(); ++pos) {
642 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700643 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
644 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700645 subReason.erase(pos);
646 break;
647 }
648 }
649 transformReason(subReason);
650 return subReason;
651}
652
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700653bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700654 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700655 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
656 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700657 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700658 // Invented for Android to allow daemons that specifically trigger sysrq
659 // to communicate more accurate boot subreasons via last console messages.
660 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
661 auto pos = console.rfind(sysrqSubreason);
662 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700663 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700664 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700665 return true;
666 }
667 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
668 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700669 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700670 return true;
671 }
672 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700673 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700674 return true;
675 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700676
677 std::string panic("Kernel panic - not syncing: ");
678 auto pos = console.rfind(panic);
679 if (pos != std::string::npos) {
680 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
681 {"Out of memory", "oom"},
682 {"out of memory", "oom"},
683 {"Oh boy, that early out of memory", "oom"}, // omg
684 {"BUG!", "bug"},
685 {"hung_task: blocked tasks", "hung"},
686 {"audit: ", "audit"},
687 {"scheduling while atomic", "atomic"},
688 {"Attempted to kill init!", "init"},
689 {"Requested init", "init"},
690 {"No working init", "init"},
691 {"Could not decompress init", "init"},
692 {"RCU Stall", "hung,rcu"},
693 {"stack-protector", "stack"},
694 {"kernel stack overflow", "stack"},
695 {"Corrupt kernel stack", "stack"},
696 {"low stack detected", "stack"},
697 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700698 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
699 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
700 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
701 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700702 };
703
704 ret = "kernel_panic";
705 for (auto& s : panicReasons) {
706 if (console.find(panic + s.first, pos) != std::string::npos) {
707 ret += "," + s.second;
708 return true;
709 }
710 }
711 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
712 if (reason.length() > 3) {
713 ret += "," + reason;
714 }
715 return true;
716 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700717 return false;
718}
719
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700720bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
721 return addKernelPanicSubReason(pstoreConsole(content), ret);
722}
723
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700724const char system_reboot_reason_property[] = "sys.boot.reason";
725const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
Mark Salyzynadc433d2018-06-05 08:17:35 -0700726const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700727constexpr size_t history_reboot_reason_size = 4;
728const char history_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY ".history";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700729const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
730
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700731// Land system_boot_reason into system_reboot_reason_property.
732// Shift system_boot_reason into history_reboot_reason_property.
733void BootReasonAddToHistory(const std::string& system_boot_reason) {
734 if (system_boot_reason.empty()) return;
735 LOG(INFO) << "Canonical boot reason: " << system_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800736 auto old_system_boot_reason = android::base::GetProperty(system_reboot_reason_property, "");
737 if (!android::base::SetProperty(system_reboot_reason_property, system_boot_reason)) {
738 android::base::SetProperty(system_reboot_reason_property,
739 system_boot_reason.substr(0, PROPERTY_VALUE_MAX - 1));
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700740 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800741 auto reason_history =
742 android::base::Split(android::base::GetProperty(history_reboot_reason_property, ""), "\n");
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700743 static auto mark = time(nullptr);
744 auto mark_str = std::string(",") + std::to_string(mark);
745 auto marked_system_boot_reason = system_boot_reason + mark_str;
746 if (!reason_history.empty()) {
747 // delete any entries that we just wrote in a previous
748 // call and leveraging duplicate line handling
749 auto last = old_system_boot_reason + mark_str;
750 // trim the list to (history_reboot_reason_size - 1)
751 ssize_t max = history_reboot_reason_size;
752 for (auto it = reason_history.begin(); it != reason_history.end();) {
753 if (it->empty() || (last == *it) || (marked_system_boot_reason == *it) || (--max <= 0)) {
754 it = reason_history.erase(it);
755 } else {
756 last = *it;
757 ++it;
758 }
759 }
760 }
761 // insert at the front, concatenating mark (<epoch time>) detail to the value.
762 reason_history.insert(reason_history.begin(), marked_system_boot_reason);
763 // If the property string is too long ( > PROPERTY_VALUE_MAX)
764 // we get an error, so trim out last entry and try again.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800765 while (!android::base::SetProperty(history_reboot_reason_property,
766 android::base::Join(reason_history, '\n'))) {
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700767 auto it = std::prev(reason_history.end());
768 if (it == reason_history.end()) break;
769 reason_history.erase(it);
770 }
771}
772
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700773// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
774std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800775 auto ret = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700776 std::string reason(boot_reason);
777 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
778 if (reason == ret) ret = "";
779
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700780 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700781
782 // Is the current system boot reason sys.boot.reason valid?
783 if (!isKnownRebootReason(ret)) ret = "";
784
785 if (ret == "") {
786 // Is the bootloader boot reason ro.boot.bootreason known?
787 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700788 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700789 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700790 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700791 if (r == s) {
792 if (isBluntRebootReason(s)) {
793 blunt = s;
794 } else {
795 ret = s;
796 break;
797 }
798 }
799 }
800 if (ret == "") ret = blunt;
801 if (ret != "") break;
802 }
803 }
804
805 if (ret == "") {
806 // A series of checks to take some officially unsupported reasons
807 // reported by the bootloader and find some logical and canonical
808 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700809 // to behave and follow our CTS standards.
810 //
811 // first member is the output
812 // second member is an unanchored regex for an alias
813 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700814 // If output has a prefix of <bang> '!', we do not use it as a
815 // match needle (and drop the <bang> prefix when landing in output),
816 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700817 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700818 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700819 {"watchdog", "wdog"},
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700820 {"cold,powerkey", "powerkey|power_key|PowerKey"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700821 {"kernel_panic", "panic"},
822 {"shutdown,thermal", "thermal"},
823 {"warm,s3_wakeup", "s3_wakeup"},
824 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700825 {"cold,charger", "usb"},
826 {"cold,rtc", "rtc"},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700827 {"cold,rtc,2sec", "2sec_reboot"},
828 {"!warm", "wdt_by_pass_pwk"}, // change flavour of blunt
829 {"!reboot", "^wdt$"}, // change flavour of blunt
830 {"reboot,tool", "tool_by_pass_pwk"},
Mark Salyzyn88d1b4a2018-06-07 09:39:24 -0700831 {"!reboot,longkey", "reboot_longkey"},
832 {"!reboot,longkey", "kpdpwr"},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700833 {"!reboot,undervoltage", "uvlo"},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700834 {"!reboot,powerloss", "smpl"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700835 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700836 };
837
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700838 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700839 size_t firstHasNot = s.first[0] == '!';
840 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700841 ret = s.first;
842 break;
843 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700844 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700845 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700846 break;
847 }
848 }
849 }
850
851 // If watchdog is the reason, see if there is a security angle?
852 if (ret == "watchdog") {
853 if (reason.find("sec") != std::string::npos) {
854 ret += ",security";
855 }
856 }
857
Mark Salyzyn64610892017-09-18 10:41:14 -0700858 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700859 // Check to see if last klog has some refinement hints.
860 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700861 if (readPstoreConsole(content)) {
862 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700863 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700864 } else if (isBluntRebootReason(ret)) {
865 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700866
Mark Salyzyn64610892017-09-18 10:41:14 -0700867 // Check to see if last klog has some refinement hints.
868 std::string content;
869 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700870 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700871 // The toybox reboot command used directly (unlikely)? But also
872 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700873 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700874 ret = "shutdown"; // Still too blunt, but more accurate.
875 // ToDo: init should record the shutdown reason to kernel messages ala:
876 // init: shutdown system with command 'last_reboot_reason'
877 // so that if pstore has persistence we can get some details
878 // that could be missing in last_reboot_reason_property.
879 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700880
Mark Salyzyn64610892017-09-18 10:41:14 -0700881 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700882 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700883 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700884 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700885 if (subReason != "") { // Will not land "reboot" as that is too blunt.
886 if (isKernelRebootReason(subReason)) {
887 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700888 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700889 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700890 } else {
891 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700892 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700893 }
Mark Salyzyn15199252018-03-16 09:26:05 -0700894 // Some bootloaders shutdown results record in last kernel message.
895 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
896 ret = "shutdown";
897 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700898 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700899
Mark Salyzyn64610892017-09-18 10:41:14 -0700900 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700901 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700902 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700903 ((console.rfind("Power held for ") != std::string::npos) ||
904 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700905 ret = "cold";
906 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700907 }
908
Elliott Hughes50a24eb2018-06-14 10:59:09 -0700909 // TODO: use the HAL to get battery level (http://b/77725702).
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700910
911 // Is there a controlled shutdown hint in last_reboot_reason_property?
912 if (isBluntRebootReason(ret)) {
913 // Content buffer no longer will have console data. Beware if more
914 // checks added below, that depend on parsing console content.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800915 content = android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700916 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700917
Mark Salyzyn62909822017-10-09 09:27:16 -0700918 // Anything in last is better than 'super-blunt' reboot or shutdown.
919 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
920 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700921 }
922 }
923
924 // Other System Health HAL reasons?
925
926 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
927 // possibly offer hardware-specific clues from the PMIC.
928 }
929
930 // If unknown left over from above, make it "reboot,<boot_reason>"
931 if (ret == "") {
932 ret = "reboot";
933 if (android::base::StartsWith(reason, "reboot")) {
934 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700935 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700936 reason = reason.substr(1);
937 }
938 }
939 if (reason != "") {
940 ret += ",";
941 ret += reason;
942 }
943 }
944
945 LOG(INFO) << "Canonical boot reason: " << ret;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700946 return ret;
947}
948
James Hawkinsb9cf7712016-04-08 15:32:19 -0700949// Returns the appropriate metric key prefix for the boot_complete metric such
950// that boot metrics after a system update are labeled as ota_boot_complete;
951// otherwise, they are labeled as boot_complete. This method encapsulates the
952// bookkeeping required to track when a system update has occurred by storing
953// the UTC timestamp of the system build date and comparing against the current
954// system build date.
955std::string CalculateBootCompletePrefix() {
956 static const std::string kBuildDateKey = "build_date";
957 std::string boot_complete_prefix = "boot_complete";
958
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800959 auto build_date_str = android::base::GetProperty("ro.build.date.utc", "");
James Hawkins4dded612016-07-28 11:50:23 -0700960 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700961 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700962 return std::string();
963 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700964
965 BootEventRecordStore boot_event_store;
966 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700967 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
968 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
969 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700970 BootReasonAddToHistory("reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700971 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700972 boot_complete_prefix = "ota_" + boot_complete_prefix;
973 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700974 BootReasonAddToHistory("reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700975 }
976
977 return boot_complete_prefix;
978}
979
James Hawkinsef0a0902017-01-06 14:38:23 -0800980// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700981void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800982 auto value = android::base::GetProperty(property, "");
James Hawkinsef0a0902017-01-06 14:38:23 -0800983
James Hawkins27c05222017-01-26 11:55:44 -0800984 int32_t time_in_ms;
985 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800986 boot_event_store->AddBootEventWithValue(property, time_in_ms);
987 }
988}
989
James Hawkins1bfcaec2017-05-19 14:27:27 -0700990// A map from bootloader timing stage to the time that stage took during boot.
991typedef std::map<std::string, int32_t> BootloaderTimingMap;
992
993// Returns a mapping from bootloader stage names to the time those stages
994// took to boot.
995const BootloaderTimingMap GetBootLoaderTimings() {
996 BootloaderTimingMap timings;
997
998 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
999 // where timeN is in milliseconds.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001000 auto value = android::base::GetProperty("ro.boot.boottime", "");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001001 if (value.empty()) {
1002 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001003 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001004 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001005
1006 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001007 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001008 // |stageTiming| is of the form 'stage:time'.
1009 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001010 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001011
Mark Salyzyn7c721162019-02-08 10:41:15 -08001012 if (stageTimingValues.size() < 2) continue;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001013 std::string stageName = stageTimingValues[0];
1014 int32_t time_ms;
1015 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001016 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001017 }
1018 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001019
James Hawkins1bfcaec2017-05-19 14:27:27 -07001020 return timings;
1021}
1022
Tej Singh4eacd382018-01-25 17:59:57 -08001023// Returns the total bootloader boot time from the ro.boot.boottime system property.
1024int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1025 int32_t total_time = 0;
1026 for (const auto& timing : bootloader_timings) {
1027 total_time += timing.second;
1028 }
1029
1030 return total_time;
1031}
1032
James Hawkins1bfcaec2017-05-19 14:27:27 -07001033// Parses and records the set of bootloader stages and associated boot times
1034// from the ro.boot.boottime system property.
1035void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1036 const BootloaderTimingMap& bootloader_timings) {
1037 int32_t total_time = 0;
1038 for (const auto& timing : bootloader_timings) {
1039 total_time += timing.second;
1040 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1041 }
1042
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001043 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001044}
1045
Tej Singh4eacd382018-01-25 17:59:57 -08001046// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001047// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001048std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1049 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001050 int32_t bootloader_time_ms = 0;
1051
1052 for (const auto& timing : bootloader_timings) {
1053 if (timing.first.compare("SW") != 0) {
1054 bootloader_time_ms += timing.second;
1055 }
1056 }
1057
1058 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001059 return bootloader_duration + uptime;
1060}
1061
1062// Records the closest estimation to the absolute device boot time in seconds.
1063// i.e. from power on to boot_complete, including bootloader times.
1064void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1065 std::chrono::milliseconds absolute_total) {
1066 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1067 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1068}
1069
1070// Logs the total boot time and reason to statsd.
1071void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1072 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1073 double time_since_last_boot_sec) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001074 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singh4eacd382018-01-25 17:59:57 -08001075
1076 if (reason.empty()) {
1077 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
1078 end_time.count(), total_duration.count(),
1079 (int64_t)bootloader_duration_ms,
1080 (int64_t)time_since_last_boot_sec * 1000);
1081 return;
1082 }
1083
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001084 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Tej Singh4eacd382018-01-25 17:59:57 -08001085 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1086 system_reason.c_str(), end_time.count(), total_duration.count(),
1087 (int64_t)bootloader_duration_ms,
1088 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001089}
1090
Tej Singhfe3e7622018-02-06 15:57:38 -08001091void SetSystemBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001092 const auto bootloader_boot_reason =
1093 android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001094 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1095 // Record the scrubbed system_boot_reason to the property
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001096 BootReasonAddToHistory(system_boot_reason);
Mark Salyzynadc433d2018-06-05 08:17:35 -07001097 // Shift last_reboot_reason_property to last_last_reboot_reason_property
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001098 auto last_boot_reason = android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzynadc433d2018-06-05 08:17:35 -07001099 if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1100 last_boot_reason = system_boot_reason;
1101 } else {
1102 transformReason(last_boot_reason);
1103 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001104 android::base::SetProperty(last_last_reboot_reason_property, last_boot_reason);
1105 android::base::SetProperty(last_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001106}
1107
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001108// Gets the boot time offset. This is useful when Android is running in a
1109// container, because the boot_clock is not reset when Android reboots.
1110std::chrono::nanoseconds GetBootTimeOffset() {
1111 static const int64_t boottime_offset =
1112 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1113 return std::chrono::nanoseconds(boottime_offset);
1114}
1115
1116// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1117// clock.
1118android::base::boot_clock::duration GetUptime() {
1119 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1120}
1121
James Hawkinsc08e9962016-03-11 14:59:50 -08001122// Records several metrics related to the time it takes to boot the device,
1123// including disambiguating boot time on encrypted or non-encrypted devices.
1124void RecordBootComplete() {
1125 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001126 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001127
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001128 auto uptime_ns = GetUptime();
1129 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001130 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001131 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001132
1133 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1134 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001135 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001136 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001137 }
1138
1139 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001140
James Hawkinsb9cf7712016-04-08 15:32:19 -07001141 // The boot_complete metric has two variants: boot_complete and
1142 // ota_boot_complete. The latter signifies that the device is booting after
1143 // a system update.
1144 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001145 if (boot_complete_prefix.empty()) {
1146 // The system is hosed because the build date property could not be read.
1147 return;
1148 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001149
1150 // post_decrypt_time_elapsed is only logged on encrypted devices.
1151 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1152 // Log the amount of time elapsed until the device is decrypted, which
1153 // includes the variable amount of time the user takes to enter the
1154 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001155 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001156
1157 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001158 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001159 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001160 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001161 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001162 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1163 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001164 }
1165
1166 // Record the total time from device startup to boot complete, regardless of
1167 // encryption state.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001168 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001169
1170 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1171 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1172 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001173
James Hawkins1bfcaec2017-05-19 14:27:27 -07001174 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001175 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001176 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1177
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001178 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001179 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1180 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1181
1182 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1183 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1184
1185 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1186 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001187}
1188
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001189// Records the boot_reason metric by querying the ro.boot.bootreason system
1190// property.
1191void RecordBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001192 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
James Hawkins25f71222017-10-10 16:37:05 -07001193
1194 if (reason.empty()) {
1195 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1196 // (and not corruption anywhere else in the reporting pipeline).
1197 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1198 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1199 } else {
1200 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1201 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1202 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001203
1204 // Log the raw bootloader_boot_reason property value.
1205 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001206 BootEventRecordStore boot_event_store;
1207 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001208
1209 // Log the scrubbed system_boot_reason.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001210 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001211 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1212 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1213
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001214 if (reason == "") {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001215 android::base::SetProperty(bootloader_reboot_reason_property, system_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001216 }
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";
Tej Singhfe3e7622018-02-06 15:57:38 -08001279 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001280 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001281 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001282 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001283 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001284 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001285 { "help", no_argument, NULL, 'h' },
1286 { "log", no_argument, NULL, 'l' },
1287 { "print", no_argument, NULL, 'p' },
1288 { "record", required_argument, NULL, 'r' },
1289 { value_str, required_argument, NULL, 0 },
1290 { system_boot_reason_str, no_argument, NULL, 0 },
1291 { boot_complete_str, no_argument, NULL, 0 },
1292 { boot_reason_str, no_argument, NULL, 0 },
1293 { factory_reset_str, no_argument, NULL, 0 },
1294 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001295 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001296 };
1297
James Hawkinsc6275582016-03-22 10:47:44 -07001298 std::string boot_event;
1299 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001300 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001301 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001302 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001303 // This case handles long options which have no single-character mapping.
1304 case 0: {
1305 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001306 if (option_name == value_str) {
1307 // |optarg| is an external variable set by getopt representing
1308 // the option argument.
1309 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001310 } else if (option_name == system_boot_reason_str) {
1311 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001312 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001313 RecordBootComplete();
1314 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001315 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001316 } else if (option_name == factory_reset_str) {
1317 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001318 } else {
1319 LOG(ERROR) << "Invalid option: " << option_name;
1320 }
1321 break;
1322 }
1323
James Hawkinsabd73e62016-01-19 15:10:38 -08001324 case 'h': {
1325 ShowHelp(argv[0]);
1326 break;
1327 }
1328
1329 case 'l': {
1330 LogBootEvents();
1331 break;
1332 }
1333
1334 case 'p': {
1335 PrintBootEvents();
1336 break;
1337 }
1338
1339 case 'r': {
1340 // |optarg| is an external variable set by getopt representing
1341 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001342 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001343 break;
1344 }
1345
1346 default: {
1347 DCHECK_EQ(opt, '?');
1348
1349 // |optopt| is an external variable set by getopt representing
1350 // the value of the invalid option.
1351 LOG(ERROR) << "Invalid option: " << optopt;
1352 ShowHelp(argv[0]);
1353 return EXIT_FAILURE;
1354 }
1355 }
1356 }
1357
James Hawkinsc6275582016-03-22 10:47:44 -07001358 if (!boot_event.empty()) {
1359 RecordBootEventFromCommandLine(boot_event, value);
1360 }
1361
James Hawkinsabd73e62016-01-19 15:10:38 -08001362 return 0;
1363}