blob: ed955eaad8b0f8f2b5a4c4f7546f24f6a22de551 [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},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800296};
297
298// Converts a string value representing the reason the system booted to an
299// integer representation. This is necessary for logging the boot_reason metric
300// via Tron, which does not accept non-integer buckets in histograms.
301int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800302 auto mapping = kBootReasonMap.find(boot_reason);
303 if (mapping != kBootReasonMap.end()) {
304 return mapping->second;
305 }
306
James Hawkins25f71222017-10-10 16:37:05 -0700307 if (boot_reason.empty()) {
308 return kEmptyBootReason;
309 }
310
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800311 LOG(INFO) << "Unknown boot reason: " << boot_reason;
312 return kUnknownBootReason;
313}
314
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700315// Canonical list of supported primary reboot reasons.
316const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700317 // clang-format off
318 // kernel
319 "watchdog",
320 "kernel_panic",
321 // strong
322 "recovery", // Should not happen from ro.boot.bootreason
323 "bootloader", // Should not happen from ro.boot.bootreason
324 // blunt
325 "cold",
326 "hard",
327 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700328 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700329 "shutdown", // Can not happen from ro.boot.bootreason
330 "reboot", // Default catch-all for anything unknown
331 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700332};
333
334// Returns true if the supplied reason prefix is considered detailed enough.
335bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700336 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700337 if (s == "cold") break;
338 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800339 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700340 return true;
341 }
342 }
343 return false;
344}
345
346// Returns true if the supplied reason prefix is associated with the kernel.
347bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700348 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700349 if (s == "recovery") break;
350 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800351 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700352 return true;
353 }
354 }
355 return false;
356}
357
358// Returns true if the supplied reason prefix is considered known.
359bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700360 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700361 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800362 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700363 return true;
364 }
365 }
366 return false;
367}
368
369// If the reboot reason should be improved, report true if is too blunt.
370bool isBluntRebootReason(const std::string& r) {
371 if (isStrongRebootReason(r)) return false;
372
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700373 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700374
375 size_t pos = 0;
376 while ((pos = r.find(',', pos)) != std::string::npos) {
377 ++pos;
378 std::string next(r.substr(pos));
379 if (next.length() == 0) break;
380 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700381 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
382 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700383 }
384 return true;
385}
386
Mark Salyzyn64610892017-09-18 10:41:14 -0700387bool readPstoreConsole(std::string& console) {
388 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
389 return true;
390 }
391 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
392}
393
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700394// Implement a variant of std::string::rfind that is resilient to errors in
395// the data stream being inspected.
396class pstoreConsole {
397 private:
398 const size_t kBitErrorRate = 8; // number of bits per error
399 const std::string& console;
400
401 // Number of bits that differ between the two arguments l and r.
402 // Returns zero if the values for l and r are identical.
403 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
404
405 // A string comparison function, reports the number of errors discovered
406 // in the match to a maximum of the bitLength / kBitErrorRate, at that
407 // point returning npos to indicate match is too poor.
408 //
409 // Since called in rfind which works backwards, expect cache locality will
410 // help if we check in reverse here as well for performance.
411 //
412 // Assumption: l (from console.c_str() + pos) is long enough to house
413 // _r.length(), checked in rfind caller below.
414 //
415 size_t numError(size_t pos, const std::string& _r) const {
416 const char* l = console.c_str() + pos;
417 const char* r = _r.c_str();
418 size_t n = _r.length();
419 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
420 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
421 size_t count = 0;
422 n = 0;
423 do {
424 // individual character bit error rate > threshold + slop
425 size_t num = numError(*--le, *--re);
426 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
427 // total bit error rate > threshold + slop
428 count += num;
429 ++n;
430 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
431 return std::string::npos;
432 }
433 } while (le != reinterpret_cast<const uint8_t*>(l));
434 return count;
435 }
436
437 public:
438 explicit pstoreConsole(const std::string& console) : console(console) {}
439 // scope of argument must be equal to or greater than scope of pstoreConsole
440 explicit pstoreConsole(const std::string&& console) = delete;
441 explicit pstoreConsole(std::string&& console) = delete;
442
443 // Our implementation of rfind, use exact match first, then resort to fuzzy.
444 size_t rfind(const std::string& needle) const {
445 size_t pos = console.rfind(needle); // exact match?
446 if (pos != std::string::npos) return pos;
447
448 // Check to make sure needle fits in console string.
449 pos = console.length();
450 if (needle.length() > pos) return std::string::npos;
451 pos -= needle.length();
452 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800453 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700454 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800455 if (pos == 0) break;
456 --pos;
457 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700458 return std::string::npos;
459 }
460
461 // Our implementation of find, use only fuzzy match.
462 size_t find(const std::string& needle, size_t start = 0) const {
463 // Check to make sure needle fits in console string.
464 if (needle.length() > console.length()) return std::string::npos;
465 const size_t last_pos = console.length() - needle.length();
466 // fuzzy match to maximum kBitErrorRate
467 for (size_t pos = start; pos <= last_pos; ++pos) {
468 if (numError(pos, needle) != std::string::npos) return pos;
469 }
470 return std::string::npos;
471 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700472
473 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700474};
475
476// If bit error match to needle, correct it.
477// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700478bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700479 bool corrected = false;
480 if (reason.length() < needle.length()) return corrected;
481 const pstoreConsole console(reason);
482 const size_t last_pos = reason.length() - needle.length();
483 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
484 pos = console.find(needle, pos);
485 if (pos == std::string::npos) break;
486
487 // exact match has no malice
488 if (needle == reason.substr(pos, needle.length())) continue;
489
490 corrected = true;
491 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
492 }
493 return corrected;
494}
495
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700496// If bit error match to needle, correct it.
497// Return true if any corrections were discovered and applied.
498// Try again if we can replace underline with spaces.
499bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
500 bool corrected = correctForBitError(reason, needle);
501 std::string _needle(needle);
502 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
503 [](char c) { return (c == '_') ? ' ' : c; });
504 if (needle != _needle) {
505 corrected |= correctForBitError(reason, _needle);
506 }
507 return corrected;
508}
509
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700510// Converts a string value representing the reason the system booted to a
511// string complying with Android system standard reason.
512void transformReason(std::string& reason) {
513 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
514 std::transform(reason.begin(), reason.end(), reason.begin(),
515 [](char c) { return ::isblank(c) ? '_' : c; });
516 std::transform(reason.begin(), reason.end(), reason.begin(),
517 [](char c) { return ::isprint(c) ? c : '?'; });
518}
519
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700520// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
521// kernel_panic,<subreason>.
522//
523// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
524// or unprintable character terminated subreason, pos is supplied just beyond
525// first quote. if quoted false, pull out and correct newline (\n) or
526// unprintable character terminated subreason.
527//
528// Heuristics to find termination is painted into a corner:
529
530// single bit error for quote ' that we can block. It is acceptable for
531// the others 7, g in reason. 2/9 chance will miss the terminating quote,
532// but there is always the terminating newline that usually immediately
533// follows to fortify our chances.
534bool likely_single_quote(char c) {
535 switch (static_cast<uint8_t>(c)) {
536 case '\'': // '\''
537 case '\'' ^ 0x01: // '&'
538 case '\'' ^ 0x02: // '%'
539 case '\'' ^ 0x04: // '#'
540 case '\'' ^ 0x08: // '/'
541 return true;
542 case '\'' ^ 0x10: // '7'
543 break;
544 case '\'' ^ 0x20: // '\a' (unprintable)
545 return true;
546 case '\'' ^ 0x40: // 'g'
547 break;
548 case '\'' ^ 0x80: // 0xA7 (unprintable)
549 return true;
550 }
551 return false;
552}
553
554// ::isprint(c) and likely_space() will prevent us from being called for
555// fundamentally printable entries, except for '\r' and '\b'.
556//
557// Except for * and J, single bit errors for \n, all others are non-
558// printable so easy catch. It is _acceptable_ for *, J or j to exist in
559// the reason string, so 2/9 chance we will miss the terminating newline.
560//
561// NB: J might not be acceptable, except if at the beginning or preceded
562// with a space, '(' or any of the quotes and their BER aliases.
563// NB: * might not be acceptable, except if at the beginning or preceded
564// with a space, another *, or any of the quotes or their BER aliases.
565//
566// To reduce the chances to closer to 1/9 is too complicated for the gain.
567bool likely_newline(char c) {
568 switch (static_cast<uint8_t>(c)) {
569 case '\n': // '\n' (unprintable)
570 case '\n' ^ 0x01: // '\r' (unprintable)
571 case '\n' ^ 0x02: // '\b' (unprintable)
572 case '\n' ^ 0x04: // 0x0E (unprintable)
573 case '\n' ^ 0x08: // 0x02 (unprintable)
574 case '\n' ^ 0x10: // 0x1A (unprintable)
575 return true;
576 case '\n' ^ 0x20: // '*'
577 case '\n' ^ 0x40: // 'J'
578 break;
579 case '\n' ^ 0x80: // 0x8A (unprintable)
580 return true;
581 }
582 return false;
583}
584
585// ::isprint(c) will prevent us from being called for all the printable
586// matches below. If we let unprintables through because of this, they
587// get converted to underscore (_) by the validation phase.
588bool likely_space(char c) {
589 switch (static_cast<uint8_t>(c)) {
590 case ' ': // ' '
591 case ' ' ^ 0x01: // '!'
592 case ' ' ^ 0x02: // '"'
593 case ' ' ^ 0x04: // '$'
594 case ' ' ^ 0x08: // '('
595 case ' ' ^ 0x10: // '0'
596 case ' ' ^ 0x20: // '\0' (unprintable)
597 case ' ' ^ 0x40: // 'P'
598 case ' ' ^ 0x80: // 0xA0 (unprintable)
599 case '\t': // '\t'
600 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
601 case '\t' ^ 0x02: // '\v' (unprintable)
602 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
603 case '\t' ^ 0x08: // 0x01 (unprintable)
604 case '\t' ^ 0x10: // 0x19 (unprintable)
605 case '\t' ^ 0x20: // ')'
606 case '\t' ^ 0x40: // '1'
607 case '\t' ^ 0x80: // 0x89 (unprintable)
608 return true;
609 }
610 return false;
611}
612
613std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700614 static constexpr size_t max_reason_length = 256;
615
616 std::string subReason(content.substr(pos, max_reason_length));
617 // Correct against any known strings that Bit Error Match
618 for (const auto& s : knownReasons) {
619 correctForBitErrorOrUnderline(subReason, s);
620 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700621 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700622 for (const auto& m : kBootReasonMap) {
623 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700624 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700625 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
626 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700627 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700628 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700629 correctForBitErrorOrUnderline(subReason,
630 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
631 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
632 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700633 }
634 }
635 for (pos = 0; pos < subReason.length(); ++pos) {
636 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700637 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
638 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700639 subReason.erase(pos);
640 break;
641 }
642 }
643 transformReason(subReason);
644 return subReason;
645}
646
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700647bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700648 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700649 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
650 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700651 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700652 // Invented for Android to allow daemons that specifically trigger sysrq
653 // to communicate more accurate boot subreasons via last console messages.
654 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
655 auto pos = console.rfind(sysrqSubreason);
656 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700657 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700658 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700659 return true;
660 }
661 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
662 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700663 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700664 return true;
665 }
666 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700667 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700668 return true;
669 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700670
671 std::string panic("Kernel panic - not syncing: ");
672 auto pos = console.rfind(panic);
673 if (pos != std::string::npos) {
674 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
675 {"Out of memory", "oom"},
676 {"out of memory", "oom"},
677 {"Oh boy, that early out of memory", "oom"}, // omg
678 {"BUG!", "bug"},
679 {"hung_task: blocked tasks", "hung"},
680 {"audit: ", "audit"},
681 {"scheduling while atomic", "atomic"},
682 {"Attempted to kill init!", "init"},
683 {"Requested init", "init"},
684 {"No working init", "init"},
685 {"Could not decompress init", "init"},
686 {"RCU Stall", "hung,rcu"},
687 {"stack-protector", "stack"},
688 {"kernel stack overflow", "stack"},
689 {"Corrupt kernel stack", "stack"},
690 {"low stack detected", "stack"},
691 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700692 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
693 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
694 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
695 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700696 };
697
698 ret = "kernel_panic";
699 for (auto& s : panicReasons) {
700 if (console.find(panic + s.first, pos) != std::string::npos) {
701 ret += "," + s.second;
702 return true;
703 }
704 }
705 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
706 if (reason.length() > 3) {
707 ret += "," + reason;
708 }
709 return true;
710 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700711 return false;
712}
713
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700714bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
715 return addKernelPanicSubReason(pstoreConsole(content), ret);
716}
717
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700718const char system_reboot_reason_property[] = "sys.boot.reason";
719const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
Mark Salyzynadc433d2018-06-05 08:17:35 -0700720const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700721constexpr size_t history_reboot_reason_size = 4;
722const char history_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY ".history";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700723const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
724
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700725// Land system_boot_reason into system_reboot_reason_property.
726// Shift system_boot_reason into history_reboot_reason_property.
727void BootReasonAddToHistory(const std::string& system_boot_reason) {
728 if (system_boot_reason.empty()) return;
729 LOG(INFO) << "Canonical boot reason: " << system_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800730 auto old_system_boot_reason = android::base::GetProperty(system_reboot_reason_property, "");
731 if (!android::base::SetProperty(system_reboot_reason_property, system_boot_reason)) {
732 android::base::SetProperty(system_reboot_reason_property,
733 system_boot_reason.substr(0, PROPERTY_VALUE_MAX - 1));
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700734 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800735 auto reason_history =
736 android::base::Split(android::base::GetProperty(history_reboot_reason_property, ""), "\n");
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700737 static auto mark = time(nullptr);
738 auto mark_str = std::string(",") + std::to_string(mark);
739 auto marked_system_boot_reason = system_boot_reason + mark_str;
740 if (!reason_history.empty()) {
741 // delete any entries that we just wrote in a previous
742 // call and leveraging duplicate line handling
743 auto last = old_system_boot_reason + mark_str;
744 // trim the list to (history_reboot_reason_size - 1)
745 ssize_t max = history_reboot_reason_size;
746 for (auto it = reason_history.begin(); it != reason_history.end();) {
747 if (it->empty() || (last == *it) || (marked_system_boot_reason == *it) || (--max <= 0)) {
748 it = reason_history.erase(it);
749 } else {
750 last = *it;
751 ++it;
752 }
753 }
754 }
755 // insert at the front, concatenating mark (<epoch time>) detail to the value.
756 reason_history.insert(reason_history.begin(), marked_system_boot_reason);
757 // If the property string is too long ( > PROPERTY_VALUE_MAX)
758 // we get an error, so trim out last entry and try again.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800759 while (!android::base::SetProperty(history_reboot_reason_property,
760 android::base::Join(reason_history, '\n'))) {
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700761 auto it = std::prev(reason_history.end());
762 if (it == reason_history.end()) break;
763 reason_history.erase(it);
764 }
765}
766
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700767// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
768std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800769 auto ret = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700770 std::string reason(boot_reason);
771 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
772 if (reason == ret) ret = "";
773
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700774 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700775
776 // Is the current system boot reason sys.boot.reason valid?
777 if (!isKnownRebootReason(ret)) ret = "";
778
779 if (ret == "") {
780 // Is the bootloader boot reason ro.boot.bootreason known?
781 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700782 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700783 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700784 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700785 if (r == s) {
786 if (isBluntRebootReason(s)) {
787 blunt = s;
788 } else {
789 ret = s;
790 break;
791 }
792 }
793 }
794 if (ret == "") ret = blunt;
795 if (ret != "") break;
796 }
797 }
798
799 if (ret == "") {
800 // A series of checks to take some officially unsupported reasons
801 // reported by the bootloader and find some logical and canonical
802 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700803 // to behave and follow our CTS standards.
804 //
805 // first member is the output
806 // second member is an unanchored regex for an alias
807 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700808 // If output has a prefix of <bang> '!', we do not use it as a
809 // match needle (and drop the <bang> prefix when landing in output),
810 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700811 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700812 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700813 {"watchdog", "wdog"},
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700814 {"cold,powerkey", "powerkey|power_key|PowerKey"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700815 {"kernel_panic", "panic"},
816 {"shutdown,thermal", "thermal"},
817 {"warm,s3_wakeup", "s3_wakeup"},
818 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700819 {"cold,charger", "usb"},
820 {"cold,rtc", "rtc"},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700821 {"cold,rtc,2sec", "2sec_reboot"},
822 {"!warm", "wdt_by_pass_pwk"}, // change flavour of blunt
823 {"!reboot", "^wdt$"}, // change flavour of blunt
824 {"reboot,tool", "tool_by_pass_pwk"},
Mark Salyzyn88d1b4a2018-06-07 09:39:24 -0700825 {"!reboot,longkey", "reboot_longkey"},
826 {"!reboot,longkey", "kpdpwr"},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700827 {"!reboot,undervoltage", "uvlo"},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700828 {"!reboot,powerloss", "smpl"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700829 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700830 };
831
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700832 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700833 size_t firstHasNot = s.first[0] == '!';
834 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700835 ret = s.first;
836 break;
837 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700838 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700839 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700840 break;
841 }
842 }
843 }
844
845 // If watchdog is the reason, see if there is a security angle?
846 if (ret == "watchdog") {
847 if (reason.find("sec") != std::string::npos) {
848 ret += ",security";
849 }
850 }
851
Mark Salyzyn64610892017-09-18 10:41:14 -0700852 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700853 // Check to see if last klog has some refinement hints.
854 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700855 if (readPstoreConsole(content)) {
856 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700857 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700858 } else if (isBluntRebootReason(ret)) {
859 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700860
Mark Salyzyn64610892017-09-18 10:41:14 -0700861 // Check to see if last klog has some refinement hints.
862 std::string content;
863 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700864 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700865 // The toybox reboot command used directly (unlikely)? But also
866 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700867 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700868 ret = "shutdown"; // Still too blunt, but more accurate.
869 // ToDo: init should record the shutdown reason to kernel messages ala:
870 // init: shutdown system with command 'last_reboot_reason'
871 // so that if pstore has persistence we can get some details
872 // that could be missing in last_reboot_reason_property.
873 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700874
Mark Salyzyn64610892017-09-18 10:41:14 -0700875 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700876 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700877 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700878 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700879 if (subReason != "") { // Will not land "reboot" as that is too blunt.
880 if (isKernelRebootReason(subReason)) {
881 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700882 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700883 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700884 } else {
885 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700886 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700887 }
Mark Salyzyn15199252018-03-16 09:26:05 -0700888 // Some bootloaders shutdown results record in last kernel message.
889 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
890 ret = "shutdown";
891 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700892 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700893
Mark Salyzyn64610892017-09-18 10:41:14 -0700894 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700895 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700896 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700897 ((console.rfind("Power held for ") != std::string::npos) ||
898 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700899 ret = "cold";
900 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700901 }
902
Elliott Hughes50a24eb2018-06-14 10:59:09 -0700903 // TODO: use the HAL to get battery level (http://b/77725702).
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700904
905 // Is there a controlled shutdown hint in last_reboot_reason_property?
906 if (isBluntRebootReason(ret)) {
907 // Content buffer no longer will have console data. Beware if more
908 // checks added below, that depend on parsing console content.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800909 content = android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700910 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700911
Mark Salyzyn62909822017-10-09 09:27:16 -0700912 // Anything in last is better than 'super-blunt' reboot or shutdown.
913 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
914 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700915 }
916 }
917
918 // Other System Health HAL reasons?
919
920 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
921 // possibly offer hardware-specific clues from the PMIC.
922 }
923
924 // If unknown left over from above, make it "reboot,<boot_reason>"
925 if (ret == "") {
926 ret = "reboot";
927 if (android::base::StartsWith(reason, "reboot")) {
928 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700929 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700930 reason = reason.substr(1);
931 }
932 }
933 if (reason != "") {
934 ret += ",";
935 ret += reason;
936 }
937 }
938
939 LOG(INFO) << "Canonical boot reason: " << ret;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700940 return ret;
941}
942
James Hawkinsb9cf7712016-04-08 15:32:19 -0700943// Returns the appropriate metric key prefix for the boot_complete metric such
944// that boot metrics after a system update are labeled as ota_boot_complete;
945// otherwise, they are labeled as boot_complete. This method encapsulates the
946// bookkeeping required to track when a system update has occurred by storing
947// the UTC timestamp of the system build date and comparing against the current
948// system build date.
949std::string CalculateBootCompletePrefix() {
950 static const std::string kBuildDateKey = "build_date";
951 std::string boot_complete_prefix = "boot_complete";
952
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800953 auto build_date_str = android::base::GetProperty("ro.build.date.utc", "");
James Hawkins4dded612016-07-28 11:50:23 -0700954 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700955 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700956 return std::string();
957 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700958
959 BootEventRecordStore boot_event_store;
960 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700961 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
962 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
963 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700964 BootReasonAddToHistory("reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700965 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700966 boot_complete_prefix = "ota_" + boot_complete_prefix;
967 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700968 BootReasonAddToHistory("reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700969 }
970
971 return boot_complete_prefix;
972}
973
James Hawkinsef0a0902017-01-06 14:38:23 -0800974// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700975void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800976 auto value = android::base::GetProperty(property, "");
James Hawkinsef0a0902017-01-06 14:38:23 -0800977
James Hawkins27c05222017-01-26 11:55:44 -0800978 int32_t time_in_ms;
979 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800980 boot_event_store->AddBootEventWithValue(property, time_in_ms);
981 }
982}
983
James Hawkins1bfcaec2017-05-19 14:27:27 -0700984// A map from bootloader timing stage to the time that stage took during boot.
985typedef std::map<std::string, int32_t> BootloaderTimingMap;
986
987// Returns a mapping from bootloader stage names to the time those stages
988// took to boot.
989const BootloaderTimingMap GetBootLoaderTimings() {
990 BootloaderTimingMap timings;
991
992 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
993 // where timeN is in milliseconds.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800994 auto value = android::base::GetProperty("ro.boot.boottime", "");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800995 if (value.empty()) {
996 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700997 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800998 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800999
1000 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001001 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001002 // |stageTiming| is of the form 'stage:time'.
1003 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001004 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001005
Mark Salyzyn7c721162019-02-08 10:41:15 -08001006 if (stageTimingValues.size() < 2) continue;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001007 std::string stageName = stageTimingValues[0];
1008 int32_t time_ms;
1009 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001010 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001011 }
1012 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001013
James Hawkins1bfcaec2017-05-19 14:27:27 -07001014 return timings;
1015}
1016
Tej Singh4eacd382018-01-25 17:59:57 -08001017// Returns the total bootloader boot time from the ro.boot.boottime system property.
1018int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1019 int32_t total_time = 0;
1020 for (const auto& timing : bootloader_timings) {
1021 total_time += timing.second;
1022 }
1023
1024 return total_time;
1025}
1026
James Hawkins1bfcaec2017-05-19 14:27:27 -07001027// Parses and records the set of bootloader stages and associated boot times
1028// from the ro.boot.boottime system property.
1029void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1030 const BootloaderTimingMap& bootloader_timings) {
1031 int32_t total_time = 0;
1032 for (const auto& timing : bootloader_timings) {
1033 total_time += timing.second;
1034 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1035 }
1036
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001037 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001038}
1039
Tej Singh4eacd382018-01-25 17:59:57 -08001040// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001041// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001042std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1043 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001044 int32_t bootloader_time_ms = 0;
1045
1046 for (const auto& timing : bootloader_timings) {
1047 if (timing.first.compare("SW") != 0) {
1048 bootloader_time_ms += timing.second;
1049 }
1050 }
1051
1052 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001053 return bootloader_duration + uptime;
1054}
1055
1056// Records the closest estimation to the absolute device boot time in seconds.
1057// i.e. from power on to boot_complete, including bootloader times.
1058void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1059 std::chrono::milliseconds absolute_total) {
1060 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1061 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1062}
1063
1064// Logs the total boot time and reason to statsd.
1065void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1066 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1067 double time_since_last_boot_sec) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001068 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singh4eacd382018-01-25 17:59:57 -08001069
1070 if (reason.empty()) {
1071 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
1072 end_time.count(), total_duration.count(),
1073 (int64_t)bootloader_duration_ms,
1074 (int64_t)time_since_last_boot_sec * 1000);
1075 return;
1076 }
1077
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001078 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Tej Singh4eacd382018-01-25 17:59:57 -08001079 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1080 system_reason.c_str(), end_time.count(), total_duration.count(),
1081 (int64_t)bootloader_duration_ms,
1082 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001083}
1084
Tej Singhfe3e7622018-02-06 15:57:38 -08001085void SetSystemBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001086 const auto bootloader_boot_reason =
1087 android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001088 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1089 // Record the scrubbed system_boot_reason to the property
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001090 BootReasonAddToHistory(system_boot_reason);
Mark Salyzynadc433d2018-06-05 08:17:35 -07001091 // Shift last_reboot_reason_property to last_last_reboot_reason_property
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001092 auto last_boot_reason = android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzynadc433d2018-06-05 08:17:35 -07001093 if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1094 last_boot_reason = system_boot_reason;
1095 } else {
1096 transformReason(last_boot_reason);
1097 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001098 android::base::SetProperty(last_last_reboot_reason_property, last_boot_reason);
1099 android::base::SetProperty(last_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001100}
1101
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001102// Gets the boot time offset. This is useful when Android is running in a
1103// container, because the boot_clock is not reset when Android reboots.
1104std::chrono::nanoseconds GetBootTimeOffset() {
1105 static const int64_t boottime_offset =
1106 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1107 return std::chrono::nanoseconds(boottime_offset);
1108}
1109
1110// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1111// clock.
1112android::base::boot_clock::duration GetUptime() {
1113 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1114}
1115
James Hawkinsc08e9962016-03-11 14:59:50 -08001116// Records several metrics related to the time it takes to boot the device,
1117// including disambiguating boot time on encrypted or non-encrypted devices.
1118void RecordBootComplete() {
1119 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001120 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001121
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001122 auto uptime_ns = GetUptime();
1123 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001124 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001125 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001126
1127 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1128 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001129 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001130 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001131 }
1132
1133 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001134
James Hawkinsb9cf7712016-04-08 15:32:19 -07001135 // The boot_complete metric has two variants: boot_complete and
1136 // ota_boot_complete. The latter signifies that the device is booting after
1137 // a system update.
1138 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001139 if (boot_complete_prefix.empty()) {
1140 // The system is hosed because the build date property could not be read.
1141 return;
1142 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001143
1144 // post_decrypt_time_elapsed is only logged on encrypted devices.
1145 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1146 // Log the amount of time elapsed until the device is decrypted, which
1147 // includes the variable amount of time the user takes to enter the
1148 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001149 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001150
1151 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001152 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001153 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001154 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001155 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001156 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1157 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001158 }
1159
1160 // Record the total time from device startup to boot complete, regardless of
1161 // encryption state.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001162 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001163
1164 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1165 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1166 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001167
James Hawkins1bfcaec2017-05-19 14:27:27 -07001168 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001169 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001170 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1171
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001172 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001173 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1174 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1175
1176 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1177 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1178
1179 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1180 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001181}
1182
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001183// Records the boot_reason metric by querying the ro.boot.bootreason system
1184// property.
1185void RecordBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001186 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
James Hawkins25f71222017-10-10 16:37:05 -07001187
1188 if (reason.empty()) {
1189 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1190 // (and not corruption anywhere else in the reporting pipeline).
1191 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1192 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1193 } else {
1194 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1195 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1196 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001197
1198 // Log the raw bootloader_boot_reason property value.
1199 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001200 BootEventRecordStore boot_event_store;
1201 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001202
1203 // Log the scrubbed system_boot_reason.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001204 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001205 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1206 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1207
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001208 if (reason == "") {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001209 android::base::SetProperty(bootloader_reboot_reason_property, system_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001210 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001211}
1212
James Hawkins500d7152016-02-16 15:05:54 -08001213// Records two metrics related to the user resetting a device: the time at
1214// which the device is reset, and the time since the user last reset the
1215// device. The former is only set once per-factory reset.
1216void RecordFactoryReset() {
1217 BootEventRecordStore boot_event_store;
1218 BootEventRecordStore::BootEventRecord record;
1219
1220 time_t current_time_utc = time(nullptr);
1221
James Hawkins0660b302016-03-08 16:18:15 -08001222 if (current_time_utc < 0) {
1223 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001224 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1225 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001226
James Hawkins9aec9262017-01-31 11:42:24 -08001227 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001228 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001229 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1230 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001231 return;
1232 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001233 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001234
James Hawkins9aec9262017-01-31 11:42:24 -08001235 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001236 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001237 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001238 }
1239
James Hawkins500d7152016-02-16 15:05:54 -08001240 // The factory_reset boot event does not exist after the device is reset, so
1241 // use this signal to mark the time of the factory reset.
1242 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1243 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001244
1245 // Don't log the time_since_factory_reset until some time has elapsed.
1246 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001247 return;
1248 }
1249
1250 // Calculate and record the difference in time between now and the
1251 // factory_reset time.
1252 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001253 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001254
James Hawkins9aec9262017-01-31 11:42:24 -08001255 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001256 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001257 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001258
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001259 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1260 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001261}
1262
James Hawkinsabd73e62016-01-19 15:10:38 -08001263} // namespace
1264
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001265int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001266 android::base::InitLogging(argv);
1267
1268 const std::string cmd_line = GetCommandLine(argc, argv);
1269 LOG(INFO) << "Service started: " << cmd_line;
1270
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001271 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001272 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001273 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001274 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001275 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001276 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001277 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001278 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001279 { "help", no_argument, NULL, 'h' },
1280 { "log", no_argument, NULL, 'l' },
1281 { "print", no_argument, NULL, 'p' },
1282 { "record", required_argument, NULL, 'r' },
1283 { value_str, required_argument, NULL, 0 },
1284 { system_boot_reason_str, no_argument, NULL, 0 },
1285 { boot_complete_str, no_argument, NULL, 0 },
1286 { boot_reason_str, no_argument, NULL, 0 },
1287 { factory_reset_str, no_argument, NULL, 0 },
1288 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001289 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001290 };
1291
James Hawkinsc6275582016-03-22 10:47:44 -07001292 std::string boot_event;
1293 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001294 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001295 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001296 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001297 // This case handles long options which have no single-character mapping.
1298 case 0: {
1299 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001300 if (option_name == value_str) {
1301 // |optarg| is an external variable set by getopt representing
1302 // the option argument.
1303 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001304 } else if (option_name == system_boot_reason_str) {
1305 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001306 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001307 RecordBootComplete();
1308 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001309 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001310 } else if (option_name == factory_reset_str) {
1311 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001312 } else {
1313 LOG(ERROR) << "Invalid option: " << option_name;
1314 }
1315 break;
1316 }
1317
James Hawkinsabd73e62016-01-19 15:10:38 -08001318 case 'h': {
1319 ShowHelp(argv[0]);
1320 break;
1321 }
1322
1323 case 'l': {
1324 LogBootEvents();
1325 break;
1326 }
1327
1328 case 'p': {
1329 PrintBootEvents();
1330 break;
1331 }
1332
1333 case 'r': {
1334 // |optarg| is an external variable set by getopt representing
1335 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001336 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001337 break;
1338 }
1339
1340 default: {
1341 DCHECK_EQ(opt, '?');
1342
1343 // |optopt| is an external variable set by getopt representing
1344 // the value of the invalid option.
1345 LOG(ERROR) << "Invalid option: " << optopt;
1346 ShowHelp(argv[0]);
1347 return EXIT_FAILURE;
1348 }
1349 }
1350 }
1351
James Hawkinsc6275582016-03-22 10:47:44 -07001352 if (!boot_event.empty()) {
1353 RecordBootEventFromCommandLine(boot_event, value);
1354 }
1355
James Hawkinsabd73e62016-01-19 15:10:38 -08001356 return 0;
1357}