1#! /bin/bash
2#
3# Bootstat boot reason tests
4#
5# throughout testing:
6# - manual tests can only run on eng/userdebug builds
7# - watch adb logcat -b all -d -s bootstat
8# - watch adb logcat -b all -d | audit2allow
9# - wait until screen is up, boot has completed, can mean wait for
10#   sys.boot_completed=1 and sys.bootstat.first_boot_completed=1 to be true
11#
12# All test frames, and nothing else, must be function names prefixed and
13# specifiged with the pattern 'test_<test>() {' as this is also how the
14# script discovers the full list of tests by inspecting its own code.
15#
16
17# Helper variables
18
19SPACE=" "
20ESCAPE=""
21TAB="	"
22GREEN="${ESCAPE}[38;5;40m"
23RED="${ESCAPE}[38;5;196m"
24NORMAL="${ESCAPE}[0m"
25# Best guess to an average device's reboot time, refined as tests return
26DURATION_DEFAULT=45
27STOP_ON_FAILURE=false
28progname="${0##*/}"
29progpath="${0%${progname}}"
30
31# Helper functions
32
33[ "USAGE: inFastboot
34
35Returns: true if device is in fastboot mode" ]
36inFastboot() {
37  fastboot devices | grep "^${ANDROID_SERIAL}[${SPACE}${TAB}]" > /dev/null
38}
39
40[ "USAGE: inAdb
41
42Returns: true if device is in adb mode" ]
43inAdb() {
44  adb devices | grep -v 'List of devices attached' | grep "^${ANDROID_SERIAL}[${SPACE}${TAB}]" > /dev/null
45}
46
47[ "USAGE: adb_sh <commands> </dev/stdin >/dev/stdout 2>/dev/stderr
48
49Returns: true if the command succeeded" ]
50adb_sh() {
51  local args=
52  for i in "${@}"; do
53    [ -z "${args}" ] || args="${args} "
54    if [ X"${i}" != X"${i#\'}" ]; then
55      args="${args}${i}"
56    elif [ X"${i}" != X"${i#*\\}" ]; then
57      args="${args}`echo ${i} | sed 's/\\\\/\\\\\\\\/g'`"
58    elif [ X"${i}" != X"${i#* }" ]; then
59      args="${args}'${i}'"
60    elif [ X"${i}" != X"${i#*${TAB}}" ]; then
61      args="${args}'${i}'"
62    else
63      args="${args}${i}"
64    fi
65  done
66  adb shell "${args}"
67}
68
69[ "USAGE: adb_su <commands> </dev/stdin >/dev/stdout 2>/dev/stderr
70
71Returns: true if the command running as root succeeded" ]
72adb_su() {
73  adb_sh su root "${@}"
74}
75
76[ "USAGE: hasPstore
77
78Returns: true if device (likely) has pstore data" ]
79hasPstore() {
80  if inAdb && [ 0 -eq `adb_su ls /sys/fs/pstore </dev/null | wc -l` ]; then
81    false
82  fi
83}
84
85[ "USAGE: get_property <prop>
86
87Returns the property value" ]
88get_property() {
89  adb_sh getprop ${1} 2>&1 </dev/null
90}
91
92[ "USAGE: isDebuggable
93
94Returns: true if device is (likely) a debug build" ]
95isDebuggable() {
96  if inAdb && [ 1 -ne `get_property ro.debuggable` ]; then
97    false
98  fi
99}
100
101[ "USAGE: checkDebugBuild [--noerror]
102
103Returns: true if device is a userdebug or eng release" ]
104checkDebugBuild() {
105  if isDebuggable; then
106    echo "INFO: '${TEST}' test requires userdebug build"
107  elif [ -n "${1}" ]; then
108    echo "WARNING: '${TEST}' test requires userdebug build"
109    false
110  else
111    echo "ERROR: '${TEST}' test requires userdebug build, skipping FAILURE"
112    duration_prefix="~"
113    duration_estimate=1
114    false
115  fi >&2
116}
117
118[ "USAGE: setBootloaderBootReason [value]
119
120Returns: true if device supports and set boot reason injection" ]
121setBootloaderBootReason() {
122  inAdb || ( echo "ERROR: device not in adb mode." >&2 ; false ) || return 1
123  if [ -z "`adb_sh ls /etc/init/bootstat-debug.rc 2>/dev/null </dev/null`" ]; then
124    echo "ERROR: '${TEST}' test requires /etc/init/bootstat-debug.rc" >&2
125    return 1
126  fi
127  checkDebugBuild || return 1
128  if adb_su "cat /proc/cmdline | tr '\\0 ' '\\n\\n'" </dev/null |
129     grep '^androidboot[.]bootreason=[^ ]' >/dev/null; then
130    echo "ERROR: '${TEST}' test requires a device with a bootloader that" >&2
131    echo "       does not set androidboot.bootreason kernel parameter." >&2
132    return 1
133  fi
134  adb_su setprop persist.test.boot.reason "'${1}'" 2>/dev/null </dev/null
135  test_reason="`get_property persist.test.boot.reason`"
136  if [ X"${test_reason}" != X"${1}" ]; then
137    echo "ERROR: can not set persist.test.boot.reason to '${1}'." >&2
138    return 1
139  fi
140}
141
142[ "USAGE: enterPstore
143
144Prints a warning string requiring functional pstore
145
146Returns: pstore_ok variable set to true or false" ]
147enterPstore() {
148  if hasPstore; then
149    echo "INFO: '${TEST}' test requires functional and reliable pstore"
150    pstore_ok=true
151  else
152    echo "WARNING: '${TEST}' test requires functional pstore"
153    pstore_ok=false
154  fi >&2
155  ${pstore_ok}
156}
157
158[ "USAGE: exitPstore
159
160Prints an error string requiring functional pstore
161
162Returns: clears error if pstore dysfunctional" ]
163exitPstore() {
164  save_ret=${?}
165  if [ ${save_ret} != 0 ]; then
166    if hasPstore; then
167      return ${save_ret}
168    fi
169    if [ true = ${pstore_ok} ]; then
170      echo "WARNING: '${TEST}' test requires functional pstore"
171      return ${save_ret}
172    fi
173    echo "ERROR: '${TEST}' test requires functional pstore, skipping FAILURE"
174    duration_prefix="~"
175    duration_estimate=1
176  fi >&2
177}
178
179[ "USAGE: format_duration <seconds>
180
181human readable output whole seconds, whole minutes or mm:ss" ]
182format_duration() {
183  if [ -z "${1}" ]; then
184    echo unknown
185    return
186  fi
187  seconds=`expr ${1} % 60`
188  minutes=`expr ${1} / 60`
189  if [ 0 -eq ${minutes} ]; then
190    if [ 1 -eq ${1} ]; then
191      echo 1 second
192      return
193    fi
194    echo ${1} seconds
195    return
196  elif [ 60 -eq ${1} ]; then
197    echo 1 minute
198    return
199  elif [ 0 -eq ${seconds} ]; then
200    echo ${minutes} minutes
201    return
202  fi
203  echo ${minutes}:`expr ${seconds} / 10``expr ${seconds} % 10`
204}
205
206wait_for_screen_timeout=900
207[ "USAGE: wait_for_screen [-n] [TIMEOUT]
208
209-n - echo newline at exit
210TIMEOUT - default `format_duration ${wait_for_screen_timeout}`" ]
211wait_for_screen() {
212  exit_function=true
213  if [ X"-n" = X"${1}" ]; then
214    exit_function=echo
215    shift
216  fi
217  timeout=${wait_for_screen_timeout}
218  if [ ${#} -gt 0 ]; then
219    timeout=${1}
220    shift
221  fi
222  counter=0
223  while true; do
224    if inFastboot; then
225      fastboot reboot
226    elif inAdb; then
227      if [ 0 != ${counter} ]; then
228        adb wait-for-device </dev/null >/dev/null 2>/dev/null
229      fi
230      if [ -n "`get_property sys.boot.reason`" ]
231      then
232        vals=`get_property |
233              sed -n 's/[[]sys[.]\(boot_completed\|logbootcomplete\|bootstat[.]first_boot_completed\)[]]: [[]\([01]\)[]]$/\1=\2/p'`
234        if [ X"${vals}" != X"${vals##*boot_completed=1}" ]; then
235          if [ X"${vals}" != X"${vals##*logbootcomple=1}" ]; then
236            sleep 1
237            break
238          fi
239          if [ X"${vals}" != X"${vals##*bootstat.first_boot_completed=1}" ]; then
240            sleep 1
241            break
242          fi
243        fi
244      fi
245    fi
246    counter=`expr ${counter} + 1`
247    if [ ${counter} -gt ${timeout} ]; then
248      ${exit_function}
249      echo "ERROR: wait_for_screen() timed out (`format_duration ${timeout}`)" >&2
250      return 1
251    fi
252    sleep 1
253  done
254  ${exit_function}
255}
256
257[ "USAGE: EXPECT_EQ <lval> <rval> [message]
258
259Returns true if (regex) lval matches rval" ]
260EXPECT_EQ() {
261  lval="${1}"
262  rval="${2}"
263  shift 2
264  if ! ( echo X"${rval}" | grep '^X'"${lval}"'$' >/dev/null 2>/dev/null ); then
265    if [ `echo ${lval}${rval}${*} | wc -c` -gt 50 -o "${rval}" != "${rval%
266*}" ]; then
267      echo "ERROR: expected \"${lval}\"" >&2
268      echo "       got \"${rval}\"" |
269        sed ': again
270             N
271             s/\(\n\)\([^ ]\)/\1             \2/
272             t again' >&2
273      if [ -n "${*}" ] ; then
274        echo "       ${*}" >&2
275      fi
276    else
277      echo "ERROR: expected \"${lval}\" got \"${rval}\" ${*}" >&2
278    fi
279    return 1
280  fi
281  if [ -n "${*}" ] ; then
282    if [ X"${lval}" != X"${rval}" ]; then
283      if [ `echo ${lval}${rval}${*} | wc -c` -gt 60 -o "${rval}" != "${rval%
284*}" ]; then
285        echo "INFO: ok \"${lval}\"" >&2
286        echo "       = \"${rval}\"" |
287          sed ': again
288               N
289               s/\(\n\)\([^ ]\)/\1          \2/
290               t again' >&2
291        if [ -n "${*}" ] ; then
292          echo "      ${*}" >&2
293        fi
294      else
295        echo "INFO: ok \"${lval}\" = \"${rval}\" ${*}" >&2
296      fi
297    else
298      echo "INFO: ok \"${lval}\" ${*}" >&2
299    fi
300  fi
301  return 0
302}
303
304BAD_BOOTLOADER_REASON=
305
306[ "USAGE: EXPECT_PROPERTY <prop> <value> [--allow_failure]
307
308Returns true (0) if current return (regex) value is true and the result matches
309and the incoming return value is true as well (wired-or)" ]
310EXPECT_PROPERTY() {
311  save_ret=${?}
312  property="${1}"
313  value="${2}"
314  shift 2
315  val=`get_property ${property}`
316  EXPECT_EQ "${value}" "${val}" for Android property ${property}
317  local_ret=${?}
318  if [ 0 != ${local_ret} -a "ro.boot.bootreason" = "${property}" ]; then
319    if [ -z "${BAD_BOOTLOADER_REASON}" ]; then
320      BAD_BOOTLOADER_REASON=${val}
321    elif [ X"${BAD_BOOTLOADER_REASON}" = X"${val}" ]; then
322      local_ret=0
323    fi
324  fi
325  if [ 0 != ${local_ret} ]; then
326    if [ -z "${1}" ] ; then
327      save_ret=${local_ret}
328    fi
329  fi
330  return ${save_ret}
331}
332
333[ "USAGE: adb_date >/dev/stdout
334
335Returns: report device epoch time (suitable for logcat -t)" ]
336adb_date() {
337  adb_sh date +%s.%N </dev/null
338}
339
340[ "USAGE: report_bootstat_logs [-t<timestamp>] <expected> ...
341
342if not prefixed with a minus (-), <expected> will become a series of expected
343matches:
344
345    bootstat: Canonical boot reason: <expected_property_value>
346
347If prefixed with a minus, <expected> will look for an exact match after
348removing the minux prefix.  All expected content is _dropped_ from the output
349and in essence forms a known blacklist, unexpected content will show.
350
351Report any logs, minus a known blacklist, preserve the current exit status" ]
352report_bootstat_logs() {
353  save_ret=${?}
354  match=
355  timestamp=-d
356  for i in "${@}"; do
357    if [ X"${i}" != X"${i#-t}" ]; then
358      timestamp="${i}"
359    elif [ X"${i}" != X"${i#-}" ]; then
360      match="${match}
361${i#-}"
362    else
363      match="${match}
364bootstat: Canonical boot reason: ${i}"
365    fi
366  done
367  adb logcat -b all ${timestamp} |
368  grep bootstat[^e] |
369  grep -v -F "bootstat: Service started: /system/bin/bootstat --record_boot_complete${match}
370bootstat: Service started: /system/bin/bootstat --record_boot_reason
371bootstat: Service started: /system/bin/bootstat --set_system_boot_reason
372bootstat: Service started: /system/bin/bootstat --record_time_since_factory_reset
373bootstat: Service started: /system/bin/bootstat -l
374bootstat: Service started: /system/bin/bootstat --set_system_boot_reason --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l
375bootstat: Battery level at shutdown 100%
376bootstat: Battery level at startup 100%
377init    : Parsing file /system/etc/init/bootstat.rc...
378init    : Parsing file /system/etc/init/bootstat-debug.rc...
379init    : processing action (persist.test.boot.reason=*) from (/system/etc/init/bootstat-debug.rc:
380init    : Command 'setprop ro.boot.bootreason \${persist.test.boot.reason}' action=persist.test.boot.reason=* (/system/etc/init/bootstat-debug.rc:
381init    : processing action (post-fs-data) from (/system/etc/init/bootstat.rc
382init    : processing action (boot) from (/system/etc/init/bootstat.rc
383init    : processing action (ro.boot.bootreason=*) from (/system/etc/init/bootstat.rc
384init    : processing action (ro.boot.bootreason=* && post-fs) from (/system/etc/init/bootstat.rc
385init    : processing action (sys.bootstat.first_zygote_start=0 && zygote-start) from (/system/etc/init/bootstat.rc
386init    : processing action (sys.boot_completed=1 && sys.bootstat.first_boot_completed=0) from (/system/etc/init/bootstat.rc
387 (/system/bin/bootstat --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l)'
388 (/system/bin/bootstat --set_system_boot_reason --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l)'
389init    : Command 'exec - system log -- /system/bin/bootstat --record_boot_complete' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc:
390init    : Command 'exec - system log -- /system/bin/bootstat --record_boot_reason' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc:
391init    : Command 'exec - system log -- /system/bin/bootstat --record_time_since_factory_reset' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc:
392init    : Command 'exec_background - system log -- /system/bin/bootstat --set_system_boot_reason --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc
393 (/system/bin/bootstat --record_boot_complete)'...
394 (/system/bin/bootstat --record_boot_complete)' (pid${SPACE}
395 (/system/bin/bootstat --record_boot_reason)'...
396 (/system/bin/bootstat --record_boot_reason)' (pid${SPACE}
397 (/system/bin/bootstat --record_time_since_factory_reset)'...
398 (/system/bin/bootstat --record_time_since_factory_reset)' (pid${SPACE}
399 (/system/bin/bootstat --set_system_boot_reason)'...
400 (/system/bin/bootstat --set_system_boot_reason)' (pid${SPACE}
401 (/system/bin/bootstat -l)'...
402 (/system/bin/bootstat -l)' (pid " |
403  grep -v 'bootstat: Unknown boot reason: $' # Hikey Special
404  return ${save_ret}
405}
406
407[ "USAGE: start_test [message]
408
409Record start of test, preserve exit status" ]
410start_test() {
411  save_ret=${?}
412  duration_prefix="~"
413  duration_estimate=1
414  START=`date +%s`
415  echo "${GREEN}[ RUN      ]${NORMAL} ${TEST} ${*}"
416  return ${save_ret}
417}
418
419duration_sum_diff=0
420duration_num=0
421[ "USAGE: duration_test [[prefix]seconds]
422
423Report the adjusted and expected test duration" ]
424duration_test() {
425  duration_prefix=${1%%[0123456789]*}
426  if [ -z "${duration_prefix}" ]; then
427    duration_prefix="~"
428  fi
429  duration_estimate="${1#${duration_prefix}}"
430  if [ -z "${duration_estimate}" ]; then
431    duration_estimate="${DURATION_DEFAULT}"
432  fi
433  duration_new_estimate="${duration_estimate}"
434  if [ 0 -ne ${duration_num} ]; then
435    duration_new_estimate=`expr ${duration_new_estimate} + \
436      \( ${duration_num} / 2 + ${duration_sum_diff} \) / ${duration_num}`
437    # guard against catastrophe
438    if [ -z "${duration_new_estimate}" ]; then
439      duration_new_estimate=${duration_estimate}
440    fi
441  fi
442  # negative values are so undignified
443  if [ 0 -ge ${duration_new_estimate} ]; then
444    duration_new_estimate=1
445  fi
446  echo "INFO: expected duration of '${TEST}' test" \
447       "${duration_prefix}`format_duration ${duration_new_estimate}`" >&2
448}
449
450[ "USAGE: end_test [message]
451
452Document duration and success of test, preserve exit status" ]
453end_test() {
454  save_ret=${?}
455  END=`date +%s`
456  duration=`expr ${END} - ${START} 2>/dev/null`
457  [ 0 -ge ${duration} ] ||
458    echo "INFO: '${TEST}' test duration `format_duration ${duration}`" >&2
459  if [ ${save_ret} = 0 ]; then
460    if [ 0 -lt ${duration} -a 0 -lt ${duration_estimate} -a \( \
461           X"~" = X"${duration_prefix}" -o \
462           ${duration_estimate} -gt ${duration} \) ]; then
463      duration_sum_diff=`expr ${duration_sum_diff} + \
464                              ${duration} - ${duration_estimate}`
465      duration_num=`expr ${duration_num} + 1`
466    fi
467    echo "${GREEN}[       OK ]${NORMAL} ${TEST} ${*}"
468  else
469    echo "${RED}[  FAILED  ]${NORMAL} ${TEST} ${*}"
470    if ${STOP_ON_FAILURE}; then
471      exit ${save_ret}
472    fi
473  fi
474  return ${save_ret}
475}
476
477[ "USAGE: wrap_test <test> [message]
478
479All tests below are wrapped with this helper" ]
480wrap_test() {
481  if [ -z "${1}" -o X"nothing" = X"${1}" ]; then
482    return
483  fi
484  TEST=${1}
485  shift
486  start_test ${1}
487  eval test_${TEST}
488  end_test ${2}
489}
490
491[ "USAGE: validate_reason <value>
492
493Check property for CTS compliance with our expectations. Return a cleansed
494string representing what is acceptable.
495
496NB: must also roughly match heuristics in system/core/bootstat/bootstat.cpp" ]
497validate_reason() {
498  var=`echo -n ${*} |
499       tr '[A-Z]' '[a-z]' |
500       tr ' \f\t\r\n' '_____'`
501  case ${var} in
502    watchdog | watchdog,?* ) ;;
503    kernel_panic | kernel_panic,?* ) ;;
504    recovery | recovery,?* ) ;;
505    bootloader | bootloader,?* ) ;;
506    cold | cold,?* ) ;;
507    hard | hard,?* ) ;;
508    warm | warm,?* ) ;;
509    shutdown | shutdown,?* ) ;;
510    reboot,reboot | reboot,reboot,* )     var=${var#reboot,} ; var=${var%,} ;;
511    reboot,cold | reboot,cold,* )         var=${var#reboot,} ; var=${var%,} ;;
512    reboot,hard | reboot,hard,* )         var=${var#reboot,} ; var=${var%,} ;;
513    reboot,warm | reboot,warm,* )         var=${var#reboot,} ; var=${var%,} ;;
514    reboot,recovery | reboot,recovery,* ) var=${var#reboot,} ; var=${var%,} ;;
515    reboot,bootloader | reboot,bootloader,* ) var=${var#reboot,} ; var=${var%,} ;;
516    reboot | reboot,?* ) ;;
517    # Aliases and Heuristics
518    *wdog* | *watchdog* )                                    var="watchdog" ;;
519    *powerkey* | *power_on_key* | *power_key* | *PowerKey* ) var="cold,powerkey" ;;
520    *panic* | *kernel_panic* )                               var="kernel_panic" ;;
521    *thermal* )                                              var="shutdown,thermal" ;;
522    *s3_wakeup* )                                            var="warm,s3_wakeup" ;;
523    *hw_reset* )                                             var="hard,hw_reset" ;;
524    *usb* | *power_on_cable* )                               var="cold,charger" ;;
525    *rtc* )                                                  var="cold,rtc" ;;
526    *2sec_reboot* )                                          var="cold,rtc,2sec" ;;
527    *wdt_by_pass_pwk* )                                      var="warm" ;;
528    wdt )                                                    var="reboot" ;;
529    *tool_by_pass_pwk* )                                     var="reboot,tool" ;;
530    *bootloader* )                                           var="bootloader" ;;
531    * )                                                      var="reboot" ;;
532  esac
533  echo ${var}
534}
535
536[ "USAGE: validate_property <property>
537
538Check property for CTS compliance with our expectations. Return a cleansed
539string representing what is acceptable.
540
541NB: must also roughly match heuristics in system/core/bootstat/bootstat.cpp" ]
542validate_property() {
543  val=`get_property ${1}`
544  ret=`validate_reason "${val}"`
545  if [ "reboot" = "${ret}" ]; then
546    ret=`validate_reason "reboot,${val}"`
547  fi
548  echo ${ret}
549}
550
551[ "USAGE: check_boilerblate_properties
552
553Check for common property values" ]
554check_boilerplate_properties() {
555  EXPECT_PROPERTY persist.sys.boot.reason ""
556  save_ret=${?}
557  reason=`validate_property sys.boot.reason`
558  ( exit ${save_ret} )  # because one can not just do ?=${save_ret}
559  EXPECT_PROPERTY persist.sys.boot.reason.history "${reason},[1-9][0-9]*\(\|[^0-9].*\)"
560}
561
562#
563# Actual test frames
564#
565
566[ "USAGE: test_properties
567
568properties test
569- (wait until screen is up, boot has completed)
570- adb shell getprop ro.boot.bootreason (bootloader reason)
571- adb shell getprop persist.sys.boot.reason (last reason)
572- adb shell getprop sys.boot.reason.last (last last reason)
573- adb shell getprop sys.boot.reason (system reason)
574- NB: all should have a value that is compliant with our known set." ]
575test_properties() {
576  duration_test 1
577  wait_for_screen
578  retval=0
579  # sys.boot.reason is last for a reason
580  check_set="ro.boot.bootreason sys.boot.reason.last sys.boot.reason"
581  bootloader=""
582  # NB: this test could fail if performed _after_ optional_factory_reset test
583  # and will report
584  #  ERROR: expected "reboot" got ""
585  #        for Android property sys.boot.reason.last
586  # following is mitigation for the persist.sys.boot.reason, skip it
587  if [ "reboot,factory_reset" = "`validate_property ro.boot_bootreason`" ]; then
588    check_set="ro.boot.bootreason sys.boot.reason"
589    bootloader="bootloader"
590  fi
591  for prop in ${check_set}; do
592    reason=`validate_property ${prop}`
593    EXPECT_PROPERTY ${prop} ${reason} || retval=${?}
594  done
595  check_boilerplate_properties || retval=${?}
596  report_bootstat_logs ${reason} ${bootloader}
597  return ${retval}
598}
599
600[ "USAGE: test_ota
601
602ota test
603- rm out/.kati_stamp-* out/build_date.txt out/build_number.txt
604- rm out/target/product/*/*/*.prop
605- rm -r out/target/product/*/obj/ETC/system_build_prop_intermediates
606- m
607- NB: ro.build.date.utc should update
608- fastboot flashall
609- (wait until screen is up, boot has completed)
610- adb shell getprop sys.boot.reason
611- NB: should report ota
612
613Decision to change the build itself rather than trick bootstat by
614rummaging through its data files was made." ]
615test_ota() {
616  duration_test ">300"
617  echo "      extended by build and flashing times" >&2
618  if [ -z "${TARGET_PRODUCT}" -o \
619       -z "${ANDROID_PRODUCT_OUT}" -o \
620       -z "${ANDROID_BUILD_TOP}" -o \
621       -z "${TARGET_BUILD_VARIANT}" ]; then
622    echo "ERROR: Missing envsetup.sh and lunch" >&2
623    return 1
624  fi
625  rm ${ANDROID_PRODUCT_OUT%/out/*}/out/.kati_stamp-* ||
626    true
627  rm ${ANDROID_PRODUCT_OUT%/out/*}/out/build_date.txt ||
628    true
629  rm ${ANDROID_PRODUCT_OUT%/out/*}/out/build_number.txt ||
630    true
631  rm ${ANDROID_PRODUCT_OUT}/*/*.prop ||
632    true
633  rm -r ${ANDROID_PRODUCT_OUT}/obj/ETC/system_build_prop_intermediates ||
634    true
635  pushd ${ANDROID_BUILD_TOP} >&2
636  build/soong/soong_ui.bash --make-mode >&2
637  if [ ${?} != 0 ]; then
638    popd >&2
639    return 1
640  fi
641  if ! inFastboot; then
642    adb reboot-bootloader >&2
643  fi
644  fastboot flashall >&2
645  popd >&2
646  wait_for_screen
647  EXPECT_PROPERTY sys.boot.reason "\(reboot,ota\|bootloader\)"
648  EXPECT_PROPERTY sys.boot.reason.last bootloader
649  check_boilerplate_properties
650  report_bootstat_logs reboot,ota bootloader
651}
652
653[ "USAGE: test_optional_ota
654
655fast and fake (touch build_date on device to make it different)" ]
656test_optional_ota() {
657  checkDebugBuild || return
658  duration_test
659  adb_su touch /data/misc/bootstat/build_date >&2 </dev/null
660  adb reboot ota
661  wait_for_screen
662  EXPECT_PROPERTY sys.boot.reason reboot,ota
663  EXPECT_PROPERTY sys.boot.reason.last reboot,ota
664  check_boilerplate_properties
665  report_bootstat_logs reboot,ota
666}
667
668[ "USAGE: [TEST=<test>] blind_reboot_test
669
670Simple tests helper
671- adb reboot <test>
672- (wait until screen is up, boot has completed)
673- adb shell getprop sys.boot.reason
674- NB: should report <test>, or reboot,<test> depending on canonical rules
675
676We interleave the simple reboot tests between the hard/complex ones
677as a means of checking sanity and any persistent side effect of the
678other tests." ]
679blind_reboot_test() {
680  duration_test
681  case ${TEST} in
682    bootloader | recovery | cold | hard | warm ) reason=${TEST} ;;
683    *)                                           reason=reboot,${TEST#optional_} ;;
684  esac
685  adb reboot ${TEST#optional_}
686  wait_for_screen
687  bootloader_reason=`validate_property ro.boot.bootreason`
688  EXPECT_PROPERTY ro.boot.bootreason ${bootloader_reason}
689  # to make sys.boot.reason report user friendly
690  reasons=${reason}
691  if [ "${bootloader_reason}" != "${reason}" -a -n "${bootloader_reason}" ]; then
692    reasons="\(${reason}\|${bootloader_reason}\)"
693  fi
694  EXPECT_PROPERTY sys.boot.reason ${reasons}
695  EXPECT_PROPERTY sys.boot.reason.last ${reason}
696  check_boilerplate_properties
697  report_bootstat_logs ${reason} ${bootloader_reason}
698}
699
700[ "USAGE: test_cold
701
702cold test
703- adb reboot cold
704- (wait until screen is up, boot has completed)
705- adb shell getprop sys.boot.reason
706- NB: should report cold" ]
707test_cold() {
708  blind_reboot_test
709}
710
711[ "USAGE: test_factory_reset
712
713factory_reset test
714- adb shell su root rm /data/misc/bootstat/build_date
715- adb reboot
716- (wait until screen is up, boot has completed)
717- adb shell getprop sys.boot.reason
718- NB: should report factory_reset
719
720Decision to rummage through bootstat data files was made as
721a _real_ factory_reset is too destructive to the device." ]
722test_factory_reset() {
723  checkDebugBuild || return
724  duration_test
725  adb_su rm /data/misc/bootstat/build_date >&2 </dev/null
726  adb reboot >&2
727  wait_for_screen
728  EXPECT_PROPERTY sys.boot.reason reboot,factory_reset
729  EXPECT_PROPERTY sys.boot.reason.last "reboot,.*"
730  check_boilerplate_properties
731  report_bootstat_logs reboot,factory_reset reboot, reboot,adb \
732    "-bootstat: Failed to read /data/misc/bootstat/build_date: No such file or directory" \
733    "-bootstat: Failed to parse boot time record: /data/misc/bootstat/build_date"
734}
735
736[ "USAGE: test_optional_factory_reset
737
738factory_reset test
739- adb reboot-bootloader
740- fastboot format userdata
741- fastboot reboot
742- (wait until screen is up, boot has completed)
743- adb shell getprop sys.boot.reason
744- NB: should report factory_reset
745
746For realz, and disruptive" ]
747test_optional_factory_reset() {
748  duration_test 60
749  if ! inFastboot; then
750    adb reboot-bootloader
751  fi
752  fastboot format userdata >&2
753  save_ret=${?}
754  if [ 0 != ${save_ret} ]; then
755    echo "ERROR: fastboot can not format userdata" >&2
756  fi
757  fastboot reboot >&2
758  wait_for_screen
759  ( exit ${save_ret} )  # because one can not just do ?=${save_ret}
760  EXPECT_PROPERTY sys.boot.reason reboot,factory_reset
761  EXPECT_PROPERTY sys.boot.reason.last "\(\|bootloader\)"
762  check_boilerplate_properties
763  report_bootstat_logs reboot,factory_reset bootloader \
764    "-bootstat: Failed to read /data/misc/bootstat/last_boot_time_utc: No such file or directory" \
765    "-bootstat: Failed to parse boot time record: /data/misc/bootstat/last_boot_time_utc" \
766    "-bootstat: Failed to read /data/misc/bootstat/build_date: No such file or directory" \
767    "-bootstat: Failed to parse boot time record: /data/misc/bootstat/build_date" \
768    "-bootstat: Failed to read /data/misc/bootstat/factory_reset: No such file or directory" \
769    "-bootstat: Failed to parse boot time record: /data/misc/bootstat/factory_reset"
770}
771
772[ "USAGE: test_hard
773
774hard test:
775- adb reboot hard
776- (wait until screen is up, boot has completed)
777- adb shell getprop sys.boot.reason
778- NB: should report hard" ]
779test_hard() {
780  blind_reboot_test
781}
782
783[ "USAGE: test_battery
784
785battery test (trick):
786- echo healthd: battery l=2<space> | adb shell su root tee /dev/kmsg
787- adb reboot cold
788- (wait until screen is up, boot has completed)
789- adb shell getprop sys.boot.reason
790- NB: should report reboot,battery, unless healthd managed to log
791  before reboot in above trick.
792
793- Bonus points (manual extras)
794- Make sure the following is added to the /init.rc file in post-fs
795  section before logd is started:
796    +    setprop logd.kernel false
797    +    rm /sys/fs/pstore/console-ramoops
798    +    rm /sys/fs/pstore/console-ramoops-0
799    +    write /dev/kmsg \"healthd: battery l=2${SPACE}
800    +\"
801- adb reboot fs
802- (wait until screen is up, boot has completed)
803- adb shell getprop sys.boot.reason
804- NB: should report reboot,battery
805- (replace set logd.kernel true to the above, and retry test)" ]
806test_battery() {
807  checkDebugBuild || return
808  duration_test 120
809  enterPstore
810  # Send it _many_ times to combat devices with flakey pstore
811  for i in a b c d e f g h i j k l m n o p q r s t u v w x y z; do
812    echo 'healthd: battery l=2 ' | adb_su tee /dev/kmsg >/dev/null
813  done
814  adb reboot cold >&2
815  adb wait-for-device
816  wait_for_screen
817  adb_su </dev/null \
818    cat /proc/fs/pstore/console-ramoops \
819        /proc/fs/pstore/console-ramoops-0 2>/dev/null |
820    grep 'healthd: battery l=' |
821    tail -1 |
822    grep 'healthd: battery l=2 ' >/dev/null || (
823      if ! EXPECT_PROPERTY sys.boot.reason reboot,battery >/dev/null 2>/dev/null; then
824        # retry
825        for i in a b c d e f g h i j k l m n o p q r s t u v w x y z; do
826          echo 'healthd: battery l=2 ' | adb_su tee /dev/kmsg >/dev/null
827        done
828        adb reboot cold >&2
829        adb wait-for-device
830        wait_for_screen
831      fi
832    )
833
834  EXPECT_PROPERTY sys.boot.reason shutdown,battery
835  EXPECT_PROPERTY sys.boot.reason.last cold
836  check_boilerplate_properties
837  report_bootstat_logs shutdown,battery "-bootstat: Battery level at shutdown 2%"
838  exitPstore
839}
840
841[ "USAGE: test_optional_battery
842
843battery shutdown test:
844- adb shell setprop sys.powerctl shutdown,battery
845- (power up the device)
846- (wait until screen is up, boot has completed)
847- adb shell getprop sys.boot.reason
848- NB: should report shutdown,battery" ]
849test_optional_battery() {
850  duration_test ">60"
851  echo "      power on request" >&2
852  adb_sh setprop sys.powerctl shutdown,battery </dev/null
853  sleep 5
854  echo -n "WARNING: Please power device back up, waiting ... " >&2
855  wait_for_screen -n >&2
856  EXPECT_PROPERTY sys.boot.reason shutdown,battery
857  EXPECT_PROPERTY sys.boot.reason.last shutdown,battery
858  check_boilerplate_properties
859  report_bootstat_logs shutdown,battery
860}
861
862[ "USAGE: test_optional_battery_thermal
863
864battery thermal shutdown test:
865- adb shell setprop sys.powerctl shutdown,thermal,battery
866- (power up the device)
867- (wait until screen is up, boot has completed)
868- adb shell getprop sys.boot.reason
869- NB: should report shutdown,thermal,battery" ]
870test_optional_battery_thermal() {
871  duration_test ">60"
872  echo "      power on request" >&2
873  adb_sh setprop sys.powerctl shutdown,thermal,battery </dev/null
874  sleep 5
875  echo -n "WARNING: Please power device back up, waiting ... " >&2
876  wait_for_screen -n >&2
877  EXPECT_PROPERTY sys.boot.reason shutdown,thermal,battery
878  EXPECT_PROPERTY sys.boot.reason.last shutdown,thermal,battery
879  check_boilerplate_properties
880  report_bootstat_logs shutdown,thermal,battery
881}
882
883[ "USAGE: test_unknown
884
885unknown test
886- adb reboot unknown
887- (wait until screen is up, boot has completed)
888- adb shell getprop sys.boot.reason
889- NB: should report reboot,unknown
890- NB: expect log \"... I bootstat: Unknown boot reason: reboot,unknown\"" ]
891test_unknown() {
892  blind_reboot_test
893}
894
895[ "USAGE: test_kernel_panic
896
897kernel_panic test:
898- echo c | adb shell su root tee /proc/sysrq-trigger
899- (wait until screen is up, boot has completed)
900- adb shell getprop sys.boot.reason
901- NB: should report kernel_panic,sysrq" ]
902test_kernel_panic() {
903  checkDebugBuild || return
904  duration_test ">90"
905  panic_msg="kernel_panic,sysrq"
906  enterPstore
907  if [ ${?} != 0 ]; then
908    echo "         or functional bootloader" >&2
909    panic_msg="\(kernel_panic,sysrq\|kernel_panic\)"
910    pstore_ok=true
911  fi
912  echo c | adb_su tee /proc/sysrq-trigger >/dev/null
913  wait_for_screen
914  EXPECT_PROPERTY sys.boot.reason ${panic_msg}
915  EXPECT_PROPERTY sys.boot.reason.last ${panic_msg}
916  check_boilerplate_properties
917  report_bootstat_logs kernel_panic,sysrq
918  exitPstore
919}
920
921[ "USAGE: test_kernel_panic_subreason
922
923kernel_panic_subreason test:
924- echo SysRq : Trigger a crash : 'test' | adb shell su root tee /dev/kmsg
925- echo c | adb shell su root tee /proc/sysrq-trigger
926- (wait until screen is up, boot has completed)
927- adb shell getprop sys.boot.reason
928- NB: should report kernel_panic,sysrq,test" ]
929test_kernel_panic_subreason() {
930  checkDebugBuild || return
931  duration_test ">90"
932  panic_msg="kernel_panic,sysrq,test"
933  enterPstore
934  if [ ${?} != 0 ]; then
935    echo "         or functional bootloader" >&2
936    panic_msg="\(kernel_panic,sysrq,test\|kernel_panic\)"
937    pstore_ok=true
938  fi
939  echo "SysRq : Trigger a crash : 'test'" | adb_su tee /dev/kmsg
940  echo c | adb_su tee /proc/sysrq-trigger >/dev/null
941  wait_for_screen
942  EXPECT_PROPERTY sys.boot.reason ${panic_msg}
943  EXPECT_PROPERTY sys.boot.reason.last ${panic_msg}
944  check_boilerplate_properties
945  report_bootstat_logs kernel_panic,sysrq,test \
946    "-bootstat: Unknown boot reason: kernel_panic,sysrq,test"
947  exitPstore
948}
949
950[ "USAGE: test_kernel_panic_hung
951
952kernel_panic_hung test:
953- echo Kernel panic - not synching: hung_task: blocked tasks |
954  adb shell su root tee /dev/kmsg
955- adb reboot warm
956- (wait until screen is up, boot has completed)
957- adb shell getprop sys.boot.reason
958- NB: should report kernel_panic,hung" ]
959test_kernel_panic_hung() {
960  checkDebugBuild || return
961  duration_test
962  panic_msg="kernel_panic,hung"
963  enterPstore
964  if [ ${?} != 0 ]; then
965    echo "         or functional bootloader" >&2
966    panic_msg="\(kernel_panic,hung\|reboot,hung\)"
967    pstore_ok=true
968  fi
969  echo "Kernel panic - not syncing: hung_task: blocked tasks" |
970    adb_su tee /dev/kmsg
971  adb reboot warm
972  wait_for_screen
973  EXPECT_PROPERTY sys.boot.reason ${panic_msg}
974  EXPECT_PROPERTY sys.boot.reason.last ${panic_msg}
975  check_boilerplate_properties
976  report_bootstat_logs kernel_panic,hung
977  exitPstore
978}
979
980[ "USAGE: test_warm
981
982warm test
983- adb reboot warm
984- (wait until screen is up, boot has completed)
985- adb shell getprop sys.boot.reason
986- NB: should report warm" ]
987test_warm() {
988  blind_reboot_test
989}
990
991[ "USAGE: test_thermal_shutdown
992
993thermal shutdown test:
994- adb shell setprop sys.powerctl shutdown,thermal
995- (power up the device)
996- (wait until screen is up, boot has completed)
997- adb shell getprop sys.boot.reason
998- NB: should report shutdown,thermal" ]
999test_thermal_shutdown() {
1000  duration_test ">60"
1001  echo "      power on request" >&2
1002  adb_sh setprop sys.powerctl shutdown,thermal </dev/null
1003  sleep 5
1004  echo -n "WARNING: Please power device back up, waiting ... " >&2
1005  wait_for_screen -n >&2
1006  EXPECT_PROPERTY sys.boot.reason shutdown,thermal
1007  EXPECT_PROPERTY sys.boot.reason.last shutdown,thermal
1008  check_boilerplate_properties
1009  report_bootstat_logs shutdown,thermal
1010}
1011
1012[ "USAGE: test_userrequested_shutdown
1013
1014userrequested shutdown test:
1015- adb shell setprop sys.powerctl shutdown,userrequested
1016- (power up the device)
1017- (wait until screen is up, boot has completed)
1018- adb shell getprop sys.boot.reason
1019- NB: should report shutdown,userrequested" ]
1020test_userrequested_shutdown() {
1021  duration_test ">60"
1022  echo "      power on request" >&2
1023  adb_sh setprop sys.powerctl shutdown,userrequested </dev/null
1024  sleep 5
1025  echo -n "WARNING: Please power device back up, waiting ... " >&2
1026  wait_for_screen -n >&2
1027  EXPECT_PROPERTY sys.boot.reason shutdown,userrequested
1028  EXPECT_PROPERTY sys.boot.reason.last shutdown,userrequested
1029  check_boilerplate_properties
1030  report_bootstat_logs shutdown,userrequested
1031}
1032
1033[ "USAGE: test_shell_reboot
1034
1035shell reboot test:
1036- adb shell reboot
1037- (wait until screen is up, boot has completed)
1038- adb shell getprop sys.boot.reason
1039- NB: should report reboot,shell" ]
1040test_shell_reboot() {
1041  duration_test
1042  adb_sh reboot </dev/null
1043  wait_for_screen
1044  EXPECT_PROPERTY sys.boot.reason reboot,shell
1045  EXPECT_PROPERTY sys.boot.reason.last reboot,shell
1046  check_boilerplate_properties
1047  report_bootstat_logs reboot,shell
1048}
1049
1050[ "USAGE: test_adb_reboot
1051
1052adb reboot test:
1053- adb reboot
1054- (wait until screen is up, boot has completed)
1055- adb shell getprop sys.boot.reason
1056- NB: should report reboot,adb" ]
1057test_adb_reboot() {
1058  duration_test
1059  adb reboot
1060  wait_for_screen
1061  EXPECT_PROPERTY sys.boot.reason reboot,adb
1062  EXPECT_PROPERTY sys.boot.reason.last reboot,adb
1063  check_boilerplate_properties
1064  report_bootstat_logs reboot,adb
1065}
1066
1067[ "USAGE: test_rescueparty
1068
1069rescueparty test
1070- adb reboot rescueparty
1071- (wait until screen is up, boot has completed)
1072- adb shell getprop sys.boot.reason
1073- adb shell getprop ro.boot.bootreason
1074- NB: should report reboot,rescueparty" ]
1075test_optional_rescueparty() {
1076  blind_reboot_test
1077  echo "WARNING: legacy devices are allowed to fail following ro.boot.bootreason result" >&2
1078  EXPECT_PROPERTY ro.boot.bootreason '\(reboot\|reboot,rescueparty\)'
1079}
1080
1081[ "USAGE: test_Its_Just_So_Hard_reboot
1082
1083Its Just So Hard reboot test:
1084- adb shell reboot 'Its Just So Hard'
1085- (wait until screen is up, boot has completed)
1086- adb shell getprop sys.boot.reason
1087- NB: should report reboot,its_just_so_hard
1088- NB: expect log \"... I bootstat: Unknown boot reason: reboot,its_just_so_hard\"" ]
1089test_Its_Just_So_Hard_reboot() {
1090  if isDebuggable; then       # see below
1091    duration_test
1092  else
1093    duration_test `expr ${DURATION_DEFAULT} + ${DURATION_DEFAULT}`
1094  fi
1095  adb_sh 'reboot "Its Just So Hard"' </dev/null
1096  wait_for_screen
1097  EXPECT_PROPERTY sys.boot.reason reboot,its_just_so_hard
1098  EXPECT_PROPERTY sys.boot.reason.last reboot,its_just_so_hard
1099  check_boilerplate_properties
1100  report_bootstat_logs reboot,its_just_so_hard
1101}
1102
1103[ "USAGE: run_bootloader [value [expected]]
1104
1105bootloader boot reason injection tests:
1106- setBootloaderBootReason value
1107- adb shell reboot
1108- (wait until screen is up, boot has completed)
1109- adb shell getprop sys.boot.reason
1110- NB: should report reboot,value" ]
1111run_bootloader() {
1112  bootloader_expected="${1}"
1113  if [ -z "${bootloader_expected}" ]; then
1114    bootloader_expected="${TEST#bootloader_}"
1115  fi
1116  if ! setBootloaderBootReason ${bootloader_expected}; then
1117    echo "       Skipping FAILURE." 2>&1
1118    return
1119  fi
1120  duration_test
1121  if [ X"warm" = X"${bootloader_expected}" ]; then
1122    last_expected=cold
1123  else
1124    last_expected=warm
1125  fi
1126  adb reboot ${last_expected}
1127  wait_for_screen
1128  # Reset so that other tests do not get unexpected injection
1129  setBootloaderBootReason
1130  # Determine the expected values
1131  sys_expected="${2}"
1132  if [ -z "${sys_expected}" ]; then
1133    sys_expected="`validate_reason ${bootloader_expected}`"
1134    if [ "reboot" = "${sys_expected}" ]; then
1135      sys_expected="${last_expected}"
1136    fi
1137  else
1138    sys_expected=`validate_reason ${sys_expected}`
1139  fi
1140  case ${sys_expected} in
1141    kernel_panic | kernel_panic,* | watchdog | watchdog,* )
1142      last_expected=${sys_expected}
1143      ;;
1144  esac
1145  # Check values
1146  EXPECT_PROPERTY ro.boot.bootreason "${bootloader_expected}"
1147  EXPECT_PROPERTY sys.boot.reason "${sys_expected}"
1148  EXPECT_PROPERTY sys.boot.reason.last "${last_expected}"
1149  check_boilerplate_properties
1150  report_bootstat_logs "${sys_expected}"
1151}
1152
1153[ "USAGE: test_bootloader_<type>
1154
1155bootloader boot reasons test injection" ]
1156test_bootloader_normal() {
1157  run_bootloader
1158}
1159
1160test_bootloader_watchdog() {
1161  run_bootloader
1162}
1163
1164test_bootloader_kernel_panic() {
1165  run_bootloader
1166}
1167
1168test_bootloader_oem_powerkey() {
1169  run_bootloader
1170}
1171
1172test_bootloader_wdog_reset() {
1173  run_bootloader
1174}
1175
1176test_bootloader_cold() {
1177  run_bootloader
1178}
1179
1180test_bootloader_warm() {
1181  run_bootloader
1182}
1183
1184test_bootloader_hard() {
1185  run_bootloader
1186}
1187
1188test_bootloader_recovery() {
1189  run_bootloader
1190}
1191
1192[ "USAGE: run_kBootReasonMap [--boot_reason_enum] value expected
1193
1194bootloader boot reason injection tests:
1195- if --boot_reason_enum run bootstat executable for result instead.
1196- inject boot reason into sys.boot.reason
1197- run bootstat --set_system_boot_reason
1198- check for expected enum
1199- " ]
1200run_kBootReasonMap() {
1201  if [ X"--boot_reason_enum" = X"${1}" ]; then
1202    shift
1203    local sys_expected="${1}"
1204    shift
1205    local enum_expected="${1}"
1206    adb_su bootstat --boot_reason_enum="${sys_expected}" |
1207      (
1208        local retval=-1
1209        while read -r id match; do
1210          if [ ${retval} = -1 -a ${enum_expected} = ${id} ]; then
1211            retval=0
1212          fi
1213          if [ ${enum_expected} != ${id} ]; then
1214            echo "ERROR: ${enum_expected} ${sys_expected} got ${id} ${match}" >&2
1215            retval=1
1216          fi
1217        done
1218        exit ${retval}
1219      )
1220    return
1221  fi
1222  local sys_expected="${1}"
1223  shift
1224  local enum_expected="${1}"
1225  adb_su setprop sys.boot.reason "${sys_expected}" </dev/null
1226  adb_su bootstat --record_boot_reason </dev/null
1227  # Check values
1228  EXPECT_PROPERTY sys.boot.reason "${sys_expected}"
1229  local retval=${?}
1230  local result=`adb_su stat -c %Y /data/misc/bootstat/system_boot_reason </dev/null 2>/dev/null`
1231  [ "${enum_expected}" = "${result}" ] ||
1232    (
1233      [ -n "${result}" ] || result="<nothing>"
1234      echo "ERROR: ${enum_expected} ${sys_expected} got ${result}" >&2
1235      false
1236    ) ||
1237    retval=${?}
1238  return ${retval}
1239}
1240
1241[ "USAGE: filter_kBootReasonMap </dev/stdin >/dev/stdout
1242
1243convert any regex expressions into a series of non-regex test strings" ]
1244filter_kBootReasonMap() {
1245  while read -r id match; do
1246    case ${match} in
1247      'reboot,[empty]')
1248        echo ${id}          # matches b/c of special case
1249        echo ${id} reboot,y # matches b/c of regex
1250        echo 1 reboot,empty # negative test (ID for unknown is 1)
1251        ;;
1252      reboot)
1253        echo 1 reboog       # negative test (ID for unknown is 1)
1254        ;;
1255      'reboot,pmic_off_fault,.*')
1256        echo ${id} reboot,pmic_off_fault,hello,world
1257        echo ${id} reboot,pmic_off_fault,
1258        echo 1 reboot,pmic_off_fault
1259        ;;
1260    esac
1261    echo ${id} "${match}"   # matches b/c of exact
1262  done
1263}
1264
1265[ "USAGE: test_kBootReasonMap
1266
1267kBootReasonMap test
1268- (wait until screen is up, boot has completed)
1269- read bootstat for kBootReasonMap entries and test them all" ]
1270test_kBootReasonMap() {
1271  checkDebugBuild || return
1272  duration_test 15
1273  local tempfile="`mktemp`"
1274  local arg=--boot_reason_enum
1275  adb_su bootstat ${arg} </dev/null 2>/dev/null |
1276    filter_kBootReasonMap >${tempfile}
1277  if [ ! -s "${tempfile}" ]; then
1278    wait_for_screen
1279    arg=
1280    sed -n <${progpath}bootstat.cpp \
1281      '/kBootReasonMap = {/,/^};/s/.*{"\([^"]*\)", *\([0-9][0-9]*\)},.*/\2 \1/p' |
1282      sed 's/\\\\/\\/g' |
1283      filter_kBootReasonMap >${tempfile}
1284  fi
1285  T=`adb_date`
1286  retval=0
1287  while read -r enum string; do
1288    if [ X"${string}" != X"${string#*[[].[]]}" -o X"${string}" != X"${string#*\\.}" ]; then
1289      if [ 'reboot\.empty' != "${string}" ]; then
1290        echo "WARNING: regex snuck through filter_kBootReasonMap ${enum} ${string}" >&2
1291        enum=1
1292      fi
1293    fi
1294    run_kBootReasonMap ${arg} "${string}" "${enum}" </dev/null || retval=${?}
1295  done <${tempfile}
1296  rm ${tempfile}
1297  ( exit ${retval} )
1298  # See filter_kBootReasonMap() for negative tests and add them here too
1299  report_bootstat_logs -t${T} \
1300    '-bootstat: Service started: bootstat --boot_reason_enum=' \
1301    '-bootstat: Unknown boot reason: reboot,empty' \
1302    '-bootstat: Unknown boot reason: reboog' \
1303    '-bootstat: Unknown boot reason: reboot,pmic_off_fault'
1304}
1305
1306[ "USAGE: ${progname} [-s SERIAL] [tests]...
1307
1308Mainline executive to run the above tests" ]
1309
1310# Rudimentary argument parsing
1311
1312if [ ${#} -ge 2 -a X"-s" = X"${1}" ]; then
1313  export ANDROID_SERIAL="${2}"
1314  shift 2
1315fi
1316
1317# Helpful for debugging, allows us to import the functions.
1318if [ X"--macros" != X"${1}" ]; then
1319
1320  if [ X"--help" = X"${1}" -o X"-h" = X"${1}" -o X"-?" = X"${1}" ]; then
1321    echo "USAGE: ${progname} [-s SERIAL] [tests]..."
1322    echo tests - `sed -n 's/^test_\([^ ()]*\)() {/\1/p' $0 </dev/null`
1323    exit 0
1324  fi
1325
1326  if [ X"--stop" = X"${1}" ]; then
1327    STOP_ON_FAILURE=true
1328    shift
1329  fi
1330
1331  # Check if all conditions for the script are valid
1332
1333  if [ -z "${ANDROID_SERIAL}" ]; then
1334    ndev=`(
1335        adb devices | grep -v 'List of devices attached'
1336        fastboot devices
1337      ) |
1338      grep -v "^[${SPACE}${TAB}]*\$" |
1339      wc -l`
1340    if [ ${ndev} -gt 1 ]; then
1341      echo "ERROR: no target device specified, ${ndev} connected" >&2
1342      echo "${RED}[  FAILED  ]${NORMAL}"
1343      exit 1
1344    fi
1345    echo "WARNING: no target device specified" >&2
1346  fi
1347
1348  ret=0
1349
1350  # Test Series
1351  if [ X"all" = X"${*}" ]; then
1352    # automagically pick up all test_<function>s.
1353    eval set nothing `sed -n 's/^test_\([^ ()]*\)() {/\1/p' $0 </dev/null`
1354    if [ X"nothing" = X"${1}" ]; then
1355      shift 1
1356    fi
1357  fi
1358  if [ -z "$*" ]; then
1359    # automagically pick up all test_<function>, except test_optional_<function>.
1360    eval set nothing `sed -n 's/^test_\([^ ()]*\)() {/\1/p' $0 </dev/null |
1361                              grep -v '^optional_'`
1362    if [ -z "${2}" ]; then
1363      # Hard coded should shell fail to find them (search/permission issues)
1364      eval set properties ota cold factory_reset hard battery unknown \
1365               kernel_panic kernel_panic_subreason kernel_panic_hung warm \
1366               thermal_shutdown userrequested_shutdown shell_reboot adb_reboot \
1367               Its_Just_So_Hard_reboot bootloader_normal bootloader_watchdog \
1368               bootloader_kernel_panic bootloader_oem_powerkey \
1369               bootloader_wdog_reset bootloader_cold bootloader_warm \
1370               bootloader_hard bootloader_recovery kBootReasonMap
1371    fi
1372    if [ X"nothing" = X"${1}" ]; then
1373      shift 1
1374    fi
1375  fi
1376  echo "INFO: selected test(s): ${@}" >&2
1377  echo
1378  # Prepare device
1379  setBootloaderBootReason 2>/dev/null
1380  # Start pouring through the tests.
1381  failures=
1382  successes=
1383  for t in "${@}"; do
1384    wrap_test ${t}
1385    retval=${?}
1386    if [ 0 = ${retval} ]; then
1387      if [ -z "${successes}" ]; then
1388        successes=${t}
1389      else
1390        successes="${successes} ${t}"
1391      fi
1392    else
1393      ret=${retval}
1394      if [ -z "${failures}" ]; then
1395        failures=${t}
1396      else
1397        failures="${failures} ${t}"
1398      fi
1399    fi
1400    echo
1401  done
1402
1403  if [ -n "${successes}" ]; then
1404    echo "${GREEN}[  PASSED  ]${NORMAL} ${successes}"
1405  fi
1406  if [ -n "${failures}" ]; then
1407    echo "${RED}[  FAILED  ]${NORMAL} ${failures}"
1408  fi
1409  exit ${ret}
1410
1411fi
1412