blob: 1981ad16c1f1dc41fd5d82f47238cf68971e5fb9 [file] [log] [blame]
James Hawkinsabd73e62016-01-19 15:10:38 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// The bootstat command provides options to persist boot events with the current
18// timestamp, dump the persisted events, and log all events to EventLog to be
19// uploaded to Android log storage via Tron.
20
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080021#include <getopt.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070022#include <sys/klog.h>
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070023#include <unistd.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070024
James Hawkinse78ea772017-03-24 11:43:02 -070025#include <chrono>
James Hawkins0660b302016-03-08 16:18:15 -080026#include <cmath>
James Hawkinsabd73e62016-01-19 15:10:38 -080027#include <cstddef>
28#include <cstdio>
James Hawkins500d7152016-02-16 15:05:54 -080029#include <ctime>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080030#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080031#include <memory>
Mark Salyzyn25900dd2018-03-16 09:05:59 -070032#include <regex>
James Hawkinsabd73e62016-01-19 15:10:38 -080033#include <string>
Mark Salyzyn853bb802018-03-16 08:44:56 -070034#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080035#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070036
James Hawkinse78ea772017-03-24 11:43:02 -070037#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070038#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080039#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070040#include <android-base/parseint.h>
Luis Hector Chavez583d34c2018-04-12 15:25:15 -070041#include <android-base/properties.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080042#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070043#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070044#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080045#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070046#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080047#include <metricslogger/metrics_logger.h>
Tej Singh4eacd382018-01-25 17:59:57 -080048#include <statslog.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070049
James Hawkinsabd73e62016-01-19 15:10:38 -080050#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080051
52namespace {
53
James Hawkinsabd73e62016-01-19 15:10:38 -080054// Scans the boot event record store for record files and logs each boot event
55// via EventLog.
56void LogBootEvents() {
57 BootEventRecordStore boot_event_store;
58
59 auto events = boot_event_store.GetAllBootEvents();
60 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080061 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080062 }
63}
64
James Hawkinsc6275582016-03-22 10:47:44 -070065// Records the named boot |event| to the record store. If |value| is non-empty
66// and is a proper string representation of an integer value, the converted
67// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070068void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070069 BootEventRecordStore boot_event_store;
70 if (!value_str.empty()) {
71 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070072 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070073 boot_event_store.AddBootEventWithValue(event, value);
74 }
James Hawkinsc6275582016-03-22 10:47:44 -070075 } else {
76 boot_event_store.AddBootEvent(event);
77 }
78}
79
James Hawkinsabd73e62016-01-19 15:10:38 -080080void PrintBootEvents() {
81 printf("Boot events:\n");
82 printf("------------\n");
83
84 BootEventRecordStore boot_event_store;
85 auto events = boot_event_store.GetAllBootEvents();
86 for (auto i = events.cbegin(); i != events.cend(); ++i) {
87 printf("%s\t%d\n", i->first.c_str(), i->second);
88 }
89}
90
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070091void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080092 fprintf(stderr, "Usage: %s [options]\n", cmd);
93 fprintf(stderr,
94 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080095 " -h, --help Show this help\n"
96 " -l, --log Log all metrics to logstorage\n"
97 " -p, --print Dump the boot event records to the console\n"
98 " -r, --record Record the timestamp of a named boot event\n"
99 " --value Optional value to associate with the boot event\n"
100 " --record_boot_complete Record metrics related to the time for the device boot\n"
101 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -0800102 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800103}
104
105// Constructs a readable, printable string from the givencommand line
106// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700107std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800108 std::string cmd;
109 for (int i = 0; i < argc; ++i) {
110 cmd += argv[i];
111 cmd += " ";
112 }
113
114 return cmd;
115}
116
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800117// Convenience wrapper over the property API that returns an
118// std::string.
119std::string GetProperty(const char* key) {
120 std::vector<char> temp(PROPERTY_VALUE_MAX);
121 const int len = property_get(key, &temp[0], nullptr);
122 if (len < 0) {
123 return "";
124 }
125 return std::string(&temp[0], len);
126}
127
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700128void SetProperty(const char* key, const std::string& val) {
129 property_set(key, val.c_str());
130}
131
132void SetProperty(const char* key, const char* val) {
133 property_set(key, val);
134}
135
James Hawkins25f71222017-10-10 16:37:05 -0700136constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800137constexpr int32_t kUnknownBootReason = 1;
138
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800139// A mapping from boot reason string, as read from the ro.boot.bootreason
140// system property, to a unique integer ID. Viewers of log data dashboards for
141// the boot_reason metric may refer to this mapping to discern the histogram
142// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800143const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700144 {"empty", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700145 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700146 {"normal", 2},
147 {"recovery", 3},
148 {"reboot", 4},
149 {"PowerKey", 5},
150 {"hard_reset", 6},
151 {"kernel_panic", 7},
152 {"rpm_err", 8},
153 {"hw_reset", 9},
154 {"tz_err", 10},
155 {"adsp_err", 11},
156 {"modem_err", 12},
157 {"mba_err", 13},
158 {"Watchdog", 14},
159 {"Panic", 15},
160 {"power_key", 16},
161 {"power_on", 17},
162 {"Reboot", 18},
163 {"rtc", 19},
164 {"edl", 20},
165 {"oem_pon1", 21},
166 {"oem_powerkey", 22},
167 {"oem_unknown_reset", 23},
168 {"srto: HWWDT reset SC", 24},
169 {"srto: HWWDT reset platform", 25},
170 {"srto: bootloader", 26},
171 {"srto: kernel panic", 27},
172 {"srto: kernel watchdog reset", 28},
173 {"srto: normal", 29},
174 {"srto: reboot", 30},
175 {"srto: reboot-bootloader", 31},
176 {"srto: security watchdog reset", 32},
177 {"srto: wakesrc", 33},
178 {"srto: watchdog", 34},
179 {"srto:1-1", 35},
180 {"srto:omap_hsmm", 36},
181 {"srto:phy0", 37},
182 {"srto:rtc0", 38},
183 {"srto:touchpad", 39},
184 {"watchdog", 40},
185 {"watchdogr", 41},
186 {"wdog_bark", 42},
187 {"wdog_bite", 43},
188 {"wdog_reset", 44},
189 {"shutdown,", 45}, // Trailing comma is intentional.
190 {"shutdown,userrequested", 46},
191 {"reboot,bootloader", 47},
192 {"reboot,cold", 48},
193 {"reboot,recovery", 49},
194 {"thermal_shutdown", 50},
195 {"s3_wakeup", 51},
196 {"kernel_panic,sysrq", 52},
197 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700198 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700199 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700200 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700201 {"bootloader", 55},
202 {"cold", 56},
203 {"hard", 57},
204 {"warm", 58},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700205 // {"recovery", 59}, // Duplicate of enum 3 above. Immediate reuse possible.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700206 {"thermal-shutdown", 60},
207 {"shutdown,thermal", 61},
208 {"shutdown,battery", 62},
209 {"reboot,ota", 63},
210 {"reboot,factory_reset", 64},
211 {"reboot,", 65},
212 {"reboot,shell", 66},
213 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700214 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700215 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700216 {"cold,powerkey", 70},
217 {"warm,s3_wakeup", 71},
218 {"hard,hw_reset", 72},
219 {"shutdown,suspend", 73}, // Suspend to RAM
220 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700221 {"power_on_key", 75},
222 {"reboot_by_key", 76},
223 {"wdt_by_pass_pwk", 77},
224 {"reboot_longkey", 78},
225 {"powerkey", 79},
226 {"usb", 80},
227 {"wdt", 81},
228 {"tool_by_pass_pwk", 82},
229 {"2sec_reboot", 83},
230 {"reboot,by_key", 84},
231 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700232 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700233 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700234 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
235 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn2b820532018-03-16 08:53:34 -0700236 // {"usb", 90}, // Duplicate of enum 80 above. Immediate reuse possible.
James Hawkins74b17582017-11-20 14:13:41 -0800237 {"charge", 91},
238 {"oem_tz_crash", 92},
239 {"uvlo", 93},
240 {"oem_ps_hold", 94},
241 {"abnormal_reset", 95},
242 {"oemerr_unknown", 96},
243 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800244 {"watchdog_apps_bite", 98},
245 {"xpu_err", 99},
246 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800247 {"watchdog_rpm", 101},
248 {"watchdog_nonsec", 102},
249 {"watchdog_apps_bark", 103},
250 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800251 {"reboot_smpl", 105},
252 {"watchdog_sdi_apps_reset", 106},
253 {"smpl", 107},
254 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800255 {"reboot_normal", 109},
256 {"oem_lpass_cfg", 110},
257 {"oem_xpu_ns_error", 111},
258 {"power_key_press", 112},
259 {"hardware_reset", 113},
260 {"reboot_by_powerkey", 114},
261 {"reboot_verity", 115},
262 {"oem_rpm_undef_error", 116},
263 {"oem_crash_on_the_lk", 117},
264 {"oem_rpm_reset", 118},
265 {"oem_lpass_cfg", 119},
266 {"oem_xpu_ns_error", 120},
267 {"factory_cable", 121},
268 {"oem_ar6320_failed_to_powerup", 122},
269 {"watchdog_rpm_bite", 123},
270 {"power_on_cable", 124},
271 {"reboot_unknown", 125},
272 {"wireless_charger", 126},
273 {"0x776655ff", 127},
274 {"oem_thermal_bite_reset", 128},
275 {"charger", 129},
276 {"pon1", 130},
277 {"unknown", 131},
278 {"reboot_rtc", 132},
279 {"cold_boot", 133},
280 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800281 {"power-on", 135},
282 {"oem_adsp_resetting_the_soc", 136},
283 {"kpdpwr", 137},
284 {"oem_modem_timeout_waiting", 138},
285 {"usb_chg", 139},
286 {"warm_reset_0x02", 140},
287 {"warm_reset_0x80", 141},
288 {"pon_reason_0xb0", 142},
289 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800290 {"reboot_recovery_mode", 144},
291 {"oem_sdi_err_fatal", 145},
292 {"pmic_watchdog", 146},
293 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700294 {"cold,charger", 148},
295 {"cold,rtc", 149},
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700296 {"cold,rtc,2sec", 150},
297 {"reboot,tool", 151},
298 {"reboot,wdt", 152},
299 {"reboot,unknown", 153},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700300 {"kernel_panic,audit", 154},
301 {"kernel_panic,atomic", 155},
302 {"kernel_panic,hung", 156},
303 {"kernel_panic,hung,rcu", 157},
304 {"kernel_panic,init", 158},
305 {"kernel_panic,oom", 159},
306 {"kernel_panic,stack", 160},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800307};
308
309// Converts a string value representing the reason the system booted to an
310// integer representation. This is necessary for logging the boot_reason metric
311// via Tron, which does not accept non-integer buckets in histograms.
312int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800313 auto mapping = kBootReasonMap.find(boot_reason);
314 if (mapping != kBootReasonMap.end()) {
315 return mapping->second;
316 }
317
James Hawkins25f71222017-10-10 16:37:05 -0700318 if (boot_reason.empty()) {
319 return kEmptyBootReason;
320 }
321
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800322 LOG(INFO) << "Unknown boot reason: " << boot_reason;
323 return kUnknownBootReason;
324}
325
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700326// Canonical list of supported primary reboot reasons.
327const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700328 // clang-format off
329 // kernel
330 "watchdog",
331 "kernel_panic",
332 // strong
333 "recovery", // Should not happen from ro.boot.bootreason
334 "bootloader", // Should not happen from ro.boot.bootreason
335 // blunt
336 "cold",
337 "hard",
338 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700339 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700340 "shutdown", // Can not happen from ro.boot.bootreason
341 "reboot", // Default catch-all for anything unknown
342 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700343};
344
345// Returns true if the supplied reason prefix is considered detailed enough.
346bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700347 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700348 if (s == "cold") break;
349 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800350 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700351 return true;
352 }
353 }
354 return false;
355}
356
357// Returns true if the supplied reason prefix is associated with the kernel.
358bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700359 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700360 if (s == "recovery") break;
361 // 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// Returns true if the supplied reason prefix is considered known.
370bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700371 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700372 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800373 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700374 return true;
375 }
376 }
377 return false;
378}
379
380// If the reboot reason should be improved, report true if is too blunt.
381bool isBluntRebootReason(const std::string& r) {
382 if (isStrongRebootReason(r)) return false;
383
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700384 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700385
386 size_t pos = 0;
387 while ((pos = r.find(',', pos)) != std::string::npos) {
388 ++pos;
389 std::string next(r.substr(pos));
390 if (next.length() == 0) break;
391 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700392 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
393 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700394 }
395 return true;
396}
397
Mark Salyzyn64610892017-09-18 10:41:14 -0700398bool readPstoreConsole(std::string& console) {
399 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
400 return true;
401 }
402 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
403}
404
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700405// Implement a variant of std::string::rfind that is resilient to errors in
406// the data stream being inspected.
407class pstoreConsole {
408 private:
409 const size_t kBitErrorRate = 8; // number of bits per error
410 const std::string& console;
411
412 // Number of bits that differ between the two arguments l and r.
413 // Returns zero if the values for l and r are identical.
414 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
415
416 // A string comparison function, reports the number of errors discovered
417 // in the match to a maximum of the bitLength / kBitErrorRate, at that
418 // point returning npos to indicate match is too poor.
419 //
420 // Since called in rfind which works backwards, expect cache locality will
421 // help if we check in reverse here as well for performance.
422 //
423 // Assumption: l (from console.c_str() + pos) is long enough to house
424 // _r.length(), checked in rfind caller below.
425 //
426 size_t numError(size_t pos, const std::string& _r) const {
427 const char* l = console.c_str() + pos;
428 const char* r = _r.c_str();
429 size_t n = _r.length();
430 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
431 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
432 size_t count = 0;
433 n = 0;
434 do {
435 // individual character bit error rate > threshold + slop
436 size_t num = numError(*--le, *--re);
437 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
438 // total bit error rate > threshold + slop
439 count += num;
440 ++n;
441 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
442 return std::string::npos;
443 }
444 } while (le != reinterpret_cast<const uint8_t*>(l));
445 return count;
446 }
447
448 public:
449 explicit pstoreConsole(const std::string& console) : console(console) {}
450 // scope of argument must be equal to or greater than scope of pstoreConsole
451 explicit pstoreConsole(const std::string&& console) = delete;
452 explicit pstoreConsole(std::string&& console) = delete;
453
454 // Our implementation of rfind, use exact match first, then resort to fuzzy.
455 size_t rfind(const std::string& needle) const {
456 size_t pos = console.rfind(needle); // exact match?
457 if (pos != std::string::npos) return pos;
458
459 // Check to make sure needle fits in console string.
460 pos = console.length();
461 if (needle.length() > pos) return std::string::npos;
462 pos -= needle.length();
463 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800464 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700465 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800466 if (pos == 0) break;
467 --pos;
468 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700469 return std::string::npos;
470 }
471
472 // Our implementation of find, use only fuzzy match.
473 size_t find(const std::string& needle, size_t start = 0) const {
474 // Check to make sure needle fits in console string.
475 if (needle.length() > console.length()) return std::string::npos;
476 const size_t last_pos = console.length() - needle.length();
477 // fuzzy match to maximum kBitErrorRate
478 for (size_t pos = start; pos <= last_pos; ++pos) {
479 if (numError(pos, needle) != std::string::npos) return pos;
480 }
481 return std::string::npos;
482 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700483
484 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700485};
486
487// If bit error match to needle, correct it.
488// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700489bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700490 bool corrected = false;
491 if (reason.length() < needle.length()) return corrected;
492 const pstoreConsole console(reason);
493 const size_t last_pos = reason.length() - needle.length();
494 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
495 pos = console.find(needle, pos);
496 if (pos == std::string::npos) break;
497
498 // exact match has no malice
499 if (needle == reason.substr(pos, needle.length())) continue;
500
501 corrected = true;
502 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
503 }
504 return corrected;
505}
506
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700507// If bit error match to needle, correct it.
508// Return true if any corrections were discovered and applied.
509// Try again if we can replace underline with spaces.
510bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
511 bool corrected = correctForBitError(reason, needle);
512 std::string _needle(needle);
513 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
514 [](char c) { return (c == '_') ? ' ' : c; });
515 if (needle != _needle) {
516 corrected |= correctForBitError(reason, _needle);
517 }
518 return corrected;
519}
520
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700521// Converts a string value representing the reason the system booted to a
522// string complying with Android system standard reason.
523void transformReason(std::string& reason) {
524 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
525 std::transform(reason.begin(), reason.end(), reason.begin(),
526 [](char c) { return ::isblank(c) ? '_' : c; });
527 std::transform(reason.begin(), reason.end(), reason.begin(),
528 [](char c) { return ::isprint(c) ? c : '?'; });
529}
530
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700531// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
532// kernel_panic,<subreason>.
533//
534// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
535// or unprintable character terminated subreason, pos is supplied just beyond
536// first quote. if quoted false, pull out and correct newline (\n) or
537// unprintable character terminated subreason.
538//
539// Heuristics to find termination is painted into a corner:
540
541// single bit error for quote ' that we can block. It is acceptable for
542// the others 7, g in reason. 2/9 chance will miss the terminating quote,
543// but there is always the terminating newline that usually immediately
544// follows to fortify our chances.
545bool likely_single_quote(char c) {
546 switch (static_cast<uint8_t>(c)) {
547 case '\'': // '\''
548 case '\'' ^ 0x01: // '&'
549 case '\'' ^ 0x02: // '%'
550 case '\'' ^ 0x04: // '#'
551 case '\'' ^ 0x08: // '/'
552 return true;
553 case '\'' ^ 0x10: // '7'
554 break;
555 case '\'' ^ 0x20: // '\a' (unprintable)
556 return true;
557 case '\'' ^ 0x40: // 'g'
558 break;
559 case '\'' ^ 0x80: // 0xA7 (unprintable)
560 return true;
561 }
562 return false;
563}
564
565// ::isprint(c) and likely_space() will prevent us from being called for
566// fundamentally printable entries, except for '\r' and '\b'.
567//
568// Except for * and J, single bit errors for \n, all others are non-
569// printable so easy catch. It is _acceptable_ for *, J or j to exist in
570// the reason string, so 2/9 chance we will miss the terminating newline.
571//
572// NB: J might not be acceptable, except if at the beginning or preceded
573// with a space, '(' or any of the quotes and their BER aliases.
574// NB: * might not be acceptable, except if at the beginning or preceded
575// with a space, another *, or any of the quotes or their BER aliases.
576//
577// To reduce the chances to closer to 1/9 is too complicated for the gain.
578bool likely_newline(char c) {
579 switch (static_cast<uint8_t>(c)) {
580 case '\n': // '\n' (unprintable)
581 case '\n' ^ 0x01: // '\r' (unprintable)
582 case '\n' ^ 0x02: // '\b' (unprintable)
583 case '\n' ^ 0x04: // 0x0E (unprintable)
584 case '\n' ^ 0x08: // 0x02 (unprintable)
585 case '\n' ^ 0x10: // 0x1A (unprintable)
586 return true;
587 case '\n' ^ 0x20: // '*'
588 case '\n' ^ 0x40: // 'J'
589 break;
590 case '\n' ^ 0x80: // 0x8A (unprintable)
591 return true;
592 }
593 return false;
594}
595
596// ::isprint(c) will prevent us from being called for all the printable
597// matches below. If we let unprintables through because of this, they
598// get converted to underscore (_) by the validation phase.
599bool likely_space(char c) {
600 switch (static_cast<uint8_t>(c)) {
601 case ' ': // ' '
602 case ' ' ^ 0x01: // '!'
603 case ' ' ^ 0x02: // '"'
604 case ' ' ^ 0x04: // '$'
605 case ' ' ^ 0x08: // '('
606 case ' ' ^ 0x10: // '0'
607 case ' ' ^ 0x20: // '\0' (unprintable)
608 case ' ' ^ 0x40: // 'P'
609 case ' ' ^ 0x80: // 0xA0 (unprintable)
610 case '\t': // '\t'
611 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
612 case '\t' ^ 0x02: // '\v' (unprintable)
613 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
614 case '\t' ^ 0x08: // 0x01 (unprintable)
615 case '\t' ^ 0x10: // 0x19 (unprintable)
616 case '\t' ^ 0x20: // ')'
617 case '\t' ^ 0x40: // '1'
618 case '\t' ^ 0x80: // 0x89 (unprintable)
619 return true;
620 }
621 return false;
622}
623
624std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700625 static constexpr size_t max_reason_length = 256;
626
627 std::string subReason(content.substr(pos, max_reason_length));
628 // Correct against any known strings that Bit Error Match
629 for (const auto& s : knownReasons) {
630 correctForBitErrorOrUnderline(subReason, s);
631 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700632 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700633 for (const auto& m : kBootReasonMap) {
634 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700635 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700636 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
637 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700638 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700639 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700640 correctForBitErrorOrUnderline(subReason,
641 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
642 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
643 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700644 }
645 }
646 for (pos = 0; pos < subReason.length(); ++pos) {
647 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700648 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
649 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700650 subReason.erase(pos);
651 break;
652 }
653 }
654 transformReason(subReason);
655 return subReason;
656}
657
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700658bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700659 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700660 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
661 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700662 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700663 // Invented for Android to allow daemons that specifically trigger sysrq
664 // to communicate more accurate boot subreasons via last console messages.
665 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
666 auto pos = console.rfind(sysrqSubreason);
667 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700668 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700669 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700670 return true;
671 }
672 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
673 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700674 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700675 return true;
676 }
677 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700678 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700679 return true;
680 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700681
682 std::string panic("Kernel panic - not syncing: ");
683 auto pos = console.rfind(panic);
684 if (pos != std::string::npos) {
685 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
686 {"Out of memory", "oom"},
687 {"out of memory", "oom"},
688 {"Oh boy, that early out of memory", "oom"}, // omg
689 {"BUG!", "bug"},
690 {"hung_task: blocked tasks", "hung"},
691 {"audit: ", "audit"},
692 {"scheduling while atomic", "atomic"},
693 {"Attempted to kill init!", "init"},
694 {"Requested init", "init"},
695 {"No working init", "init"},
696 {"Could not decompress init", "init"},
697 {"RCU Stall", "hung,rcu"},
698 {"stack-protector", "stack"},
699 {"kernel stack overflow", "stack"},
700 {"Corrupt kernel stack", "stack"},
701 {"low stack detected", "stack"},
702 {"corrupted stack end", "stack"},
703 };
704
705 ret = "kernel_panic";
706 for (auto& s : panicReasons) {
707 if (console.find(panic + s.first, pos) != std::string::npos) {
708 ret += "," + s.second;
709 return true;
710 }
711 }
712 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
713 if (reason.length() > 3) {
714 ret += "," + reason;
715 }
716 return true;
717 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700718 return false;
719}
720
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700721bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
722 return addKernelPanicSubReason(pstoreConsole(content), ret);
723}
724
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700725const char system_reboot_reason_property[] = "sys.boot.reason";
726const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
727const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
728
729// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
730std::string BootReasonStrToReason(const std::string& boot_reason) {
731 std::string ret(GetProperty(system_reboot_reason_property));
732 std::string reason(boot_reason);
733 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
734 if (reason == ret) ret = "";
735
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700736 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700737
738 // Is the current system boot reason sys.boot.reason valid?
739 if (!isKnownRebootReason(ret)) ret = "";
740
741 if (ret == "") {
742 // Is the bootloader boot reason ro.boot.bootreason known?
743 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700744 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700745 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700746 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700747 if (r == s) {
748 if (isBluntRebootReason(s)) {
749 blunt = s;
750 } else {
751 ret = s;
752 break;
753 }
754 }
755 }
756 if (ret == "") ret = blunt;
757 if (ret != "") break;
758 }
759 }
760
761 if (ret == "") {
762 // A series of checks to take some officially unsupported reasons
763 // reported by the bootloader and find some logical and canonical
764 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700765 // to behave and follow our CTS standards.
766 //
767 // first member is the output
768 // second member is an unanchored regex for an alias
769 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700770 // If output has a prefix of <bang> '!', we do not use it as a
771 // match needle (and drop the <bang> prefix when landing in output),
772 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700773 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700774 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700775 {"watchdog", "wdog"},
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700776 {"cold,powerkey", "powerkey|power_key|PowerKey"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700777 {"kernel_panic", "panic"},
778 {"shutdown,thermal", "thermal"},
779 {"warm,s3_wakeup", "s3_wakeup"},
780 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700781 {"cold,charger", "usb"},
782 {"cold,rtc", "rtc"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700783 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700784 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700785 };
786
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700787 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700788 size_t firstHasNot = s.first[0] == '!';
789 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700790 ret = s.first;
791 break;
792 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700793 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700794 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700795 break;
796 }
797 }
798 }
799
800 // If watchdog is the reason, see if there is a security angle?
801 if (ret == "watchdog") {
802 if (reason.find("sec") != std::string::npos) {
803 ret += ",security";
804 }
805 }
806
Mark Salyzyn64610892017-09-18 10:41:14 -0700807 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700808 // Check to see if last klog has some refinement hints.
809 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700810 if (readPstoreConsole(content)) {
811 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700812 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700813 } else if (isBluntRebootReason(ret)) {
814 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700815
Mark Salyzyn64610892017-09-18 10:41:14 -0700816 // Check to see if last klog has some refinement hints.
817 std::string content;
818 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700819 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700820 // The toybox reboot command used directly (unlikely)? But also
821 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700822 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700823 ret = "shutdown"; // Still too blunt, but more accurate.
824 // ToDo: init should record the shutdown reason to kernel messages ala:
825 // init: shutdown system with command 'last_reboot_reason'
826 // so that if pstore has persistence we can get some details
827 // that could be missing in last_reboot_reason_property.
828 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700829
Mark Salyzyn64610892017-09-18 10:41:14 -0700830 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700831 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700832 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700833 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700834 if (subReason != "") { // Will not land "reboot" as that is too blunt.
835 if (isKernelRebootReason(subReason)) {
836 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700837 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700838 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700839 } else {
840 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700841 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700842 }
843 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700844
Mark Salyzyn64610892017-09-18 10:41:14 -0700845 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700846 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700847 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700848 ((console.rfind("Power held for ") != std::string::npos) ||
849 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700850 ret = "cold";
851 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700852 }
853
854 // The following battery test should migrate to a default system health HAL
855
856 // Let us not worry if the reboot command was issued, for the cases of
857 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
858 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
859 // battery could conceivably lead to these, so worthy of override.
860 if (isBluntRebootReason(ret)) {
861 // Heuristic to determine if shutdown possibly because of a dead battery?
862 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700863 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700864 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700865 const pstoreConsole console(content);
866 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700867 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700868 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700869 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700870 // correct common errors
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700871 correctForBitError(digits, "100 ");
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700872 if (digits[0] == '!') digits[0] = '1';
873 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700874 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700875 const char* endptr = digits.c_str();
876 unsigned level = 0;
877 while (::isdigit(*endptr)) {
878 level *= 10;
879 level += *endptr++ - '0';
880 // make sure no leading zeros, except zero itself, and range check.
881 if ((level == 0) || (level > 100)) break;
882 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700883 // example bit error rate issues for 10%
884 // 'l=10 ' no bits in error
885 // 'l=00 ' single bit error (fails above)
886 // 'l=1 ' single bit error
887 // 'l=0 ' double bit error
888 // There are others, not typically critical because of 2%
889 // battery_dead_threshold. KISS check, make sure second
890 // character after digit sequence is not a space.
891 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700892 LOG(INFO) << "Battery level at shutdown " << level << "%";
893 if (level <= battery_dead_threshold) {
894 ret = "shutdown,battery";
895 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700896 } else { // Most likely
897 digits = ""; // reset digits
898
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700899 // Content buffer no longer will have console data. Beware if more
900 // checks added below, that depend on parsing console content.
901 content = "";
902
903 LOG(DEBUG) << "Can not find last low battery in last console messages";
904 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700905 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700906 if (fp != nullptr) {
907 android::base::ReadFdToString(fileno(fp), &content);
908 }
909 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700910 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
911 const char* match = logcat_battery;
912
913 if (content == "") {
914 // Service logd.klog not running, go to smaller buffer in the kernel.
915 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
916 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700917 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700918 std::unique_ptr<char[]> buf(new char[len]);
919 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
920 if (rc < len) {
921 len = rc + 1;
922 }
923 buf[--len] = '\0';
924 content = buf.get();
925 }
926 match = battery;
927 }
928
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700929 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700930 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700931 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700932 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700933 endptr = digits.c_str();
934 level = 0;
935 while (::isdigit(*endptr)) {
936 level *= 10;
937 level += *endptr++ - '0';
938 // make sure no leading zeros, except zero itself, and range check.
939 if ((level == 0) || (level > 100)) break;
940 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700941 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700942 LOG(INFO) << "Battery level at startup " << level << "%";
943 if (level <= battery_dead_threshold) {
944 ret = "shutdown,battery";
945 }
946 } else {
947 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
948 }
949 }
950 }
951
952 // Is there a controlled shutdown hint in last_reboot_reason_property?
953 if (isBluntRebootReason(ret)) {
954 // Content buffer no longer will have console data. Beware if more
955 // checks added below, that depend on parsing console content.
956 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700957 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700958
Mark Salyzyn62909822017-10-09 09:27:16 -0700959 // Anything in last is better than 'super-blunt' reboot or shutdown.
960 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
961 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700962 }
963 }
964
965 // Other System Health HAL reasons?
966
967 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
968 // possibly offer hardware-specific clues from the PMIC.
969 }
970
971 // If unknown left over from above, make it "reboot,<boot_reason>"
972 if (ret == "") {
973 ret = "reboot";
974 if (android::base::StartsWith(reason, "reboot")) {
975 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700976 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700977 reason = reason.substr(1);
978 }
979 }
980 if (reason != "") {
981 ret += ",";
982 ret += reason;
983 }
984 }
985
986 LOG(INFO) << "Canonical boot reason: " << ret;
987 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
988 // Rewrite as it must be old news, kernel reasons trump user space.
989 SetProperty(last_reboot_reason_property, ret);
990 }
991 return ret;
992}
993
James Hawkinsb9cf7712016-04-08 15:32:19 -0700994// Returns the appropriate metric key prefix for the boot_complete metric such
995// that boot metrics after a system update are labeled as ota_boot_complete;
996// otherwise, they are labeled as boot_complete. This method encapsulates the
997// bookkeeping required to track when a system update has occurred by storing
998// the UTC timestamp of the system build date and comparing against the current
999// system build date.
1000std::string CalculateBootCompletePrefix() {
1001 static const std::string kBuildDateKey = "build_date";
1002 std::string boot_complete_prefix = "boot_complete";
1003
1004 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -07001005 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -07001006 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -07001007 return std::string();
1008 }
James Hawkinsb9cf7712016-04-08 15:32:19 -07001009
1010 BootEventRecordStore boot_event_store;
1011 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -07001012 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
1013 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
1014 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001015 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001016 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001017 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001018 boot_complete_prefix = "ota_" + boot_complete_prefix;
1019 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001020 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001021 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001022 }
1023
1024 return boot_complete_prefix;
1025}
1026
James Hawkinsef0a0902017-01-06 14:38:23 -08001027// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001028void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001029 std::string value = GetProperty(property);
1030
James Hawkins27c05222017-01-26 11:55:44 -08001031 int32_t time_in_ms;
1032 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001033 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1034 }
1035}
1036
James Hawkins1bfcaec2017-05-19 14:27:27 -07001037// A map from bootloader timing stage to the time that stage took during boot.
1038typedef std::map<std::string, int32_t> BootloaderTimingMap;
1039
1040// Returns a mapping from bootloader stage names to the time those stages
1041// took to boot.
1042const BootloaderTimingMap GetBootLoaderTimings() {
1043 BootloaderTimingMap timings;
1044
1045 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1046 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -08001047 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001048 if (value.empty()) {
1049 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001050 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001051 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001052
1053 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001054 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001055 // |stageTiming| is of the form 'stage:time'.
1056 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001057 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001058
1059 std::string stageName = stageTimingValues[0];
1060 int32_t time_ms;
1061 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001062 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001063 }
1064 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001065
James Hawkins1bfcaec2017-05-19 14:27:27 -07001066 return timings;
1067}
1068
Tej Singh4eacd382018-01-25 17:59:57 -08001069// Returns the total bootloader boot time from the ro.boot.boottime system property.
1070int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1071 int32_t total_time = 0;
1072 for (const auto& timing : bootloader_timings) {
1073 total_time += timing.second;
1074 }
1075
1076 return total_time;
1077}
1078
James Hawkins1bfcaec2017-05-19 14:27:27 -07001079// Parses and records the set of bootloader stages and associated boot times
1080// from the ro.boot.boottime system property.
1081void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1082 const BootloaderTimingMap& bootloader_timings) {
1083 int32_t total_time = 0;
1084 for (const auto& timing : bootloader_timings) {
1085 total_time += timing.second;
1086 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1087 }
1088
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001089 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001090}
1091
Tej Singh4eacd382018-01-25 17:59:57 -08001092// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001093// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001094std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1095 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001096 int32_t bootloader_time_ms = 0;
1097
1098 for (const auto& timing : bootloader_timings) {
1099 if (timing.first.compare("SW") != 0) {
1100 bootloader_time_ms += timing.second;
1101 }
1102 }
1103
1104 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001105 return bootloader_duration + uptime;
1106}
1107
1108// Records the closest estimation to the absolute device boot time in seconds.
1109// i.e. from power on to boot_complete, including bootloader times.
1110void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1111 std::chrono::milliseconds absolute_total) {
1112 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1113 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1114}
1115
1116// Logs the total boot time and reason to statsd.
1117void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1118 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1119 double time_since_last_boot_sec) {
1120 const std::string reason(GetProperty(bootloader_reboot_reason_property));
1121
1122 if (reason.empty()) {
1123 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
1124 end_time.count(), total_duration.count(),
1125 (int64_t)bootloader_duration_ms,
1126 (int64_t)time_since_last_boot_sec * 1000);
1127 return;
1128 }
1129
Tej Singhfe3e7622018-02-06 15:57:38 -08001130 const std::string system_reason(GetProperty(system_reboot_reason_property));
Tej Singh4eacd382018-01-25 17:59:57 -08001131 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1132 system_reason.c_str(), end_time.count(), total_duration.count(),
1133 (int64_t)bootloader_duration_ms,
1134 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001135}
1136
Tej Singhfe3e7622018-02-06 15:57:38 -08001137void SetSystemBootReason() {
1138 const std::string bootloader_boot_reason(GetProperty(bootloader_reboot_reason_property));
1139 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1140 // Record the scrubbed system_boot_reason to the property
1141 SetProperty(system_reboot_reason_property, system_boot_reason);
1142}
1143
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001144// Gets the boot time offset. This is useful when Android is running in a
1145// container, because the boot_clock is not reset when Android reboots.
1146std::chrono::nanoseconds GetBootTimeOffset() {
1147 static const int64_t boottime_offset =
1148 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1149 return std::chrono::nanoseconds(boottime_offset);
1150}
1151
1152// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1153// clock.
1154android::base::boot_clock::duration GetUptime() {
1155 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1156}
1157
James Hawkinsc08e9962016-03-11 14:59:50 -08001158// Records several metrics related to the time it takes to boot the device,
1159// including disambiguating boot time on encrypted or non-encrypted devices.
1160void RecordBootComplete() {
1161 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001162 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001163
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001164 auto uptime_ns = GetUptime();
1165 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001166 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001167 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001168
1169 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1170 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001171 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001172 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001173 }
1174
1175 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001176
James Hawkinsb9cf7712016-04-08 15:32:19 -07001177 // The boot_complete metric has two variants: boot_complete and
1178 // ota_boot_complete. The latter signifies that the device is booting after
1179 // a system update.
1180 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001181 if (boot_complete_prefix.empty()) {
1182 // The system is hosed because the build date property could not be read.
1183 return;
1184 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001185
1186 // post_decrypt_time_elapsed is only logged on encrypted devices.
1187 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1188 // Log the amount of time elapsed until the device is decrypted, which
1189 // includes the variable amount of time the user takes to enter the
1190 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001191 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001192
1193 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001194 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001195 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001196 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001197 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001198 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1199 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001200 }
1201
1202 // Record the total time from device startup to boot complete, regardless of
1203 // encryption state.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001204 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001205
1206 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1207 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1208 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001209
James Hawkins1bfcaec2017-05-19 14:27:27 -07001210 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001211 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001212 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1213
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001214 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001215 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1216 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1217
1218 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1219 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1220
1221 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1222 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001223}
1224
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001225// Records the boot_reason metric by querying the ro.boot.bootreason system
1226// property.
1227void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001228 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -07001229
1230 if (reason.empty()) {
1231 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1232 // (and not corruption anywhere else in the reporting pipeline).
1233 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1234 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1235 } else {
1236 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1237 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1238 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001239
1240 // Log the raw bootloader_boot_reason property value.
1241 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001242 BootEventRecordStore boot_event_store;
1243 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001244
1245 // Log the scrubbed system_boot_reason.
Tej Singhfe3e7622018-02-06 15:57:38 -08001246 const std::string system_reason(GetProperty(system_reboot_reason_property));
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001247 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1248 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1249
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001250 if (reason == "") {
1251 SetProperty(bootloader_reboot_reason_property, system_reason);
1252 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001253}
1254
James Hawkins500d7152016-02-16 15:05:54 -08001255// Records two metrics related to the user resetting a device: the time at
1256// which the device is reset, and the time since the user last reset the
1257// device. The former is only set once per-factory reset.
1258void RecordFactoryReset() {
1259 BootEventRecordStore boot_event_store;
1260 BootEventRecordStore::BootEventRecord record;
1261
1262 time_t current_time_utc = time(nullptr);
1263
James Hawkins0660b302016-03-08 16:18:15 -08001264 if (current_time_utc < 0) {
1265 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001266 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1267 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001268
James Hawkins9aec9262017-01-31 11:42:24 -08001269 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001270 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001271 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1272 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001273 return;
1274 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001275 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001276
James Hawkins9aec9262017-01-31 11:42:24 -08001277 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001278 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001279 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001280 }
1281
James Hawkins500d7152016-02-16 15:05:54 -08001282 // The factory_reset boot event does not exist after the device is reset, so
1283 // use this signal to mark the time of the factory reset.
1284 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1285 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001286
1287 // Don't log the time_since_factory_reset until some time has elapsed.
1288 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001289 return;
1290 }
1291
1292 // Calculate and record the difference in time between now and the
1293 // factory_reset time.
1294 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001295 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001296
James Hawkins9aec9262017-01-31 11:42:24 -08001297 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001298 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001299 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001300
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001301 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1302 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001303}
1304
James Hawkinsabd73e62016-01-19 15:10:38 -08001305} // namespace
1306
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001307int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001308 android::base::InitLogging(argv);
1309
1310 const std::string cmd_line = GetCommandLine(argc, argv);
1311 LOG(INFO) << "Service started: " << cmd_line;
1312
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001313 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001314 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001315 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001316 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001317 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001318 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001319 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001320 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001321 { "help", no_argument, NULL, 'h' },
1322 { "log", no_argument, NULL, 'l' },
1323 { "print", no_argument, NULL, 'p' },
1324 { "record", required_argument, NULL, 'r' },
1325 { value_str, required_argument, NULL, 0 },
1326 { system_boot_reason_str, no_argument, NULL, 0 },
1327 { boot_complete_str, no_argument, NULL, 0 },
1328 { boot_reason_str, no_argument, NULL, 0 },
1329 { factory_reset_str, no_argument, NULL, 0 },
1330 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001331 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001332 };
1333
James Hawkinsc6275582016-03-22 10:47:44 -07001334 std::string boot_event;
1335 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001336 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001337 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001338 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001339 // This case handles long options which have no single-character mapping.
1340 case 0: {
1341 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001342 if (option_name == value_str) {
1343 // |optarg| is an external variable set by getopt representing
1344 // the option argument.
1345 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001346 } else if (option_name == system_boot_reason_str) {
1347 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001348 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001349 RecordBootComplete();
1350 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001351 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001352 } else if (option_name == factory_reset_str) {
1353 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001354 } else {
1355 LOG(ERROR) << "Invalid option: " << option_name;
1356 }
1357 break;
1358 }
1359
James Hawkinsabd73e62016-01-19 15:10:38 -08001360 case 'h': {
1361 ShowHelp(argv[0]);
1362 break;
1363 }
1364
1365 case 'l': {
1366 LogBootEvents();
1367 break;
1368 }
1369
1370 case 'p': {
1371 PrintBootEvents();
1372 break;
1373 }
1374
1375 case 'r': {
1376 // |optarg| is an external variable set by getopt representing
1377 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001378 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001379 break;
1380 }
1381
1382 default: {
1383 DCHECK_EQ(opt, '?');
1384
1385 // |optopt| is an external variable set by getopt representing
1386 // the value of the invalid option.
1387 LOG(ERROR) << "Invalid option: " << optopt;
1388 ShowHelp(argv[0]);
1389 return EXIT_FAILURE;
1390 }
1391 }
1392 }
1393
James Hawkinsc6275582016-03-22 10:47:44 -07001394 if (!boot_event.empty()) {
1395 RecordBootEventFromCommandLine(boot_event, value);
1396 }
1397
James Hawkinsabd73e62016-01-19 15:10:38 -08001398 return 0;
1399}