Merge "init: cleanup exit() uses"
diff --git a/adb/set_verity_enable_state_service.cpp b/adb/set_verity_enable_state_service.cpp
index 253d14a..49e0363 100644
--- a/adb/set_verity_enable_state_service.cpp
+++ b/adb/set_verity_enable_state_service.cpp
@@ -93,21 +93,9 @@
/* Helper function to get A/B suffix, if any. If the device isn't
* using A/B the empty string is returned. Otherwise either "_a",
* "_b", ... is returned.
- *
- * Note that since sometime in O androidboot.slot_suffix is deprecated
- * and androidboot.slot should be used instead. Since bootloaders may
- * be out of sync with the OS, we check both and for extra safety
- * prepend a leading underscore if there isn't one already.
*/
static std::string get_ab_suffix() {
- std::string ab_suffix = android::base::GetProperty("ro.boot.slot_suffix", "");
- if (ab_suffix == "") {
- ab_suffix = android::base::GetProperty("ro.boot.slot", "");
- }
- if (ab_suffix.size() > 0 && ab_suffix[0] != '_') {
- ab_suffix = std::string("_") + ab_suffix;
- }
- return ab_suffix;
+ return android::base::GetProperty("ro.boot.slot_suffix", "");
}
/* Use AVB to turn verity on/off */
diff --git a/base/include/android-base/logging.h b/base/include/android-base/logging.h
index 548b286..f93c696 100644
--- a/base/include/android-base/logging.h
+++ b/base/include/android-base/logging.h
@@ -438,4 +438,36 @@
} // namespace base
} // namespace android
+namespace std {
+
+// Emit a warning of ostream<< with std::string*. The intention was most likely to print *string.
+//
+// Note: for this to work, we need to have this in a namespace.
+// Note: lots of ifdef magic to make this work with Clang (platform) vs GCC (windows tools)
+// Note: using diagnose_if(true) under Clang and nothing under GCC/mingw as there is no common
+// attribute support.
+// Note: using a pragma because "-Wgcc-compat" (included in "-Weverything") complains about
+// diagnose_if.
+// Note: to print the pointer, use "<< static_cast<const void*>(string_pointer)" instead.
+// Note: a not-recommended alternative is to let Clang ignore the warning by adding
+// -Wno-user-defined-warnings to CPPFLAGS.
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgcc-compat"
+#define OSTREAM_STRING_POINTER_USAGE_WARNING \
+ __attribute__((diagnose_if(true, "Unexpected logging of string pointer", "warning")))
+#else
+#define OSTREAM_STRING_POINTER_USAGE_WARNING /* empty */
+#endif
+inline std::ostream& operator<<(std::ostream& stream, const std::string* string_pointer)
+ OSTREAM_STRING_POINTER_USAGE_WARNING {
+ return stream << static_cast<const void*>(string_pointer);
+}
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+#undef OSTREAM_STRING_POINTER_USAGE_WARNING
+
+} // namespace std
+
#endif // ANDROID_BASE_LOGGING_H
diff --git a/bootstat/boot_event_record_store.cpp b/bootstat/boot_event_record_store.cpp
index 99d9405..e2a4b04 100644
--- a/bootstat/boot_event_record_store.cpp
+++ b/bootstat/boot_event_record_store.cpp
@@ -58,16 +58,15 @@
}
void BootEventRecordStore::AddBootEvent(const std::string& event) {
- auto uptime = std::chrono::duration_cast<std::chrono::seconds>(
- android::base::boot_clock::now().time_since_epoch());
- AddBootEventWithValue(event, uptime.count());
+ auto uptime = std::chrono::duration_cast<std::chrono::seconds>(
+ android::base::boot_clock::now().time_since_epoch());
+ AddBootEventWithValue(event, uptime.count());
}
// The implementation of AddBootEventValue makes use of the mtime file
// attribute to store the value associated with a boot event in order to
// optimize on-disk size requirements and small-file thrashing.
-void BootEventRecordStore::AddBootEventWithValue(
- const std::string& event, int32_t value) {
+void BootEventRecordStore::AddBootEventWithValue(const std::string& event, int32_t value) {
std::string record_path = GetBootEventPath(event);
int record_fd = creat(record_path.c_str(), S_IRUSR | S_IWUSR);
if (record_fd == -1) {
@@ -96,8 +95,7 @@
close(record_fd);
}
-bool BootEventRecordStore::GetBootEvent(
- const std::string& event, BootEventRecord* record) const {
+bool BootEventRecordStore::GetBootEvent(const std::string& event, BootEventRecord* record) const {
CHECK_NE(static_cast<BootEventRecord*>(nullptr), record);
CHECK(!event.empty());
@@ -112,8 +110,7 @@
return true;
}
-std::vector<BootEventRecordStore::BootEventRecord> BootEventRecordStore::
- GetAllBootEvents() const {
+std::vector<BootEventRecordStore::BootEventRecord> BootEventRecordStore::GetAllBootEvents() const {
std::vector<BootEventRecord> events;
std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(store_path_.c_str()), closedir);
@@ -147,8 +144,7 @@
store_path_ = path;
}
-std::string BootEventRecordStore::GetBootEventPath(
- const std::string& event) const {
+std::string BootEventRecordStore::GetBootEventPath(const std::string& event) const {
DCHECK_EQ('/', store_path_.back());
return store_path_ + event;
}
diff --git a/bootstat/boot_event_record_store.h b/bootstat/boot_event_record_store.h
index a2b8318..f872c85 100644
--- a/bootstat/boot_event_record_store.h
+++ b/bootstat/boot_event_record_store.h
@@ -17,12 +17,12 @@
#ifndef BOOT_EVENT_RECORD_STORE_H_
#define BOOT_EVENT_RECORD_STORE_H_
+#include <android-base/macros.h>
+#include <gtest/gtest_prod.h>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
-#include <android-base/macros.h>
-#include <gtest/gtest_prod.h>
// BootEventRecordStore manages the persistence of boot events to the record
// store and the retrieval of all boot event records from the store.
diff --git a/bootstat/boot_event_record_store_test.cpp b/bootstat/boot_event_record_store_test.cpp
index d98169b..4b7ab36 100644
--- a/bootstat/boot_event_record_store_test.cpp
+++ b/bootstat/boot_event_record_store_test.cpp
@@ -94,20 +94,16 @@
// Returns the time in seconds since boot.
time_t GetUptimeSeconds() {
- return std::chrono::duration_cast<std::chrono::seconds>(
- android::base::boot_clock::now().time_since_epoch())
- .count();
+ return std::chrono::duration_cast<std::chrono::seconds>(
+ android::base::boot_clock::now().time_since_epoch())
+ .count();
}
class BootEventRecordStoreTest : public ::testing::Test {
public:
- BootEventRecordStoreTest() {
- store_path_ = std::string(store_dir_.path) + "/";
- }
+ BootEventRecordStoreTest() { store_path_ = std::string(store_dir_.path) + "/"; }
- const std::string& GetStorePathForTesting() const {
- return store_path_;
- }
+ const std::string& GetStorePathForTesting() const { return store_path_; }
private:
void TearDown() {
@@ -159,9 +155,7 @@
store.AddBootEvent("triassic");
const std::string EXPECTED_NAMES[] = {
- "cretaceous",
- "jurassic",
- "triassic",
+ "cretaceous", "jurassic", "triassic",
};
auto events = store.GetAllBootEvents();
diff --git a/bootstat/boot_reason_test.sh b/bootstat/boot_reason_test.sh
index 4314271..b76011a 100755
--- a/bootstat/boot_reason_test.sh
+++ b/bootstat/boot_reason_test.sh
@@ -370,6 +370,7 @@
fast and fake (touch build_date on device to make it different)" ]
test_optional_ota() {
echo "INFO: expected duration of ${TEST} test about 45 seconds" >&2
+ echo "WARNING: ${TEST} requires userdebug build" >&2
adb shell su root touch /data/misc/bootstat/build_date >&2
adb reboot ota
wait_for_screen
@@ -425,6 +426,7 @@
a _real_ factory_reset is too destructive to the device." ]
test_factory_reset() {
echo "INFO: expected duration of ${TEST} test roughly 45 seconds" >&2
+ echo "WARNING: ${TEST} requires userdebug build" >&2
adb shell su root rm /data/misc/bootstat/build_date >&2
adb reboot >&2
wait_for_screen
@@ -479,7 +481,8 @@
[ "USAGE: test_battery
battery test (trick):
-- echo healthd: battery l=2 | adb shell su root tee /dev/kmsg ; adb reboot cold
+- echo healthd: battery l=2<space> | adb shell su root tee /dev/kmsg
+- adb reboot cold
- (wait until screen is up, boot has completed)
- adb shell getprop sys.boot.reason
- NB: should report reboot,battery, unless healthd managed to log
@@ -491,7 +494,7 @@
+ setprop logd.kernel false
+ rm /sys/fs/pstore/console-ramoops
+ rm /sys/fs/pstore/console-ramoops-0
- + write /dev/kmsg \"healthd: battery l=2
+ + write /dev/kmsg \"healthd: battery l=2${SPACE}
+\"
- adb reboot fs
- (wait until screen is up, boot has completed)
@@ -500,9 +503,10 @@
- (replace set logd.kernel true to the above, and retry test)" ]
test_battery() {
echo "INFO: expected duration of ${TEST} test roughly two minutes" >&2
+ echo "WARNING: ${TEST} requires userdebug build" >&2
# Send it _many_ times to combat devices with flakey pstore
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
- echo healthd: battery l=2 | adb shell su root tee /dev/kmsg >/dev/null
+ echo 'healthd: battery l=2 ' | adb shell su root tee /dev/kmsg >/dev/null
done
adb reboot cold >&2
adb wait-for-device
@@ -512,11 +516,11 @@
/proc/fs/pstore/console-ramoops-0 2>/dev/null |
grep 'healthd: battery l=' |
tail -1 |
- grep 'healthd: battery l=2' >/dev/null || (
+ grep 'healthd: battery l=2 ' >/dev/null || (
if ! EXPECT_PROPERTY sys.boot.reason reboot,battery >/dev/null 2>/dev/null; then
# retry
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
- echo healthd: battery l=2 | adb shell su root tee /dev/kmsg >/dev/null
+ echo 'healthd: battery l=2 ' | adb shell su root tee /dev/kmsg >/dev/null
done
adb reboot cold >&2
adb wait-for-device
@@ -550,6 +554,7 @@
- NB: should report kernel_panic,sysrq" ]
test_kernel_panic() {
echo "INFO: expected duration of ${TEST} test > 2 minutes" >&2
+ echo "WARNING: ${TEST} requires userdebug build" >&2
echo c | adb shell su root tee /proc/sysrq-trigger >/dev/null
wait_for_screen
EXPECT_PROPERTY sys.boot.reason kernel_panic,sysrq
@@ -640,6 +645,26 @@
report_bootstat_logs reboot,adb
}
+[ "USAGE: test_Its_Just_So_Hard_reboot
+
+Its Just So Hard reboot test:
+- adb shell reboot 'Its Just So Hard'
+- (wait until screen is up, boot has completed)
+- adb shell getprop sys.boot.reason
+- NB: should report reboot,its_just_so_hard
+- NB: expect log \"... I bootstat: Unknown boot reason: reboot,its_just_so_hard\"" ]
+test_Its_Just_So_Hard_reboot() {
+ echo "INFO: expected duration of ${TEST} test roughly 45 seconds" >&2
+ echo "INFO: ${TEST} cleanup requires userdebug build" >&2
+ adb shell 'reboot "Its Just So Hard"'
+ wait_for_screen
+ EXPECT_PROPERTY sys.boot.reason reboot,its_just_so_hard
+ EXPECT_PROPERTY persist.sys.boot.reason "reboot,Its Just So Hard"
+ adb shell su root setprop persist.sys.boot.reason reboot,its_just_so_hard
+ EXPECT_PROPERTY persist.sys.boot.reason reboot,its_just_so_hard
+ report_bootstat_logs reboot,its_just_so_hard
+}
+
[ "USAGE: ${0##*/} [-s SERIAL] [tests]
Mainline executive to run the above tests" ]
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index e7f9c11..7c0b15e 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -19,8 +19,8 @@
// uploaded to Android log storage via Tron.
#include <getopt.h>
-#include <unistd.h>
#include <sys/klog.h>
+#include <unistd.h>
#include <chrono>
#include <cmath>
@@ -61,8 +61,7 @@
// Records the named boot |event| to the record store. If |value| is non-empty
// and is a proper string representation of an integer value, the converted
// integer value is associated with the boot event.
-void RecordBootEventFromCommandLine(
- const std::string& event, const std::string& value_str) {
+void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
BootEventRecordStore boot_event_store;
if (!value_str.empty()) {
int32_t value = 0;
@@ -85,7 +84,7 @@
}
}
-void ShowHelp(const char *cmd) {
+void ShowHelp(const char* cmd) {
fprintf(stderr, "Usage: %s [options]\n", cmd);
fprintf(stderr,
"options include:\n"
@@ -101,7 +100,7 @@
// Constructs a readable, printable string from the givencommand line
// arguments.
-std::string GetCommandLine(int argc, char **argv) {
+std::string GetCommandLine(int argc, char** argv) {
std::string cmd;
for (int i = 0; i < argc; ++i) {
cmd += argv[i];
@@ -137,73 +136,74 @@
// the boot_reason metric may refer to this mapping to discern the histogram
// values.
const std::map<std::string, int32_t> kBootReasonMap = {
- {"unknown", kUnknownBootReason},
- {"normal", 2},
- {"recovery", 3},
- {"reboot", 4},
- {"PowerKey", 5},
- {"hard_reset", 6},
- {"kernel_panic", 7},
- {"rpm_err", 8},
- {"hw_reset", 9},
- {"tz_err", 10},
- {"adsp_err", 11},
- {"modem_err", 12},
- {"mba_err", 13},
- {"Watchdog", 14},
- {"Panic", 15},
- {"power_key", 16},
- {"power_on", 17},
- {"Reboot", 18},
- {"rtc", 19},
- {"edl", 20},
- {"oem_pon1", 21},
- {"oem_powerkey", 22},
- {"oem_unknown_reset", 23},
- {"srto: HWWDT reset SC", 24},
- {"srto: HWWDT reset platform", 25},
- {"srto: bootloader", 26},
- {"srto: kernel panic", 27},
- {"srto: kernel watchdog reset", 28},
- {"srto: normal", 29},
- {"srto: reboot", 30},
- {"srto: reboot-bootloader", 31},
- {"srto: security watchdog reset", 32},
- {"srto: wakesrc", 33},
- {"srto: watchdog", 34},
- {"srto:1-1", 35},
- {"srto:omap_hsmm", 36},
- {"srto:phy0", 37},
- {"srto:rtc0", 38},
- {"srto:touchpad", 39},
- {"watchdog", 40},
- {"watchdogr", 41},
- {"wdog_bark", 42},
- {"wdog_bite", 43},
- {"wdog_reset", 44},
- {"shutdown,", 45}, // Trailing comma is intentional.
- {"shutdown,userrequested", 46},
- {"reboot,bootloader", 47},
- {"reboot,cold", 48},
- {"reboot,recovery", 49},
- {"thermal_shutdown", 50},
- {"s3_wakeup", 51},
- {"kernel_panic,sysrq", 52},
- {"kernel_panic,NULL", 53},
- {"kernel_panic,BUG", 54},
- {"bootloader", 55},
- {"cold", 56},
- {"hard", 57},
- {"warm", 58},
- {"recovery", 59},
- {"thermal-shutdown", 60},
- {"shutdown,thermal", 61},
- {"shutdown,battery", 62},
- {"reboot,ota", 63},
- {"reboot,factory_reset", 64},
- {"reboot,", 65},
- {"reboot,shell", 66},
- {"reboot,adb", 67},
+ {"unknown", kUnknownBootReason},
+ {"normal", 2},
+ {"recovery", 3},
+ {"reboot", 4},
+ {"PowerKey", 5},
+ {"hard_reset", 6},
+ {"kernel_panic", 7},
+ {"rpm_err", 8},
+ {"hw_reset", 9},
+ {"tz_err", 10},
+ {"adsp_err", 11},
+ {"modem_err", 12},
+ {"mba_err", 13},
+ {"Watchdog", 14},
+ {"Panic", 15},
+ {"power_key", 16},
+ {"power_on", 17},
+ {"Reboot", 18},
+ {"rtc", 19},
+ {"edl", 20},
+ {"oem_pon1", 21},
+ {"oem_powerkey", 22},
+ {"oem_unknown_reset", 23},
+ {"srto: HWWDT reset SC", 24},
+ {"srto: HWWDT reset platform", 25},
+ {"srto: bootloader", 26},
+ {"srto: kernel panic", 27},
+ {"srto: kernel watchdog reset", 28},
+ {"srto: normal", 29},
+ {"srto: reboot", 30},
+ {"srto: reboot-bootloader", 31},
+ {"srto: security watchdog reset", 32},
+ {"srto: wakesrc", 33},
+ {"srto: watchdog", 34},
+ {"srto:1-1", 35},
+ {"srto:omap_hsmm", 36},
+ {"srto:phy0", 37},
+ {"srto:rtc0", 38},
+ {"srto:touchpad", 39},
+ {"watchdog", 40},
+ {"watchdogr", 41},
+ {"wdog_bark", 42},
+ {"wdog_bite", 43},
+ {"wdog_reset", 44},
+ {"shutdown,", 45}, // Trailing comma is intentional.
+ {"shutdown,userrequested", 46},
+ {"reboot,bootloader", 47},
+ {"reboot,cold", 48},
+ {"reboot,recovery", 49},
+ {"thermal_shutdown", 50},
+ {"s3_wakeup", 51},
+ {"kernel_panic,sysrq", 52},
+ {"kernel_panic,NULL", 53},
+ {"kernel_panic,BUG", 54},
+ {"bootloader", 55},
+ {"cold", 56},
+ {"hard", 57},
+ {"warm", 58},
+ {"recovery", 59},
+ {"thermal-shutdown", 60},
+ {"shutdown,thermal", 61},
+ {"shutdown,battery", 62},
+ {"reboot,ota", 63},
+ {"reboot,factory_reset", 64},
+ {"reboot,", 65},
+ {"reboot,shell", 66},
+ {"reboot,adb", 67},
+ {"reboot,userrequested", 68},
};
// Converts a string value representing the reason the system booted to an
@@ -221,23 +221,25 @@
// Canonical list of supported primary reboot reasons.
const std::vector<const std::string> knownReasons = {
- // kernel
- "watchdog",
- "kernel_panic",
- // strong
- "recovery", // Should not happen from ro.boot.bootreason
- "bootloader", // Should not happen from ro.boot.bootreason
- // blunt
- "cold",
- "hard",
- "warm",
- "shutdown", // Can not happen from ro.boot.bootreason
- "reboot", // Default catch-all for anything unknown
+ // clang-format off
+ // kernel
+ "watchdog",
+ "kernel_panic",
+ // strong
+ "recovery", // Should not happen from ro.boot.bootreason
+ "bootloader", // Should not happen from ro.boot.bootreason
+ // blunt
+ "cold",
+ "hard",
+ "warm",
+ "shutdown", // Can not happen from ro.boot.bootreason
+ "reboot", // Default catch-all for anything unknown
+ // clang-format on
};
// Returns true if the supplied reason prefix is considered detailed enough.
bool isStrongRebootReason(const std::string& r) {
- for (auto &s : knownReasons) {
+ for (auto& s : knownReasons) {
if (s == "cold") break;
// Prefix defined as terminated by a nul or comma (,).
if (android::base::StartsWith(r, s.c_str()) &&
@@ -250,7 +252,7 @@
// Returns true if the supplied reason prefix is associated with the kernel.
bool isKernelRebootReason(const std::string& r) {
- for (auto &s : knownReasons) {
+ for (auto& s : knownReasons) {
if (s == "recovery") break;
// Prefix defined as terminated by a nul or comma (,).
if (android::base::StartsWith(r, s.c_str()) &&
@@ -263,7 +265,7 @@
// Returns true if the supplied reason prefix is considered known.
bool isKnownRebootReason(const std::string& r) {
- for (auto &s : knownReasons) {
+ for (auto& s : knownReasons) {
// Prefix defined as terminated by a nul or comma (,).
if (android::base::StartsWith(r, s.c_str()) &&
((r.length() == s.length()) || (r[s.length()] == ','))) {
@@ -277,7 +279,7 @@
bool isBluntRebootReason(const std::string& r) {
if (isStrongRebootReason(r)) return false;
- if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
+ if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
size_t pos = 0;
while ((pos = r.find(',', pos)) != std::string::npos) {
@@ -285,17 +287,47 @@
std::string next(r.substr(pos));
if (next.length() == 0) break;
if (next[0] == ',') continue;
- if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
- if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
+ if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
+ if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
}
return true;
}
+bool readPstoreConsole(std::string& console) {
+ if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
+ return true;
+ }
+ return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
+}
+
+bool addKernelPanicSubReason(const std::string& console, std::string& ret) {
+ // Check for kernel panic types to refine information
+ if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
+ // Can not happen, except on userdebug, during testing/debugging.
+ ret = "kernel_panic,sysrq";
+ return true;
+ }
+ if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
+ std::string::npos) {
+ ret = "kernel_panic,NULL";
+ return true;
+ }
+ if (console.rfind("Kernel BUG at ") != std::string::npos) {
+ ret = "kernel_panic,BUG";
+ return true;
+ }
+ return false;
+}
+
// std::transform Helper callback functions:
// Converts a string value representing the reason the system booted to a
// string complying with Android system standard reason.
-char tounderline(char c) { return ::isblank(c) ? '_' : c; }
-char toprintable(char c) { return ::isprint(c) ? c : '?'; }
+char tounderline(char c) {
+ return ::isblank(c) ? '_' : c;
+}
+char toprintable(char c) {
+ return ::isprint(c) ? c : '?';
+}
const char system_reboot_reason_property[] = "sys.boot.reason";
const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
@@ -303,6 +335,8 @@
// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
std::string BootReasonStrToReason(const std::string& boot_reason) {
+ static const size_t max_reason_length = 256;
+
std::string ret(GetProperty(system_reboot_reason_property));
std::string reason(boot_reason);
// If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
@@ -319,9 +353,9 @@
if (ret == "") {
// Is the bootloader boot reason ro.boot.bootreason known?
std::vector<std::string> words(android::base::Split(reason, ",_-"));
- for (auto &s : knownReasons) {
+ for (auto& s : knownReasons) {
std::string blunt;
- for (auto &r : words) {
+ for (auto& r : words) {
if (r == s) {
if (isBluntRebootReason(s)) {
blunt = s;
@@ -342,17 +376,17 @@
// sense. In an ideal world, we would require those bootloaders
// to behave and follow our standards.
static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
- {"watchdog", "wdog"},
- {"cold,powerkey", "powerkey"},
- {"kernel_panic", "panic"},
- {"shutdown,thermal", "thermal"},
- {"warm,s3_wakeup", "s3_wakeup"},
- {"hard,hw_reset", "hw_reset"},
- {"bootloader", ""},
+ {"watchdog", "wdog"},
+ {"cold,powerkey", "powerkey"},
+ {"kernel_panic", "panic"},
+ {"shutdown,thermal", "thermal"},
+ {"warm,s3_wakeup", "s3_wakeup"},
+ {"hard,hw_reset", "hw_reset"},
+ {"bootloader", ""},
};
// Either the primary or alias is found _somewhere_ in the reason string.
- for (auto &s : aliasReasons) {
+ for (auto& s : aliasReasons) {
if (reason.find(s.first) != std::string::npos) {
ret = s.first;
break;
@@ -371,55 +405,57 @@
}
}
- // Check the other reason resources if the reason is still blunt.
- if (isBluntRebootReason(ret)) {
+ if (ret == "kernel_panic") {
// Check to see if last klog has some refinement hints.
std::string content;
- if (!android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0",
- &content)) {
- android::base::ReadFileToString("/sys/fs/pstore/console-ramoops",
- &content);
+ if (readPstoreConsole(content)) {
+ addKernelPanicSubReason(content, ret);
}
+ } else if (isBluntRebootReason(ret)) {
+ // Check the other available reason resources if the reason is still blunt.
- // The toybox reboot command used directly (unlikely)? But also
- // catches init's response to the Android's more controlled reboot command.
- if (content.rfind("reboot: Power down") != std::string::npos) {
- ret = "shutdown"; // Still too blunt, but more accurate.
- // ToDo: init should record the shutdown reason to kernel messages ala:
- // init: shutdown system with command 'last_reboot_reason'
- // so that if pstore has persistence we can get some details
- // that could be missing in last_reboot_reason_property.
- }
+ // Check to see if last klog has some refinement hints.
+ std::string content;
+ if (readPstoreConsole(content)) {
+ // The toybox reboot command used directly (unlikely)? But also
+ // catches init's response to Android's more controlled reboot command.
+ if (content.rfind("reboot: Power down") != std::string::npos) {
+ ret = "shutdown"; // Still too blunt, but more accurate.
+ // ToDo: init should record the shutdown reason to kernel messages ala:
+ // init: shutdown system with command 'last_reboot_reason'
+ // so that if pstore has persistence we can get some details
+ // that could be missing in last_reboot_reason_property.
+ }
- static const char cmd[] = "reboot: Restarting system with command '";
- size_t pos = content.rfind(cmd);
- if (pos != std::string::npos) {
- pos += strlen(cmd);
- std::string subReason(content.substr(pos));
- pos = subReason.find('\'');
- if (pos != std::string::npos) subReason.erase(pos);
- if (subReason != "") { // Will not land "reboot" as that is too blunt.
- if (isKernelRebootReason(subReason)) {
- ret = "reboot," + subReason; // User space can't talk kernel reasons.
- } else {
- ret = subReason;
+ static const char cmd[] = "reboot: Restarting system with command '";
+ size_t pos = content.rfind(cmd);
+ if (pos != std::string::npos) {
+ pos += strlen(cmd);
+ std::string subReason(content.substr(pos, max_reason_length));
+ for (pos = 0; pos < subReason.length(); ++pos) {
+ char c = tounderline(subReason[pos]);
+ if (!::isprint(c) || (c == '\'')) {
+ subReason.erase(pos);
+ break;
+ }
+ subReason[pos] = ::tolower(c);
+ }
+ if (subReason != "") { // Will not land "reboot" as that is too blunt.
+ if (isKernelRebootReason(subReason)) {
+ ret = "reboot," + subReason; // User space can't talk kernel reasons.
+ } else {
+ ret = subReason;
+ }
}
}
- }
- // Check for kernel panics, but allowed to override reboot command.
- if (content.rfind("sysrq: SysRq : Trigger a crash") != std::string::npos) {
- // Can not happen, except on userdebug, during testing/debugging.
- ret = "kernel_panic,sysrq";
- } else if (content.rfind(
- "Unable to handle kernel NULL pointer dereference at virtual address")
- != std::string::npos) {
- ret = "kernel_panic,NULL";
- } else if (content.rfind("Kernel BUG at ") != std::string::npos) {
- ret = "kernel_panic,BUG";
- } else if ((content.rfind("Power held for ") != std::string::npos) ||
- (content.rfind("charger: [") != std::string::npos)) {
- ret = "cold";
+ // Check for kernel panics, allowed to override reboot command.
+ if (!addKernelPanicSubReason(content, ret) &&
+ // check for long-press power down
+ ((content.rfind("Power held for ") != std::string::npos) ||
+ (content.rfind("charger: [") != std::string::npos))) {
+ ret = "cold";
+ }
}
// The following battery test should migrate to a default system health HAL
@@ -431,23 +467,30 @@
if (isBluntRebootReason(ret)) {
// Heuristic to determine if shutdown possibly because of a dead battery?
// Really a hail-mary pass to find it in last klog content ...
- static const int battery_dead_threshold = 2; // percent
+ static const int battery_dead_threshold = 2; // percent
static const char battery[] = "healthd: battery l=";
- pos = content.rfind(battery); // last one
+ size_t pos = content.rfind(battery); // last one
+ std::string digits;
if (pos != std::string::npos) {
- int level = atoi(content.substr(pos + strlen(battery)).c_str());
+ digits = content.substr(pos + strlen(battery));
+ }
+ char* endptr = NULL;
+ unsigned long long level = strtoull(digits.c_str(), &endptr, 10);
+ if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
LOG(INFO) << "Battery level at shutdown " << level << "%";
if (level <= battery_dead_threshold) {
ret = "shutdown,battery";
}
- } else { // Most likely
+ } else { // Most likely
+ digits = ""; // reset digits
+
// Content buffer no longer will have console data. Beware if more
// checks added below, that depend on parsing console content.
content = "";
LOG(DEBUG) << "Can not find last low battery in last console messages";
android_logcat_context ctx = create_android_logcat();
- FILE *fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
+ FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
if (fp != nullptr) {
android::base::ReadFdToString(fileno(fp), &content);
}
@@ -460,7 +503,7 @@
// Service logd.klog not running, go to smaller buffer in the kernel.
int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
if (rc > 0) {
- ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
+ ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
std::unique_ptr<char[]> buf(new char[len]);
rc = klogctl(KLOG_READ_ALL, buf.get(), len);
if (rc < len) {
@@ -472,10 +515,13 @@
match = battery;
}
- pos = content.find(match); // The first one it finds.
+ pos = content.find(match); // The first one it finds.
if (pos != std::string::npos) {
- pos += strlen(match);
- int level = atoi(content.substr(pos).c_str());
+ digits = content.substr(pos + strlen(match));
+ }
+ endptr = NULL;
+ level = strtoull(digits.c_str(), &endptr, 10);
+ if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
LOG(INFO) << "Battery level at startup " << level << "%";
if (level <= battery_dead_threshold) {
ret = "shutdown,battery";
@@ -491,13 +537,17 @@
// Content buffer no longer will have console data. Beware if more
// checks added below, that depend on parsing console content.
content = GetProperty(last_reboot_reason_property);
+ // Cleanup last_boot_reason regarding acceptable character set
+ std::transform(content.begin(), content.end(), content.begin(), ::tolower);
+ std::transform(content.begin(), content.end(), content.begin(), tounderline);
+ std::transform(content.begin(), content.end(), content.begin(), toprintable);
// String is either "reboot,<reason>" or "shutdown,<reason>".
// We will set if default reasons, only override with detail if thermal.
if ((android::base::StartsWith(content, ret.c_str()) && (content[ret.length()] == ',')) ||
!isBluntRebootReason(content)) {
// Ok, we want it, let's squash it if secondReason is known.
- pos = content.find(',');
+ size_t pos = content.find(',');
if (pos != std::string::npos) {
++pos;
std::string secondReason(content.substr(pos));
@@ -558,7 +608,7 @@
if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
- LOG(INFO) << "Canonical boot reason: " << "reboot,factory_reset";
+ LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
SetProperty(system_reboot_reason_property, "reboot,factory_reset");
if (GetProperty(bootloader_reboot_reason_property) == "") {
SetProperty(bootloader_reboot_reason_property, "reboot,factory_reset");
@@ -566,7 +616,7 @@
} else if (build_date != record.second) {
boot_complete_prefix = "ota_" + boot_complete_prefix;
boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
- LOG(INFO) << "Canonical boot reason: " << "reboot,ota";
+ LOG(INFO) << "Canonical boot reason: reboot,ota";
SetProperty(system_reboot_reason_property, "reboot,ota");
if (GetProperty(bootloader_reboot_reason_property) == "") {
SetProperty(bootloader_reboot_reason_property, "reboot,ota");
@@ -577,8 +627,7 @@
}
// Records the value of a given ro.boottime.init property in milliseconds.
-void RecordInitBootTimeProp(
- BootEventRecordStore* boot_event_store, const char* property) {
+void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
std::string value = GetProperty(property);
int32_t time_in_ms;
@@ -663,10 +712,8 @@
if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
time_t last_boot_time_utc = record.second;
- time_t time_since_last_boot = difftime(current_time_utc,
- last_boot_time_utc);
- boot_event_store.AddBootEventWithValue("time_since_last_boot",
- time_since_last_boot);
+ time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
+ boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
}
boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
@@ -692,8 +739,7 @@
boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
boot_complete.count());
} else {
- boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
- uptime.count());
+ boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
}
// Record the total time from device startup to boot complete, regardless of
@@ -716,8 +762,7 @@
void RecordBootReason() {
const std::string reason(GetProperty(bootloader_reboot_reason_property));
android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
- android::metricslogger::FIELD_PLATFORM_REASON,
- reason);
+ android::metricslogger::FIELD_PLATFORM_REASON, reason);
// Log the raw bootloader_boot_reason property value.
int32_t boot_reason = BootReasonStrToEnum(reason);
@@ -747,21 +792,20 @@
if (current_time_utc < 0) {
// UMA does not display negative values in buckets, so convert to positive.
- android::metricslogger::LogHistogram(
- "factory_reset_current_time_failure", std::abs(current_time_utc));
+ android::metricslogger::LogHistogram("factory_reset_current_time_failure",
+ std::abs(current_time_utc));
// Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
// is losing records somehow.
- boot_event_store.AddBootEventWithValue(
- "factory_reset_current_time_failure", std::abs(current_time_utc));
+ boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
+ std::abs(current_time_utc));
return;
} else {
android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
// Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
// is losing records somehow.
- boot_event_store.AddBootEventWithValue(
- "factory_reset_current_time", current_time_utc);
+ boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
}
// The factory_reset boot event does not exist after the device is reset, so
@@ -781,18 +825,15 @@
// Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
// is losing records somehow.
- boot_event_store.AddBootEventWithValue(
- "factory_reset_record_value", factory_reset_utc);
+ boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
- time_t time_since_factory_reset = difftime(current_time_utc,
- factory_reset_utc);
- boot_event_store.AddBootEventWithValue("time_since_factory_reset",
- time_since_factory_reset);
+ time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
+ boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
}
} // namespace
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
android::base::InitLogging(argv);
const std::string cmd_line = GetCommandLine(argc, argv);
@@ -804,15 +845,17 @@
static const char boot_reason_str[] = "record_boot_reason";
static const char factory_reset_str[] = "record_time_since_factory_reset";
static const struct option long_options[] = {
- { "help", no_argument, NULL, 'h' },
- { "log", no_argument, NULL, 'l' },
- { "print", no_argument, NULL, 'p' },
- { "record", required_argument, NULL, 'r' },
- { value_str, required_argument, NULL, 0 },
- { boot_complete_str, no_argument, NULL, 0 },
- { boot_reason_str, no_argument, NULL, 0 },
- { factory_reset_str, no_argument, NULL, 0 },
- { NULL, 0, NULL, 0 }
+ // clang-format off
+ { "help", no_argument, NULL, 'h' },
+ { "log", no_argument, NULL, 'l' },
+ { "print", no_argument, NULL, 'p' },
+ { "record", required_argument, NULL, 'r' },
+ { value_str, required_argument, NULL, 0 },
+ { boot_complete_str, no_argument, NULL, 0 },
+ { boot_reason_str, no_argument, NULL, 0 },
+ { factory_reset_str, no_argument, NULL, 0 },
+ { NULL, 0, NULL, 0 }
+ // clang-format on
};
std::string boot_event;
diff --git a/debuggerd/crasher/crasher.cpp b/debuggerd/crasher/crasher.cpp
index f57349b..e9a3ebd 100644
--- a/debuggerd/crasher/crasher.cpp
+++ b/debuggerd/crasher/crasher.cpp
@@ -114,6 +114,11 @@
return reinterpret_cast<uintptr_t>(result);
}
+noinline int crash_null() {
+ int (*null_func)() = nullptr;
+ return null_func();
+}
+
noinline int crash3(int a) {
*reinterpret_cast<int*>(0xdead) = a;
return a*4;
@@ -169,6 +174,7 @@
fprintf(stderr, " nostack crash with a NULL stack pointer\n");
fprintf(stderr, "\n");
fprintf(stderr, " heap-usage cause a libc abort by abusing a heap function\n");
+ fprintf(stderr, " call-null cause a crash by calling through a nullptr\n");
fprintf(stderr, " leak leak memory until we get OOM-killed\n");
fprintf(stderr, "\n");
fprintf(stderr, " abort call abort()\n");
@@ -239,6 +245,8 @@
crashnostack();
} else if (!strcasecmp(arg, "exit")) {
exit(1);
+ } else if (!strcasecmp(arg, "call-null")) {
+ return crash_null();
} else if (!strcasecmp(arg, "crash") || !strcmp(arg, "SIGSEGV")) {
return crash(42);
} else if (!strcasecmp(arg, "abort")) {
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index f5ecf48..418d092 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -413,15 +413,17 @@
}
ScopedBacktraceMapIteratorLock lock(map);
- _LOG(log, logtype::MAPS, "\n");
- if (!print_fault_address_marker) {
- _LOG(log, logtype::MAPS, "memory map:\n");
- } else {
- _LOG(log, logtype::MAPS, "memory map: (fault address prefixed with --->)\n");
+ _LOG(log, logtype::MAPS,
+ "\n"
+ "memory map (%zu entries):\n",
+ map->size());
+ if (print_fault_address_marker) {
if (map->begin() != map->end() && addr < map->begin()->start) {
_LOG(log, logtype::MAPS, "--->Fault address falls at %s before any mapped regions\n",
get_addr_string(addr).c_str());
print_fault_address_marker = false;
+ } else {
+ _LOG(log, logtype::MAPS, "(fault address prefixed with --->)\n");
}
}
diff --git a/debuggerd/tombstoned/intercept_manager.cpp b/debuggerd/tombstoned/intercept_manager.cpp
index 24960bc..c446dbb 100644
--- a/debuggerd/tombstoned/intercept_manager.cpp
+++ b/debuggerd/tombstoned/intercept_manager.cpp
@@ -185,8 +185,8 @@
}
InterceptManager::InterceptManager(event_base* base, int intercept_socket) : base(base) {
- this->listener = evconnlistener_new(base, intercept_accept_cb, this, -1, LEV_OPT_CLOSE_ON_FREE,
- intercept_socket);
+ this->listener = evconnlistener_new(base, intercept_accept_cb, this, LEV_OPT_CLOSE_ON_FREE,
+ /* backlog */ -1, intercept_socket);
}
bool InterceptManager::GetIntercept(pid_t pid, DebuggerdDumpType dump_type,
diff --git a/demangle/Android.bp b/demangle/Android.bp
index e55c886..89b8772 100644
--- a/demangle/Android.bp
+++ b/demangle/Android.bp
@@ -24,6 +24,12 @@
"-Werror",
"-Wextra",
],
+
+ target: {
+ linux_bionic: {
+ enabled: true,
+ },
+ },
}
cc_library {
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 41a5868..31c8803 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -782,11 +782,12 @@
* Returns the 1st matching fstab_rec that follows the start_rec.
* start_rec is the result of a previous search or NULL.
*/
-struct fstab_rec *fs_mgr_get_entry_for_mount_point_after(struct fstab_rec *start_rec, struct fstab *fstab, const char *path)
-{
+struct fstab_rec* fs_mgr_get_entry_for_mount_point_after(struct fstab_rec* start_rec,
+ struct fstab* fstab,
+ const std::string& path) {
int i;
if (!fstab) {
- return NULL;
+ return nullptr;
}
if (start_rec) {
@@ -799,14 +800,14 @@
} else {
i = 0;
}
+
for (; i < fstab->num_entries; i++) {
- int len = strlen(fstab->recs[i].mount_point);
- if (strncmp(path, fstab->recs[i].mount_point, len) == 0 &&
- (path[len] == '\0' || path[len] == '/')) {
+ if (fstab->recs[i].mount_point && path == fstab->recs[i].mount_point) {
return &fstab->recs[i];
}
}
- return NULL;
+
+ return nullptr;
}
/*
diff --git a/fs_mgr/fs_mgr_slotselect.cpp b/fs_mgr/fs_mgr_slotselect.cpp
index 9ca15e2..33fd562 100644
--- a/fs_mgr/fs_mgr_slotselect.cpp
+++ b/fs_mgr/fs_mgr_slotselect.cpp
@@ -21,19 +21,12 @@
#include "fs_mgr.h"
#include "fs_mgr_priv.h"
-// Returns "_a" or "_b" based on two possible values in kernel cmdline:
-// - androidboot.slot = a or b OR
-// - androidboot.slot_suffix = _a or _b
-// TODO: remove slot_suffix once it's deprecated.
+// Returns "_a" or "_b" based on androidboot.slot_suffix in kernel cmdline, or an empty string
+// if that parameter does not exist.
std::string fs_mgr_get_slot_suffix() {
- std::string slot;
std::string ab_suffix;
- if (fs_mgr_get_boot_config("slot", &slot)) {
- ab_suffix = "_" + slot;
- } else if (!fs_mgr_get_boot_config("slot_suffix", &ab_suffix)) {
- ab_suffix = "";
- }
+ fs_mgr_get_boot_config("slot_suffix", &ab_suffix);
return ab_suffix;
}
diff --git a/init/persistent_properties_test.cpp b/init/persistent_properties_test.cpp
index 875a4f3..872e9a1 100644
--- a/init/persistent_properties_test.cpp
+++ b/init/persistent_properties_test.cpp
@@ -52,7 +52,7 @@
entry.second == persistent_property_record.value();
});
ASSERT_TRUE(it != expected.end())
- << "Found unexpected proprety (" << persistent_property_record.name() << ", "
+ << "Found unexpected property (" << persistent_property_record.name() << ", "
<< persistent_property_record.value() << ")";
expected.erase(it);
}
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 049c952..18f493a 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -483,6 +483,8 @@
// Run fsck once the file system is remounted in read-only mode.
run_fsck = true;
} else if (cmd_params[1] == "thermal") {
+ // Turn off sources of heat immediately.
+ TurnOffBacklight();
// run_fsck is false to avoid delay
cmd = ANDROID_RB_THERMOFF;
}
diff --git a/libbacktrace/UnwindStack.cpp b/libbacktrace/UnwindStack.cpp
index 61812ab..b4481cc 100644
--- a/libbacktrace/UnwindStack.cpp
+++ b/libbacktrace/UnwindStack.cpp
@@ -68,6 +68,32 @@
return library == "libunwindstack.so" || library == "libbacktrace.so";
}
+static void SetFrameInfo(unwindstack::Regs* regs, unwindstack::MapInfo* map_info,
+ uint64_t adjusted_rel_pc, backtrace_frame_data_t* frame) {
+ // This will point to the adjusted absolute pc. regs->pc() is
+ // unaltered.
+ frame->pc = map_info->start + adjusted_rel_pc;
+ frame->sp = regs->sp();
+ frame->rel_pc = adjusted_rel_pc;
+ frame->stack_size = 0;
+
+ frame->map.start = map_info->start;
+ frame->map.end = map_info->end;
+ frame->map.offset = map_info->offset;
+ frame->map.flags = map_info->flags;
+ frame->map.name = map_info->name;
+
+ unwindstack::Elf* elf = map_info->elf;
+ frame->map.load_bias = elf->GetLoadBias();
+ uint64_t func_offset = 0;
+ if (elf->GetFunctionName(adjusted_rel_pc, &frame->func_name, &func_offset)) {
+ frame->func_name = demangle(frame->func_name.c_str());
+ } else {
+ frame->func_name = "";
+ }
+ frame->func_offset = func_offset;
+}
+
static bool Unwind(unwindstack::Regs* regs, BacktraceMap* back_map,
std::vector<backtrace_frame_data_t>* frames, size_t num_ignore_frames) {
UnwindStackMap* stack_map = reinterpret_cast<UnwindStackMap*>(back_map);
@@ -75,70 +101,96 @@
bool adjust_rel_pc = false;
size_t num_frames = 0;
frames->clear();
+ bool return_address_attempted = false;
+ auto process_memory = stack_map->process_memory();
while (num_frames < MAX_BACKTRACE_FRAMES) {
- if (regs->pc() == 0) {
- break;
- }
unwindstack::MapInfo* map_info = maps->Find(regs->pc());
+ bool stepped;
+ bool in_device_map = false;
if (map_info == nullptr) {
- break;
- }
-
- unwindstack::Elf* elf = map_info->GetElf(stack_map->process_memory(), true);
- uint64_t rel_pc = elf->GetRelPc(regs->pc(), map_info);
-
- bool skip_frame = num_frames == 0 && IsUnwindLibrary(map_info->name);
- if (num_ignore_frames == 0 && !skip_frame) {
- uint64_t adjusted_rel_pc = rel_pc;
- if (adjust_rel_pc) {
- adjusted_rel_pc = regs->GetAdjustedPc(rel_pc, elf);
- }
- frames->resize(num_frames + 1);
- backtrace_frame_data_t* frame = &frames->at(num_frames);
- frame->num = num_frames;
- // This will point to the adjusted absolute pc. regs->pc() is
- // unaltered.
- frame->pc = map_info->start + adjusted_rel_pc;
- frame->sp = regs->sp();
- frame->rel_pc = adjusted_rel_pc;
- frame->stack_size = 0;
-
- frame->map.start = map_info->start;
- frame->map.end = map_info->end;
- frame->map.offset = map_info->offset;
- frame->map.load_bias = elf->GetLoadBias();
- frame->map.flags = map_info->flags;
- frame->map.name = map_info->name;
-
- uint64_t func_offset = 0;
- if (elf->GetFunctionName(adjusted_rel_pc, &frame->func_name, &func_offset)) {
- frame->func_name = demangle(frame->func_name.c_str());
+ stepped = false;
+ if (num_ignore_frames == 0) {
+ frames->resize(num_frames + 1);
+ backtrace_frame_data_t* frame = &frames->at(num_frames);
+ frame->pc = regs->pc();
+ frame->sp = regs->sp();
+ frame->rel_pc = frame->pc;
+ num_frames++;
} else {
- frame->func_name = "";
+ num_ignore_frames--;
}
- frame->func_offset = func_offset;
- if (num_frames > 0) {
- // Set the stack size for the previous frame.
- backtrace_frame_data_t* prev = &frames->at(num_frames - 1);
- prev->stack_size = frame->sp - prev->sp;
+ } else {
+ unwindstack::Elf* elf = map_info->GetElf(process_memory, true);
+ uint64_t rel_pc = elf->GetRelPc(regs->pc(), map_info);
+
+ if (frames->size() != 0 || !IsUnwindLibrary(map_info->name)) {
+ if (num_ignore_frames == 0) {
+ uint64_t adjusted_rel_pc = rel_pc;
+ if (adjust_rel_pc) {
+ adjusted_rel_pc = regs->GetAdjustedPc(rel_pc, elf);
+ }
+
+ frames->resize(num_frames + 1);
+ backtrace_frame_data_t* frame = &frames->at(num_frames);
+ frame->num = num_frames;
+ SetFrameInfo(regs, map_info, adjusted_rel_pc, frame);
+
+ if (num_frames > 0) {
+ // Set the stack size for the previous frame.
+ backtrace_frame_data_t* prev = &frames->at(num_frames - 1);
+ prev->stack_size = frame->sp - prev->sp;
+ }
+ num_frames++;
+ } else {
+ num_ignore_frames--;
+ }
}
- num_frames++;
- } else if (!skip_frame && num_ignore_frames > 0) {
- num_ignore_frames--;
+
+ if (map_info->flags & PROT_DEVICE_MAP) {
+ // Do not stop here, fall through in case we are
+ // in the speculative unwind path and need to remove
+ // some of the speculative frames.
+ stepped = false;
+ in_device_map = true;
+ } else {
+ unwindstack::MapInfo* sp_info = maps->Find(regs->sp());
+ if (sp_info->flags & PROT_DEVICE_MAP) {
+ // Do not stop here, fall through in case we are
+ // in the speculative unwind path and need to remove
+ // some of the speculative frames.
+ stepped = false;
+ in_device_map = true;
+ } else {
+ bool finished;
+ stepped = elf->Step(rel_pc + map_info->elf_offset, regs, process_memory.get(), &finished);
+ if (stepped && finished) {
+ break;
+ }
+ }
+ }
}
adjust_rel_pc = true;
- // Do not unwind through a device map.
- if (map_info->flags & PROT_DEVICE_MAP) {
- break;
- }
- unwindstack::MapInfo* sp_info = maps->Find(regs->sp());
- if (sp_info->flags & PROT_DEVICE_MAP) {
- break;
- }
-
- if (!elf->Step(rel_pc + map_info->elf_offset, regs, stack_map->process_memory().get())) {
- break;
+ if (!stepped) {
+ if (return_address_attempted) {
+ // Remove the speculative frame.
+ if (frames->size() > 0) {
+ frames->pop_back();
+ }
+ break;
+ } else if (in_device_map) {
+ // Do not attempt any other unwinding, pc or sp is in a device
+ // map.
+ break;
+ } else {
+ // Stepping didn't work, try this secondary method.
+ if (!regs->SetPcFromReturnAddress(process_memory.get())) {
+ break;
+ }
+ return_address_attempted = true;
+ }
+ } else {
+ return_address_attempted = false;
}
}
diff --git a/libbacktrace/backtrace_test.cpp b/libbacktrace/backtrace_test.cpp
index 9fe2d1c..e5eb9e3 100644
--- a/libbacktrace/backtrace_test.cpp
+++ b/libbacktrace/backtrace_test.cpp
@@ -82,6 +82,14 @@
int32_t done;
};
+typedef Backtrace* (*create_func_t)(pid_t, pid_t, BacktraceMap*);
+typedef BacktraceMap* (*map_create_func_t)(pid_t, bool);
+
+static void VerifyLevelDump(Backtrace* backtrace, create_func_t create_func = nullptr,
+ map_create_func_t map_func = nullptr);
+static void VerifyMaxDump(Backtrace* backtrace, create_func_t create_func = nullptr,
+ map_create_func_t map_func = nullptr);
+
static uint64_t NanoTime() {
struct timespec t = { 0, 0 };
clock_gettime(CLOCK_MONOTONIC, &t);
@@ -147,7 +155,7 @@
return found;
}
-static void VerifyLevelDump(Backtrace* backtrace) {
+static void VerifyLevelDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
ASSERT_GT(backtrace->NumFrames(), static_cast<size_t>(0))
<< DumpFrames(backtrace);
ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
@@ -189,7 +197,7 @@
return (backtrace->NumFrames() == MAX_BACKTRACE_FRAMES);
}
-static void VerifyMaxDump(Backtrace* backtrace) {
+static void VerifyMaxDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
ASSERT_EQ(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
<< DumpFrames(backtrace);
// Verify that the last frame is our recursive call.
@@ -251,10 +259,14 @@
static void VerifyIgnoreFrames(Backtrace* bt_all, Backtrace* bt_ign1, Backtrace* bt_ign2,
const char* cur_proc) {
- EXPECT_EQ(bt_all->NumFrames(), bt_ign1->NumFrames() + 1)
- << "All backtrace:\n" << DumpFrames(bt_all) << "Ignore 1 backtrace:\n" << DumpFrames(bt_ign1);
- EXPECT_EQ(bt_all->NumFrames(), bt_ign2->NumFrames() + 2)
- << "All backtrace:\n" << DumpFrames(bt_all) << "Ignore 2 backtrace:\n" << DumpFrames(bt_ign2);
+ ASSERT_EQ(bt_all->NumFrames(), bt_ign1->NumFrames() + 1) << "All backtrace:\n"
+ << DumpFrames(bt_all)
+ << "Ignore 1 backtrace:\n"
+ << DumpFrames(bt_ign1);
+ ASSERT_EQ(bt_all->NumFrames(), bt_ign2->NumFrames() + 2) << "All backtrace:\n"
+ << DumpFrames(bt_all)
+ << "Ignore 2 backtrace:\n"
+ << DumpFrames(bt_ign2);
// Check all of the frames are the same > the current frame.
bool check = (cur_proc == nullptr);
@@ -305,9 +317,8 @@
}
static void VerifyProcTest(pid_t pid, pid_t tid, bool (*ReadyFunc)(Backtrace*),
- void (*VerifyFunc)(Backtrace*),
- Backtrace* (*back_func)(pid_t, pid_t, BacktraceMap*),
- BacktraceMap* (*map_func)(pid_t, bool)) {
+ void (*VerifyFunc)(Backtrace*, create_func_t, map_create_func_t),
+ create_func_t create_func, map_create_func_t map_create_func) {
pid_t ptrace_tid;
if (tid < 0) {
ptrace_tid = pid;
@@ -324,13 +335,13 @@
WaitForStop(ptrace_tid);
std::unique_ptr<BacktraceMap> map;
- map.reset(map_func(pid, false));
- std::unique_ptr<Backtrace> backtrace(back_func(pid, tid, map.get()));
+ map.reset(map_create_func(pid, false));
+ std::unique_ptr<Backtrace> backtrace(create_func(pid, tid, map.get()));
ASSERT_TRUE(backtrace.get() != nullptr);
ASSERT_TRUE(backtrace->Unwind(0));
ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
if (ReadyFunc(backtrace.get())) {
- VerifyFunc(backtrace.get());
+ VerifyFunc(backtrace.get(), create_func, map_create_func);
verified = true;
} else {
last_dump = DumpFrames(backtrace.get());
@@ -399,13 +410,15 @@
ASSERT_EQ(waitpid(pid, &status, 0), pid);
}
-static void VerifyProcessIgnoreFrames(Backtrace* bt_all) {
- std::unique_ptr<Backtrace> ign1(Backtrace::Create(bt_all->Pid(), BACKTRACE_CURRENT_THREAD));
+static void VerifyProcessIgnoreFrames(Backtrace* bt_all, create_func_t create_func,
+ map_create_func_t map_create_func) {
+ std::unique_ptr<BacktraceMap> map(map_create_func(bt_all->Pid(), false));
+ std::unique_ptr<Backtrace> ign1(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
ASSERT_TRUE(ign1.get() != nullptr);
ASSERT_TRUE(ign1->Unwind(1));
ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError());
- std::unique_ptr<Backtrace> ign2(Backtrace::Create(bt_all->Pid(), BACKTRACE_CURRENT_THREAD));
+ std::unique_ptr<Backtrace> ign2(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
ASSERT_TRUE(ign2.get() != nullptr);
ASSERT_TRUE(ign2->Unwind(2));
ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError());
@@ -1702,9 +1715,8 @@
;
}
-static void UnwindThroughSignal(bool use_action,
- Backtrace* (*back_func)(pid_t, pid_t, BacktraceMap*),
- BacktraceMap* (*map_func)(pid_t, bool)) {
+static void UnwindThroughSignal(bool use_action, create_func_t create_func,
+ map_create_func_t map_create_func) {
volatile int value = 0;
pid_t pid;
if ((pid = fork()) == 0) {
@@ -1730,8 +1742,8 @@
WaitForStop(pid);
- std::unique_ptr<BacktraceMap> map(map_func(pid, false));
- std::unique_ptr<Backtrace> backtrace(back_func(pid, pid, map.get()));
+ std::unique_ptr<BacktraceMap> map(map_create_func(pid, false));
+ std::unique_ptr<Backtrace> backtrace(create_func(pid, pid, map.get()));
size_t bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(const_cast<int*>(&value)),
reinterpret_cast<uint8_t*>(&read_value), sizeof(read_value));
@@ -1758,9 +1770,9 @@
WaitForStop(pid);
- map.reset(map_func(pid, false));
+ map.reset(map_create_func(pid, false));
ASSERT_TRUE(map.get() != nullptr);
- backtrace.reset(back_func(pid, pid, map.get()));
+ backtrace.reset(create_func(pid, pid, map.get()));
ASSERT_TRUE(backtrace->Unwind(0));
bool found = false;
for (frame_iter = backtrace->begin(); frame_iter != backtrace->end(); ++frame_iter) {
diff --git a/libbacktrace/include/backtrace/BacktraceMap.h b/libbacktrace/include/backtrace/BacktraceMap.h
index 963c34b..6cf8b3f 100644
--- a/libbacktrace/include/backtrace/BacktraceMap.h
+++ b/libbacktrace/include/backtrace/BacktraceMap.h
@@ -91,6 +91,8 @@
const_iterator begin() const { return maps_.begin(); }
const_iterator end() const { return maps_.end(); }
+ size_t size() const { return maps_.size(); }
+
virtual bool Build();
static inline bool IsValid(const backtrace_map_t& map) {
diff --git a/libion/include/ion/ion.h b/libion/include/ion/ion.h
index f47793d..a60d24e 100644
--- a/libion/include/ion/ion.h
+++ b/libion/include/ion/ion.h
@@ -41,6 +41,15 @@
int ion_share(int fd, ion_user_handle_t handle, int *share_fd);
int ion_import(int fd, int share_fd, ion_user_handle_t *handle);
+/**
+ * Add 4.12+ kernel ION interfaces here for forward compatibility
+ * This should be needed till the pre-4.12+ ION interfaces are backported.
+ */
+int ion_query_heap_cnt(int fd, int* cnt);
+int ion_query_get_heaps(int fd, int cnt, void* buffers);
+
+int ion_is_legacy(int fd);
+
__END_DECLS
#endif /* __SYS_CORE_ION_H */
diff --git a/libion/ion.c b/libion/ion.c
index 9aaa6f2..5836128 100644
--- a/libion/ion.c
+++ b/libion/ion.c
@@ -22,6 +22,7 @@
#include <errno.h>
#include <fcntl.h>
#include <linux/ion.h>
+#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
@@ -30,81 +31,89 @@
#include <unistd.h>
#include <ion/ion.h>
+#include "ion_4.12.h"
+
#include <log/log.h>
-int ion_open()
-{
+enum ion_version { ION_VERSION_UNKNOWN, ION_VERSION_MODERN, ION_VERSION_LEGACY };
+
+static atomic_int g_ion_version = ATOMIC_VAR_INIT(ION_VERSION_UNKNOWN);
+
+int ion_is_legacy(int fd) {
+ int version = atomic_load_explicit(&g_ion_version, memory_order_acquire);
+ if (version == ION_VERSION_UNKNOWN) {
+ /**
+ * Check for FREE IOCTL here; it is available only in the old
+ * kernels, not the new ones.
+ */
+ int err = ion_free(fd, (ion_user_handle_t)NULL);
+ version = (err == -ENOTTY) ? ION_VERSION_MODERN : ION_VERSION_LEGACY;
+ atomic_store_explicit(&g_ion_version, version, memory_order_release);
+ }
+ return version == ION_VERSION_LEGACY;
+}
+
+int ion_open() {
int fd = open("/dev/ion", O_RDONLY | O_CLOEXEC);
- if (fd < 0)
- ALOGE("open /dev/ion failed!\n");
+ if (fd < 0) ALOGE("open /dev/ion failed!\n");
+
return fd;
}
-int ion_close(int fd)
-{
+int ion_close(int fd) {
int ret = close(fd);
- if (ret < 0)
- return -errno;
+ if (ret < 0) return -errno;
return ret;
}
-static int ion_ioctl(int fd, int req, void *arg)
-{
+static int ion_ioctl(int fd, int req, void* arg) {
int ret = ioctl(fd, req, arg);
if (ret < 0) {
- ALOGE("ioctl %x failed with code %d: %s\n", req,
- ret, strerror(errno));
+ ALOGE("ioctl %x failed with code %d: %s\n", req, ret, strerror(errno));
return -errno;
}
return ret;
}
-int ion_alloc(int fd, size_t len, size_t align, unsigned int heap_mask,
- unsigned int flags, ion_user_handle_t *handle)
-{
- int ret;
+int ion_alloc(int fd, size_t len, size_t align, unsigned int heap_mask, unsigned int flags,
+ ion_user_handle_t* handle) {
+ int ret = 0;
+
+ if ((handle == NULL) || (!ion_is_legacy(fd))) return -EINVAL;
+
struct ion_allocation_data data = {
- .len = len,
- .align = align,
- .heap_id_mask = heap_mask,
- .flags = flags,
+ .len = len, .align = align, .heap_id_mask = heap_mask, .flags = flags,
};
- if (handle == NULL)
- return -EINVAL;
-
ret = ion_ioctl(fd, ION_IOC_ALLOC, &data);
- if (ret < 0)
- return ret;
+ if (ret < 0) return ret;
+
*handle = data.handle;
+
return ret;
}
-int ion_free(int fd, ion_user_handle_t handle)
-{
+int ion_free(int fd, ion_user_handle_t handle) {
struct ion_handle_data data = {
.handle = handle,
};
return ion_ioctl(fd, ION_IOC_FREE, &data);
}
-int ion_map(int fd, ion_user_handle_t handle, size_t length, int prot,
- int flags, off_t offset, unsigned char **ptr, int *map_fd)
-{
+int ion_map(int fd, ion_user_handle_t handle, size_t length, int prot, int flags, off_t offset,
+ unsigned char** ptr, int* map_fd) {
+ if (!ion_is_legacy(fd)) return -EINVAL;
int ret;
- unsigned char *tmp_ptr;
+ unsigned char* tmp_ptr;
struct ion_fd_data data = {
.handle = handle,
};
- if (map_fd == NULL)
- return -EINVAL;
- if (ptr == NULL)
- return -EINVAL;
+ if (map_fd == NULL) return -EINVAL;
+ if (ptr == NULL) return -EINVAL;
ret = ion_ioctl(fd, ION_IOC_MAP, &data);
- if (ret < 0)
- return ret;
+ if (ret < 0) return ret;
if (data.fd < 0) {
ALOGE("map ioctl returned negative fd\n");
return -EINVAL;
@@ -119,19 +128,17 @@
return ret;
}
-int ion_share(int fd, ion_user_handle_t handle, int *share_fd)
-{
+int ion_share(int fd, ion_user_handle_t handle, int* share_fd) {
int ret;
struct ion_fd_data data = {
.handle = handle,
};
- if (share_fd == NULL)
- return -EINVAL;
+ if (!ion_is_legacy(fd)) return -EINVAL;
+ if (share_fd == NULL) return -EINVAL;
ret = ion_ioctl(fd, ION_IOC_SHARE, &data);
- if (ret < 0)
- return ret;
+ if (ret < 0) return ret;
if (data.fd < 0) {
ALOGE("share ioctl returned negative fd\n");
return -EINVAL;
@@ -140,40 +147,75 @@
return ret;
}
-int ion_alloc_fd(int fd, size_t len, size_t align, unsigned int heap_mask,
- unsigned int flags, int *handle_fd) {
+int ion_alloc_fd(int fd, size_t len, size_t align, unsigned int heap_mask, unsigned int flags,
+ int* handle_fd) {
ion_user_handle_t handle;
int ret;
- ret = ion_alloc(fd, len, align, heap_mask, flags, &handle);
- if (ret < 0)
- return ret;
- ret = ion_share(fd, handle, handle_fd);
- ion_free(fd, handle);
+ if (!ion_is_legacy(fd)) {
+ struct ion_new_allocation_data data = {
+ .len = len,
+ .heap_id_mask = heap_mask,
+ .flags = flags,
+ };
+
+ ret = ion_ioctl(fd, ION_IOC_NEW_ALLOC, &data);
+ if (ret < 0) return ret;
+ *handle_fd = data.fd;
+ } else {
+ ret = ion_alloc(fd, len, align, heap_mask, flags, &handle);
+ if (ret < 0) return ret;
+ ret = ion_share(fd, handle, handle_fd);
+ ion_free(fd, handle);
+ }
return ret;
}
-int ion_import(int fd, int share_fd, ion_user_handle_t *handle)
-{
+int ion_import(int fd, int share_fd, ion_user_handle_t* handle) {
int ret;
struct ion_fd_data data = {
.fd = share_fd,
};
- if (handle == NULL)
- return -EINVAL;
+ if (!ion_is_legacy(fd)) return -EINVAL;
+
+ if (handle == NULL) return -EINVAL;
ret = ion_ioctl(fd, ION_IOC_IMPORT, &data);
- if (ret < 0)
- return ret;
+ if (ret < 0) return ret;
*handle = data.handle;
return ret;
}
-int ion_sync_fd(int fd, int handle_fd)
-{
+int ion_sync_fd(int fd, int handle_fd) {
struct ion_fd_data data = {
.fd = handle_fd,
};
+
+ if (!ion_is_legacy(fd)) return -EINVAL;
+
return ion_ioctl(fd, ION_IOC_SYNC, &data);
}
+
+int ion_query_heap_cnt(int fd, int* cnt) {
+ int ret;
+ struct ion_heap_query query;
+
+ memset(&query, 0, sizeof(query));
+
+ ret = ion_ioctl(fd, ION_IOC_HEAP_QUERY, &query);
+ if (ret < 0) return ret;
+
+ *cnt = query.cnt;
+ return ret;
+}
+
+int ion_query_get_heaps(int fd, int cnt, void* buffers) {
+ int ret;
+ struct ion_heap_query query = {
+ .cnt = cnt, .heaps = (uintptr_t)buffers,
+ };
+
+ ret = ion_ioctl(fd, ION_IOC_HEAP_QUERY, &query);
+ return ret;
+}
diff --git a/libion/ion_4.12.h b/libion/ion_4.12.h
new file mode 100644
index 0000000..6ae79d4
--- /dev/null
+++ b/libion/ion_4.12.h
@@ -0,0 +1,125 @@
+/*
+ * Adapted from drivers/staging/android/uapi/ion.h
+ *
+ * Copyright (C) 2011 Google, Inc.
+ *
+ * This software is licensed under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation, and
+ * may be copied, distributed, and modified under those terms.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#ifndef _UAPI_LINUX_ION_NEW_H
+#define _UAPI_LINUX_ION_NEW_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
+
+/**
+ * DOC: Ion Userspace API
+ *
+ * create a client by opening /dev/ion
+ * most operations handled via following ioctls
+ *
+ */
+
+/**
+ * struct ion_new_allocation_data - metadata passed from userspace for allocations
+ * @len: size of the allocation
+ * @heap_id_mask: mask of heap ids to allocate from
+ * @flags: flags passed to heap
+ * @handle: pointer that will be populated with a cookie to use to
+ * refer to this allocation
+ *
+ * Provided by userspace as an argument to the ioctl - added _new to denote
+ * this belongs to the new ION interface.
+ */
+struct ion_new_allocation_data {
+ __u64 len;
+ __u32 heap_id_mask;
+ __u32 flags;
+ __u32 fd;
+ __u32 unused;
+};
+
+#define MAX_HEAP_NAME 32
+
+/**
+ * struct ion_heap_data - data about a heap
+ * @name - first 32 characters of the heap name
+ * @type - heap type
+ * @heap_id - heap id for the heap
+ */
+struct ion_heap_data {
+ char name[MAX_HEAP_NAME];
+ __u32 type;
+ __u32 heap_id;
+ __u32 reserved0;
+ __u32 reserved1;
+ __u32 reserved2;
+};
+
+/**
+ * struct ion_heap_query - collection of data about all heaps
+ * @cnt - total number of heaps to be copied
+ * @heaps - buffer to copy heap data
+ */
+struct ion_heap_query {
+ __u32 cnt; /* Total number of heaps to be copied */
+ __u32 reserved0; /* align to 64bits */
+ __u64 heaps; /* buffer to be populated */
+ __u32 reserved1;
+ __u32 reserved2;
+};
+
+#define ION_IOC_MAGIC 'I'
+
+/**
+ * DOC: ION_IOC_NEW_ALLOC - allocate memory
+ *
+ * Takes an ion_allocation_data struct and returns it with the handle field
+ * populated with the opaque handle for the allocation.
+ * TODO: This IOCTL will clash by design; however, only one of
+ * ION_IOC_ALLOC or ION_IOC_NEW_ALLOC paths will be exercised,
+ * so this should not conflict.
+ */
+#define ION_IOC_NEW_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_new_allocation_data)
+
+/**
+ * DOC: ION_IOC_FREE - free memory
+ *
+ * Takes an ion_handle_data struct and frees the handle.
+ *
+ * #define ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data)
+ * This will come from the older kernels, so don't redefine here
+ */
+
+/**
+ * DOC: ION_IOC_SHARE - creates a file descriptor to use to share an allocation
+ *
+ * Takes an ion_fd_data struct with the handle field populated with a valid
+ * opaque handle. Returns the struct with the fd field set to a file
+ * descriptor open in the current address space. This file descriptor
+ * can then be passed to another process. The corresponding opaque handle can
+ * be retrieved via ION_IOC_IMPORT.
+ *
+ * #define ION_IOC_SHARE _IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data)
+ * This will come from the older kernels, so don't redefine here
+ */
+
+/**
+ * DOC: ION_IOC_HEAP_QUERY - information about available heaps
+ *
+ * Takes an ion_heap_query structure and populates information about
+ * available Ion heaps.
+ */
+#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query)
+
+#endif /* _UAPI_LINUX_ION_NEW_H */
diff --git a/libmemunreachable/tests/MemUnreachable_test.cpp b/libmemunreachable/tests/MemUnreachable_test.cpp
index ec89388..87417f1 100644
--- a/libmemunreachable/tests/MemUnreachable_test.cpp
+++ b/libmemunreachable/tests/MemUnreachable_test.cpp
@@ -27,6 +27,9 @@
class HiddenPointer {
public:
+ // Since we're doing such a good job of hiding it, the static analyzer
+ // thinks that we're leaking this `malloc`. This is probably related to
+ // https://bugs.llvm.org/show_bug.cgi?id=34198. NOLINTNEXTLINE
explicit HiddenPointer(size_t size = 256) { Set(malloc(size)); }
~HiddenPointer() { Free(); }
void* Get() { return reinterpret_cast<void*>(~ptr_); }
diff --git a/libmetricslogger/Android.bp b/libmetricslogger/Android.bp
index 9b179d1..6549b8d 100644
--- a/libmetricslogger/Android.bp
+++ b/libmetricslogger/Android.bp
@@ -18,14 +18,6 @@
"-Wall",
"-Wextra",
"-Werror",
-
- // The following defines map logtag IDs as represented by:
- // frameworks/base/core/java/com/android/internal/logging/EventLogTags.logtags
- //
- // E.g., 524290 corresponds to sysui_count.
- "-DCOUNT_LOG_TAG=524290",
- "-DHISTOGRAM_LOG_TAG=524292",
- "-DMULTI_ACTION_LOG_TAG=524292",
],
}
diff --git a/libmetricslogger/metrics_logger.cpp b/libmetricslogger/metrics_logger.cpp
index a0dcf09..fdc4407 100644
--- a/libmetricslogger/metrics_logger.cpp
+++ b/libmetricslogger/metrics_logger.cpp
@@ -18,28 +18,37 @@
#include <cstdlib>
+#include <log/event_tag_map.h>
#include <log/log_event_list.h>
+namespace {
+
+EventTagMap* kEventTagMap = android_openEventTagMap(nullptr);
+const int kSysuiMultiActionTag = android_lookupEventTagNum(
+ kEventTagMap, "sysui_multi_action", "(content|4)", ANDROID_LOG_UNKNOWN);
+
+} // namespace
+
namespace android {
namespace metricslogger {
// Mirror com.android.internal.logging.MetricsLogger#histogram().
void LogHistogram(const std::string& event, int32_t data) {
- android_log_event_list log(HISTOGRAM_LOG_TAG);
+ android_log_event_list log(kSysuiMultiActionTag);
log << LOGBUILDER_CATEGORY << LOGBUILDER_HISTOGRAM << LOGBUILDER_NAME << event
<< LOGBUILDER_BUCKET << data << LOGBUILDER_VALUE << 1 << LOG_ID_EVENTS;
}
// Mirror com.android.internal.logging.MetricsLogger#count().
void LogCounter(const std::string& name, int32_t val) {
- android_log_event_list log(COUNT_LOG_TAG);
+ android_log_event_list log(kSysuiMultiActionTag);
log << LOGBUILDER_CATEGORY << LOGBUILDER_COUNTER << LOGBUILDER_NAME << name << LOGBUILDER_VALUE
<< val << LOG_ID_EVENTS;
}
// Mirror com.android.internal.logging.MetricsLogger#action().
void LogMultiAction(int32_t category, int32_t field, const std::string& value) {
- android_log_event_list log(MULTI_ACTION_LOG_TAG);
+ android_log_event_list log(kSysuiMultiActionTag);
log << LOGBUILDER_CATEGORY << category << LOGBUILDER_TYPE << TYPE_ACTION
<< field << value << LOG_ID_EVENTS;
}
diff --git a/libsync/sync.c b/libsync/sync.c
index e657658..6b187fa 100644
--- a/libsync/sync.c
+++ b/libsync/sync.c
@@ -217,6 +217,8 @@
local_info.num_fences * sizeof(struct sync_fence_info));
if (!info)
return NULL;
+
+ info->num_fences = local_info.num_fences;
info->sync_fence_info = (__u64)(uintptr_t)(info + 1);
err = ioctl(fd, SYNC_IOC_FILE_INFO, info);
diff --git a/libsync/tests/sync_test.cpp b/libsync/tests/sync_test.cpp
index f08e97e..0fb86d6 100644
--- a/libsync/tests/sync_test.cpp
+++ b/libsync/tests/sync_test.cpp
@@ -448,6 +448,41 @@
ASSERT_EQ(mergedFence.wait(100), 0);
}
+TEST(FenceTest, GetInfoActive) {
+ SyncTimeline timeline;
+ ASSERT_TRUE(timeline.isValid());
+
+ SyncFence fence(timeline, 1);
+ ASSERT_TRUE(fence.isValid());
+
+ vector<SyncPointInfo> info = fence.getInfo();
+ ASSERT_EQ(info.size(), 1);
+
+ ASSERT_FALSE(info[0].driverName.empty());
+ ASSERT_FALSE(info[0].objectName.empty());
+ ASSERT_EQ(info[0].timeStampNs, 0);
+ ASSERT_EQ(info[0].status, 0);
+}
+
+TEST(FenceTest, GetInfoSignaled) {
+ SyncTimeline timeline;
+ ASSERT_TRUE(timeline.isValid());
+
+ SyncFence fence(timeline, 1);
+ ASSERT_TRUE(fence.isValid());
+
+ ASSERT_EQ(timeline.inc(1), 0);
+ ASSERT_EQ(fence.wait(), 0);
+
+ vector<SyncPointInfo> info = fence.getInfo();
+ ASSERT_EQ(info.size(), 1);
+
+ ASSERT_FALSE(info[0].driverName.empty());
+ ASSERT_FALSE(info[0].objectName.empty());
+ ASSERT_GT(info[0].timeStampNs, 0);
+ ASSERT_EQ(info[0].status, 1);
+}
+
TEST(StressTest, TwoThreadsSharedTimeline) {
const int iterations = 1 << 16;
int counter = 0;
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 32ba692..ca05516 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -29,6 +29,9 @@
darwin: {
enabled: false,
},
+ linux_bionic: {
+ enabled: true,
+ },
},
}
@@ -58,6 +61,7 @@
"Maps.cpp",
"Memory.cpp",
"Regs.cpp",
+ "Unwinder.cpp",
"Symbols.cpp",
],
diff --git a/libunwindstack/DwarfSection.cpp b/libunwindstack/DwarfSection.cpp
index 1234eb1..8b30b76 100644
--- a/libunwindstack/DwarfSection.cpp
+++ b/libunwindstack/DwarfSection.cpp
@@ -47,7 +47,7 @@
return nullptr;
}
-bool DwarfSection::Step(uint64_t pc, Regs* regs, Memory* process_memory) {
+bool DwarfSection::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
last_error_ = DWARF_ERROR_NONE;
const DwarfFde* fde = GetFdeFromPc(pc);
if (fde == nullptr || fde->cie == nullptr) {
@@ -62,7 +62,7 @@
}
// Now eval the actual registers.
- return Eval(fde->cie, process_memory, loc_regs, regs);
+ return Eval(fde->cie, process_memory, loc_regs, regs, finished);
}
template <typename AddressType>
@@ -92,7 +92,8 @@
template <typename AddressType>
bool DwarfSectionImpl<AddressType>::Eval(const DwarfCie* cie, Memory* regular_memory,
- const dwarf_loc_regs_t& loc_regs, Regs* regs) {
+ const dwarf_loc_regs_t& loc_regs, Regs* regs,
+ bool* finished) {
RegsImpl<AddressType>* cur_regs = reinterpret_cast<RegsImpl<AddressType>*>(regs);
if (cie->return_address_register >= cur_regs->total_regs()) {
last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
@@ -224,12 +225,14 @@
// Find the return address location.
if (return_address_undefined) {
cur_regs->set_pc(0);
+ *finished = true;
} else {
cur_regs->set_pc((*cur_regs)[cie->return_address_register]);
+ *finished = false;
}
cur_regs->set_sp(cfa);
- // Stop if the cfa and pc are the same.
- return prev_cfa != cfa || prev_pc != cur_regs->pc();
+ // Return false if the unwind is not finished or the cfa and pc didn't change.
+ return *finished || prev_cfa != cfa || prev_pc != cur_regs->pc();
}
template <typename AddressType>
diff --git a/libunwindstack/Elf.cpp b/libunwindstack/Elf.cpp
index 4f7476d..dc6591d 100644
--- a/libunwindstack/Elf.cpp
+++ b/libunwindstack/Elf.cpp
@@ -95,11 +95,17 @@
gnu_debugdata_interface_->GetFunctionName(addr, name, func_offset)));
}
-bool Elf::Step(uint64_t rel_pc, Regs* regs, Memory* process_memory) {
- return valid_ && (regs->StepIfSignalHandler(rel_pc, this, process_memory) ||
- interface_->Step(rel_pc, regs, process_memory) ||
- (gnu_debugdata_interface_ &&
- gnu_debugdata_interface_->Step(rel_pc, regs, process_memory)));
+bool Elf::Step(uint64_t rel_pc, Regs* regs, Memory* process_memory, bool* finished) {
+ if (!valid_) {
+ return false;
+ }
+ if (regs->StepIfSignalHandler(rel_pc, this, process_memory)) {
+ *finished = false;
+ return true;
+ }
+ return interface_->Step(rel_pc, regs, process_memory, finished) ||
+ (gnu_debugdata_interface_ &&
+ gnu_debugdata_interface_->Step(rel_pc, regs, process_memory, finished));
}
uint64_t Elf::GetLoadBias() {
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
index be4f88a..46a3f3f 100644
--- a/libunwindstack/ElfInterface.cpp
+++ b/libunwindstack/ElfInterface.cpp
@@ -348,7 +348,7 @@
return false;
}
-bool ElfInterface::Step(uint64_t pc, Regs* regs, Memory* process_memory) {
+bool ElfInterface::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
// Need to subtract off the load_bias to get the correct pc.
if (pc < load_bias_) {
return false;
@@ -357,16 +357,15 @@
// Try the eh_frame first.
DwarfSection* eh_frame = eh_frame_.get();
- if (eh_frame != nullptr && eh_frame->Step(pc, regs, process_memory)) {
+ if (eh_frame != nullptr && eh_frame->Step(pc, regs, process_memory, finished)) {
return true;
}
// Try the debug_frame next.
DwarfSection* debug_frame = debug_frame_.get();
- if (debug_frame != nullptr && debug_frame->Step(pc, regs, process_memory)) {
+ if (debug_frame != nullptr && debug_frame->Step(pc, regs, process_memory, finished)) {
return true;
}
-
return false;
}
diff --git a/libunwindstack/ElfInterfaceArm.cpp b/libunwindstack/ElfInterfaceArm.cpp
index 66bc51f..17364d0 100644
--- a/libunwindstack/ElfInterfaceArm.cpp
+++ b/libunwindstack/ElfInterfaceArm.cpp
@@ -99,22 +99,25 @@
return true;
}
-bool ElfInterfaceArm::Step(uint64_t pc, Regs* regs, Memory* process_memory) {
+bool ElfInterfaceArm::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
// Dwarf unwind information is precise about whether a pc is covered or not,
// but arm unwind information only has ranges of pc. In order to avoid
// incorrectly doing a bad unwind using arm unwind information for a
// different function, always try and unwind with the dwarf information first.
- return ElfInterface32::Step(pc, regs, process_memory) || StepExidx(pc, regs, process_memory);
+ return ElfInterface32::Step(pc, regs, process_memory, finished) ||
+ StepExidx(pc, regs, process_memory, finished);
}
-bool ElfInterfaceArm::StepExidx(uint64_t pc, Regs* regs, Memory* process_memory) {
+bool ElfInterfaceArm::StepExidx(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
RegsArm* regs_arm = reinterpret_cast<RegsArm*>(regs);
uint64_t entry_offset;
if (!FindEntry(pc, &entry_offset)) {
return false;
}
+
ArmExidx arm(regs_arm, memory_, process_memory);
arm.set_cfa(regs_arm->sp());
+ bool return_value = false;
if (arm.ExtractEntryData(entry_offset) && arm.Eval()) {
// If the pc was not set, then use the LR registers for the PC.
if (!arm.pc_set()) {
@@ -125,9 +128,15 @@
}
regs_arm->set_sp(arm.cfa());
(*regs_arm)[ARM_REG_SP] = regs_arm->sp();
+ *finished = false;
+ return_value = true;
+ }
+
+ if (arm.status() == ARM_STATUS_NO_UNWIND) {
+ *finished = true;
return true;
}
- return false;
+ return return_value;
}
} // namespace unwindstack
diff --git a/libunwindstack/ElfInterfaceArm.h b/libunwindstack/ElfInterfaceArm.h
index 1f4e8cb..bfe7704 100644
--- a/libunwindstack/ElfInterfaceArm.h
+++ b/libunwindstack/ElfInterfaceArm.h
@@ -70,9 +70,9 @@
bool HandleType(uint64_t offset, uint32_t type) override;
- bool Step(uint64_t pc, Regs* regs, Memory* process_memory) override;
+ bool Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) override;
- bool StepExidx(uint64_t pc, Regs* regs, Memory* process_memory);
+ bool StepExidx(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished);
uint64_t start_offset() { return start_offset_; }
diff --git a/libunwindstack/Regs.cpp b/libunwindstack/Regs.cpp
index 4d09c1b..8c6172e 100644
--- a/libunwindstack/Regs.cpp
+++ b/libunwindstack/Regs.cpp
@@ -91,6 +91,15 @@
set_sp(regs_[ARM_REG_SP]);
}
+bool RegsArm::SetPcFromReturnAddress(Memory*) {
+ if (pc() == regs_[ARM_REG_LR]) {
+ return false;
+ }
+
+ set_pc(regs_[ARM_REG_LR]);
+ return true;
+}
+
RegsArm64::RegsArm64()
: RegsImpl<uint64_t>(ARM64_REG_LAST, ARM64_REG_SP, Location(LOCATION_REGISTER, ARM64_REG_LR)) {}
@@ -114,6 +123,15 @@
set_sp(regs_[ARM64_REG_SP]);
}
+bool RegsArm64::SetPcFromReturnAddress(Memory*) {
+ if (pc() == regs_[ARM64_REG_LR]) {
+ return false;
+ }
+
+ set_pc(regs_[ARM64_REG_LR]);
+ return true;
+}
+
RegsX86::RegsX86()
: RegsImpl<uint32_t>(X86_REG_LAST, X86_REG_SP, Location(LOCATION_SP_OFFSET, -4)) {}
@@ -137,6 +155,17 @@
set_sp(regs_[X86_REG_SP]);
}
+bool RegsX86::SetPcFromReturnAddress(Memory* process_memory) {
+ // Attempt to get the return address from the top of the stack.
+ uint32_t new_pc;
+ if (!process_memory->Read(sp_, &new_pc, sizeof(new_pc)) || new_pc == pc()) {
+ return false;
+ }
+
+ set_pc(new_pc);
+ return true;
+}
+
RegsX86_64::RegsX86_64()
: RegsImpl<uint64_t>(X86_64_REG_LAST, X86_64_REG_SP, Location(LOCATION_SP_OFFSET, -8)) {}
@@ -161,6 +190,17 @@
set_sp(regs_[X86_64_REG_SP]);
}
+bool RegsX86_64::SetPcFromReturnAddress(Memory* process_memory) {
+ // Attempt to get the return address from the top of the stack.
+ uint64_t new_pc;
+ if (!process_memory->Read(sp_, &new_pc, sizeof(new_pc)) || new_pc == pc()) {
+ return false;
+ }
+
+ set_pc(new_pc);
+ return true;
+}
+
static Regs* ReadArm(void* remote_data) {
arm_user_regs* user = reinterpret_cast<arm_user_regs*>(remote_data);
diff --git a/libunwindstack/Unwinder.cpp b/libunwindstack/Unwinder.cpp
new file mode 100644
index 0000000..1a86e16
--- /dev/null
+++ b/libunwindstack/Unwinder.cpp
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <elf.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/stringprintf.h>
+
+#include <unwindstack/Elf.h>
+#include <unwindstack/MapInfo.h>
+#include <unwindstack/Unwinder.h>
+
+namespace unwindstack {
+
+void Unwinder::FillInFrame(MapInfo* map_info, uint64_t* rel_pc) {
+ size_t frame_num = frames_.size();
+ frames_.resize(frame_num + 1);
+ FrameData* frame = &frames_.at(frame_num);
+ frame->num = frame_num;
+ frame->pc = regs_->pc();
+ frame->sp = regs_->sp();
+ frame->rel_pc = frame->pc;
+
+ if (map_info == nullptr) {
+ return;
+ }
+
+ Elf* elf = map_info->GetElf(process_memory_, true);
+ *rel_pc = elf->GetRelPc(regs_->pc(), map_info);
+ if (frame_num != 0) {
+ // Don't adjust the first frame pc.
+ frame->rel_pc = regs_->GetAdjustedPc(*rel_pc, elf);
+
+ // Adjust the original pc.
+ frame->pc -= *rel_pc - frame->rel_pc;
+ } else {
+ frame->rel_pc = *rel_pc;
+ }
+
+ frame->map_name = map_info->name;
+ frame->map_offset = map_info->elf_offset;
+ frame->map_start = map_info->start;
+ frame->map_end = map_info->end;
+
+ if (!elf->GetFunctionName(frame->rel_pc, &frame->function_name, &frame->function_offset)) {
+ frame->function_name = "";
+ frame->function_offset = 0;
+ }
+}
+
+void Unwinder::Unwind() {
+ frames_.clear();
+
+ bool return_address_attempt = false;
+ for (; frames_.size() < max_frames_;) {
+ MapInfo* map_info = maps_->Find(regs_->pc());
+
+ uint64_t rel_pc;
+ FillInFrame(map_info, &rel_pc);
+
+ bool stepped;
+ if (map_info == nullptr) {
+ stepped = false;
+ } else {
+ bool finished;
+ stepped = map_info->elf->Step(rel_pc + map_info->elf_offset, regs_, process_memory_.get(),
+ &finished);
+ if (stepped && finished) {
+ break;
+ }
+ }
+ if (!stepped) {
+ if (return_address_attempt) {
+ // Remove the speculative frame.
+ frames_.pop_back();
+ break;
+ } else {
+ // Steping didn't work, try this secondary method.
+ if (!regs_->SetPcFromReturnAddress(process_memory_.get())) {
+ break;
+ }
+ return_address_attempt = true;
+ }
+ } else {
+ return_address_attempt = false;
+ }
+ }
+}
+
+std::string Unwinder::FormatFrame(size_t frame_num) {
+ if (frame_num >= frames_.size()) {
+ return "";
+ }
+ return FormatFrame(frames_[frame_num],
+ regs_->MachineType() == EM_ARM || regs_->MachineType() == EM_386);
+}
+
+std::string Unwinder::FormatFrame(const FrameData& frame, bool bits32) {
+ std::string data;
+
+ if (bits32) {
+ data += android::base::StringPrintf(" #%02zu pc %08" PRIx64, frame.num, frame.rel_pc);
+ } else {
+ data += android::base::StringPrintf(" #%02zu pc %016" PRIx64, frame.num, frame.rel_pc);
+ }
+
+ if (frame.map_offset != 0) {
+ data += android::base::StringPrintf(" (offset 0x%" PRIx64 ")", frame.map_offset);
+ }
+
+ if (frame.map_start == frame.map_end) {
+ // No valid map associated with this frame.
+ data += " <unknown>";
+ } else if (!frame.map_name.empty()) {
+ data += " " + frame.map_name;
+ } else {
+ data += android::base::StringPrintf(" <anonymous:%" PRIx64 ">", frame.map_start);
+ }
+ if (!frame.function_name.empty()) {
+ data += " (" + frame.function_name;
+ if (frame.function_offset != 0) {
+ data += android::base::StringPrintf("+%" PRId64, frame.function_offset);
+ }
+ data += ')';
+ }
+ return data;
+}
+
+} // namespace unwindstack
diff --git a/libunwindstack/include/unwindstack/DwarfSection.h b/libunwindstack/include/unwindstack/DwarfSection.h
index 26485ae..1e843c3 100644
--- a/libunwindstack/include/unwindstack/DwarfSection.h
+++ b/libunwindstack/include/unwindstack/DwarfSection.h
@@ -76,7 +76,7 @@
virtual bool Init(uint64_t offset, uint64_t size) = 0;
- virtual bool Eval(const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*) = 0;
+ virtual bool Eval(const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*, bool*) = 0;
virtual bool GetFdeOffsetFromPc(uint64_t pc, uint64_t* fde_offset) = 0;
@@ -100,7 +100,7 @@
virtual uint64_t AdjustPcFromFde(uint64_t pc) = 0;
- bool Step(uint64_t pc, Regs* regs, Memory* process_memory);
+ bool Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished);
protected:
DwarfMemory memory_;
@@ -119,7 +119,7 @@
virtual ~DwarfSectionImpl() = default;
bool Eval(const DwarfCie* cie, Memory* regular_memory, const dwarf_loc_regs_t& loc_regs,
- Regs* regs) override;
+ Regs* regs, bool* finished) override;
const DwarfCie* GetCie(uint64_t offset);
bool FillInCie(DwarfCie* cie);
diff --git a/libunwindstack/include/unwindstack/Elf.h b/libunwindstack/include/unwindstack/Elf.h
index 4e7eb34..f246beb 100644
--- a/libunwindstack/include/unwindstack/Elf.h
+++ b/libunwindstack/include/unwindstack/Elf.h
@@ -50,7 +50,7 @@
uint64_t GetRelPc(uint64_t pc, const MapInfo* map_info);
- bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory);
+ bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory, bool* finished);
ElfInterface* CreateInterfaceFromMemory(Memory* memory);
diff --git a/libunwindstack/include/unwindstack/ElfInterface.h b/libunwindstack/include/unwindstack/ElfInterface.h
index 142a625..4fe966f 100644
--- a/libunwindstack/include/unwindstack/ElfInterface.h
+++ b/libunwindstack/include/unwindstack/ElfInterface.h
@@ -59,7 +59,7 @@
virtual bool GetFunctionName(uint64_t addr, std::string* name, uint64_t* offset) = 0;
- virtual bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory);
+ virtual bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory, bool* finished);
Memory* CreateGnuDebugdataMemory();
diff --git a/libunwindstack/include/unwindstack/Regs.h b/libunwindstack/include/unwindstack/Regs.h
index ed4d38a..385ee18 100644
--- a/libunwindstack/include/unwindstack/Regs.h
+++ b/libunwindstack/include/unwindstack/Regs.h
@@ -63,6 +63,8 @@
virtual void SetFromRaw() = 0;
+ virtual bool SetPcFromReturnAddress(Memory* process_memory) = 0;
+
uint16_t sp_reg() { return sp_reg_; }
uint16_t total_regs() { return total_regs_; }
@@ -113,6 +115,8 @@
void SetFromRaw() override;
+ bool SetPcFromReturnAddress(Memory* process_memory) override;
+
bool StepIfSignalHandler(uint64_t rel_pc, Elf* elf, Memory* process_memory) override;
};
@@ -127,6 +131,8 @@
void SetFromRaw() override;
+ bool SetPcFromReturnAddress(Memory* process_memory) override;
+
bool StepIfSignalHandler(uint64_t rel_pc, Elf* elf, Memory* process_memory) override;
};
@@ -141,6 +147,8 @@
void SetFromRaw() override;
+ bool SetPcFromReturnAddress(Memory* process_memory) override;
+
bool StepIfSignalHandler(uint64_t rel_pc, Elf* elf, Memory* process_memory) override;
void SetFromUcontext(x86_ucontext_t* ucontext);
@@ -157,6 +165,8 @@
void SetFromRaw() override;
+ bool SetPcFromReturnAddress(Memory* process_memory) override;
+
bool StepIfSignalHandler(uint64_t rel_pc, Elf* elf, Memory* process_memory) override;
void SetFromUcontext(x86_64_ucontext_t* ucontext);
diff --git a/libunwindstack/include/unwindstack/Unwinder.h b/libunwindstack/include/unwindstack/Unwinder.h
new file mode 100644
index 0000000..d66fe55
--- /dev/null
+++ b/libunwindstack/include/unwindstack/Unwinder.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_UNWINDER_H
+#define _LIBUNWINDSTACK_UNWINDER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
+
+namespace unwindstack {
+
+struct FrameData {
+ size_t num;
+
+ uint64_t rel_pc;
+ uint64_t pc;
+ uint64_t sp;
+
+ std::string function_name;
+ uint64_t function_offset;
+
+ std::string map_name;
+ uint64_t map_offset;
+ uint64_t map_start;
+ uint64_t map_end;
+};
+
+class Unwinder {
+ public:
+ Unwinder(size_t max_frames, Maps* maps, Regs* regs, std::shared_ptr<Memory> process_memory)
+ : max_frames_(max_frames), maps_(maps), regs_(regs), process_memory_(process_memory) {
+ frames_.reserve(max_frames);
+ }
+ ~Unwinder() = default;
+
+ void Unwind();
+
+ size_t NumFrames() { return frames_.size(); }
+
+ const std::vector<FrameData>& frames() { return frames_; }
+
+ std::string FormatFrame(size_t frame_num);
+ static std::string FormatFrame(const FrameData& frame, bool bits32);
+
+ private:
+ void FillInFrame(MapInfo* map_info, uint64_t* rel_pc);
+
+ size_t max_frames_;
+ Maps* maps_;
+ Regs* regs_;
+ std::vector<FrameData> frames_;
+ std::shared_ptr<Memory> process_memory_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_UNWINDER_H
diff --git a/libunwindstack/tests/DwarfSectionImplTest.cpp b/libunwindstack/tests/DwarfSectionImplTest.cpp
index b871539..2939126 100644
--- a/libunwindstack/tests/DwarfSectionImplTest.cpp
+++ b/libunwindstack/tests/DwarfSectionImplTest.cpp
@@ -98,7 +98,8 @@
regs[5] = 0x20;
regs[9] = 0x3000;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_EXPRESSION, {0x2, 0x5000}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_MEMORY_INVALID, this->section_->last_error());
}
@@ -113,7 +114,8 @@
regs[9] = 0x3000;
this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x96, 0x96, 0x96});
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_EXPRESSION, {0x2, 0x5000}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->section_->last_error());
}
@@ -130,7 +132,9 @@
TypeParam cfa_value = 0x12345;
this->memory_.SetMemory(0x80000000, &cfa_value, sizeof(cfa_value));
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_EXPRESSION, {0x4, 0x5000}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x12345U, regs.sp());
EXPECT_EQ(0x20U, regs.pc());
}
@@ -146,7 +150,9 @@
regs[9] = 0x3000;
this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x0c, 0x00, 0x00, 0x00, 0x80});
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_VAL_EXPRESSION, {0x4, 0x5000}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ ASSERT_FALSE(finished);
EXPECT_EQ(0x80000000U, regs.sp());
EXPECT_EQ(0x20U, regs.pc());
}
@@ -162,7 +168,8 @@
regs[9] = 0x3000;
this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x50, 0x96, 0x96});
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_EXPRESSION, {0x2, 0x5000}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_NOT_IMPLEMENTED, this->section_->last_error());
}
@@ -171,7 +178,8 @@
RegsFake<TypeParam> regs(10, 9);
dwarf_loc_regs_t loc_regs;
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->section_->last_error());
}
@@ -180,7 +188,8 @@
RegsFake<TypeParam> regs(10, 9);
dwarf_loc_regs_t loc_regs;
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_CFA_NOT_DEFINED, this->section_->last_error());
}
@@ -190,25 +199,26 @@
dwarf_loc_regs_t loc_regs;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {20, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->section_->last_error());
this->section_->TestClearError();
loc_regs.erase(CFA_REG);
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_INVALID, {0, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->section_->last_error());
this->section_->TestClearError();
loc_regs.erase(CFA_REG);
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_OFFSET, {0, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->section_->last_error());
this->section_->TestClearError();
loc_regs.erase(CFA_REG);
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_VAL_OFFSET, {0, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->section_->last_error());
}
@@ -222,7 +232,9 @@
regs[5] = 0x20;
regs[9] = 0x3000;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {9, 0}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x20U, regs.pc());
EXPECT_EQ(0x2000U, regs.sp());
}
@@ -238,7 +250,9 @@
regs[6] = 0x4000;
regs[9] = 0x3000;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {6, 0}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x20U, regs.pc());
EXPECT_EQ(0x4000U, regs.sp());
}
@@ -254,7 +268,8 @@
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
loc_regs[1] = DwarfLocation{DWARF_LOCATION_REGISTER, {3, 0}};
loc_regs[9] = DwarfLocation{DWARF_LOCATION_REGISTER, {1, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->section_->last_error());
}
@@ -268,7 +283,8 @@
regs[8] = 0x10;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
loc_regs[1] = DwarfLocation{DWARF_LOCATION_REGISTER, {10, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->section_->last_error());
}
@@ -292,7 +308,9 @@
loc_regs[1] = DwarfLocation{DWARF_LOCATION_VAL_OFFSET, {0x100, 0}};
loc_regs[2] = DwarfLocation{DWARF_LOCATION_OFFSET, {0x50, 0}};
loc_regs[3] = DwarfLocation{DWARF_LOCATION_UNDEFINED, {0, 0}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x10U, regs.pc());
EXPECT_EQ(0x2100U, regs.sp());
EXPECT_EQ(0x2200U, regs[1]);
@@ -315,7 +333,9 @@
regs[8] = 0x10;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
loc_regs[5] = DwarfLocation{DWARF_LOCATION_UNDEFINED, {0, 0}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_TRUE(finished);
EXPECT_EQ(0U, regs.pc());
EXPECT_EQ(0x10U, regs.sp());
}
@@ -330,7 +350,9 @@
regs[5] = 0x20;
regs[8] = 0x10;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x20U, regs.pc());
EXPECT_EQ(0x10U, regs.sp());
}
@@ -347,7 +369,9 @@
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
// This should not result in any errors.
loc_regs[20] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x20U, regs.pc());
EXPECT_EQ(0x10U, regs.sp());
}
@@ -365,7 +389,9 @@
this->memory_.SetMemory(0x80000000, &cfa_value, sizeof(cfa_value));
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
loc_regs[5] = DwarfLocation{DWARF_LOCATION_EXPRESSION, {0x4, 0x5000}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x3000U, regs.sp());
EXPECT_EQ(0x12345U, regs.pc());
}
@@ -381,7 +407,9 @@
this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x0c, 0x00, 0x00, 0x00, 0x80});
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
loc_regs[5] = DwarfLocation{DWARF_LOCATION_VAL_EXPRESSION, {0x4, 0x5000}};
- ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_FALSE(finished);
EXPECT_EQ(0x3000U, regs.sp());
EXPECT_EQ(0x80000000U, regs.pc());
}
@@ -396,7 +424,8 @@
regs[5] = 0x100;
regs[8] = 0x2000;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s));
+ bool finished;
+ ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
EXPECT_EQ(0x2000U, regs.sp());
EXPECT_EQ(0x100U, regs.pc());
}
diff --git a/libunwindstack/tests/DwarfSectionTest.cpp b/libunwindstack/tests/DwarfSectionTest.cpp
index fc67063..3fcd2b6 100644
--- a/libunwindstack/tests/DwarfSectionTest.cpp
+++ b/libunwindstack/tests/DwarfSectionTest.cpp
@@ -32,7 +32,7 @@
MOCK_METHOD4(Log, bool(uint8_t, uint64_t, uint64_t, const DwarfFde*));
- MOCK_METHOD4(Eval, bool(const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*));
+ MOCK_METHOD5(Eval, bool(const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*, bool*));
MOCK_METHOD3(GetCfaLocationInfo, bool(uint64_t, const DwarfFde*, dwarf_loc_regs_t*));
@@ -104,7 +104,8 @@
EXPECT_CALL(mock_section, GetFdeOffsetFromPc(0x1000, ::testing::_))
.WillOnce(::testing::Return(false));
- ASSERT_FALSE(mock_section.Step(0x1000, nullptr, nullptr));
+ bool finished;
+ ASSERT_FALSE(mock_section.Step(0x1000, nullptr, nullptr, &finished));
}
TEST_F(DwarfSectionTest, Step_fail_cie_null) {
@@ -118,7 +119,8 @@
.WillOnce(::testing::Return(true));
EXPECT_CALL(mock_section, GetFdeFromOffset(::testing::_)).WillOnce(::testing::Return(&fde));
- ASSERT_FALSE(mock_section.Step(0x1000, nullptr, nullptr));
+ bool finished;
+ ASSERT_FALSE(mock_section.Step(0x1000, nullptr, nullptr, &finished));
}
TEST_F(DwarfSectionTest, Step_fail_cfa_location) {
@@ -136,7 +138,8 @@
EXPECT_CALL(mock_section, GetCfaLocationInfo(0x1000, &fde, ::testing::_))
.WillOnce(::testing::Return(false));
- ASSERT_FALSE(mock_section.Step(0x1000, nullptr, nullptr));
+ bool finished;
+ ASSERT_FALSE(mock_section.Step(0x1000, nullptr, nullptr, &finished));
}
TEST_F(DwarfSectionTest, Step_pass) {
@@ -155,10 +158,11 @@
.WillOnce(::testing::Return(true));
MemoryFake process;
- EXPECT_CALL(mock_section, Eval(&cie, &process, ::testing::_, nullptr))
+ EXPECT_CALL(mock_section, Eval(&cie, &process, ::testing::_, nullptr, ::testing::_))
.WillOnce(::testing::Return(true));
- ASSERT_TRUE(mock_section.Step(0x1000, nullptr, &process));
+ bool finished;
+ ASSERT_TRUE(mock_section.Step(0x1000, nullptr, &process, &finished));
}
} // namespace unwindstack
diff --git a/libunwindstack/tests/ElfInterfaceArmTest.cpp b/libunwindstack/tests/ElfInterfaceArmTest.cpp
index c7ef4a1..4df7e1c 100644
--- a/libunwindstack/tests/ElfInterfaceArmTest.cpp
+++ b/libunwindstack/tests/ElfInterfaceArmTest.cpp
@@ -322,7 +322,8 @@
ElfInterfaceArm interface(&memory_);
// FindEntry fails.
- ASSERT_FALSE(interface.StepExidx(0x7000, nullptr, nullptr));
+ bool finished;
+ ASSERT_FALSE(interface.StepExidx(0x7000, nullptr, nullptr, &finished));
// ExtractEntry should fail.
interface.set_start_offset(0x1000);
@@ -335,15 +336,16 @@
regs[ARM_REG_LR] = 0x20000;
regs.set_sp(regs[ARM_REG_SP]);
regs.set_pc(0x1234);
- ASSERT_FALSE(interface.StepExidx(0x7000, ®s, &process_memory_));
+ ASSERT_FALSE(interface.StepExidx(0x7000, ®s, &process_memory_, &finished));
// Eval should fail.
memory_.SetData32(0x1004, 0x81000000);
- ASSERT_FALSE(interface.StepExidx(0x7000, ®s, &process_memory_));
+ ASSERT_FALSE(interface.StepExidx(0x7000, ®s, &process_memory_, &finished));
// Everything should pass.
memory_.SetData32(0x1004, 0x80b0b0b0);
- ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_));
+ ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_, &finished));
+ ASSERT_FALSE(finished);
ASSERT_EQ(0x1000U, regs.sp());
ASSERT_EQ(0x1000U, regs[ARM_REG_SP]);
ASSERT_EQ(0x20000U, regs.pc());
@@ -367,11 +369,57 @@
regs.set_pc(0x1234);
// Everything should pass.
- ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_));
+ bool finished;
+ ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_, &finished));
+ ASSERT_FALSE(finished);
ASSERT_EQ(0x10004U, regs.sp());
ASSERT_EQ(0x10004U, regs[ARM_REG_SP]);
ASSERT_EQ(0x10U, regs.pc());
ASSERT_EQ(0x10U, regs[ARM_REG_PC]);
}
+TEST_F(ElfInterfaceArmTest, StepExidx_cant_unwind) {
+ ElfInterfaceArm interface(&memory_);
+
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(1);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1004, 1);
+
+ RegsArm regs;
+ regs[ARM_REG_SP] = 0x10000;
+ regs[ARM_REG_LR] = 0x20000;
+ regs.set_sp(regs[ARM_REG_SP]);
+ regs.set_pc(0x1234);
+
+ bool finished;
+ ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_, &finished));
+ ASSERT_TRUE(finished);
+ ASSERT_EQ(0x10000U, regs.sp());
+ ASSERT_EQ(0x10000U, regs[ARM_REG_SP]);
+ ASSERT_EQ(0x1234U, regs.pc());
+}
+
+TEST_F(ElfInterfaceArmTest, StepExidx_refuse_unwind) {
+ ElfInterfaceArm interface(&memory_);
+
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(1);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1004, 0x808000b0);
+
+ RegsArm regs;
+ regs[ARM_REG_SP] = 0x10000;
+ regs[ARM_REG_LR] = 0x20000;
+ regs.set_sp(regs[ARM_REG_SP]);
+ regs.set_pc(0x1234);
+
+ bool finished;
+ ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_, &finished));
+ ASSERT_TRUE(finished);
+ ASSERT_EQ(0x10000U, regs.sp());
+ ASSERT_EQ(0x10000U, regs[ARM_REG_SP]);
+ ASSERT_EQ(0x1234U, regs.pc());
+}
+
} // namespace unwindstack
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
index ed1be3b..42a0246 100644
--- a/libunwindstack/tests/ElfTest.cpp
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -129,7 +129,8 @@
uint64_t func_offset;
ASSERT_FALSE(elf.GetFunctionName(0, &name, &func_offset));
- ASSERT_FALSE(elf.Step(0, nullptr, nullptr));
+ bool finished;
+ ASSERT_FALSE(elf.Step(0, nullptr, nullptr, &finished));
}
TEST_F(ElfTest, elf32_invalid_machine) {
diff --git a/libunwindstack/tests/RegsFake.h b/libunwindstack/tests/RegsFake.h
index c76ecaa..b667ec1 100644
--- a/libunwindstack/tests/RegsFake.h
+++ b/libunwindstack/tests/RegsFake.h
@@ -35,6 +35,7 @@
uint64_t GetAdjustedPc(uint64_t, Elf*) override { return 0; }
void SetFromRaw() override {}
+ bool SetPcFromReturnAddress(Memory*) override { return false; }
bool StepIfSignalHandler(uint64_t, Elf*, Memory*) override { return false; }
bool GetReturnAddressFromDefault(Memory*, uint64_t*) { return false; }
};
diff --git a/libunwindstack/tests/RegsTest.cpp b/libunwindstack/tests/RegsTest.cpp
index f549a50..3912e17 100644
--- a/libunwindstack/tests/RegsTest.cpp
+++ b/libunwindstack/tests/RegsTest.cpp
@@ -46,7 +46,7 @@
void InitHeaders() override {}
bool GetSoname(std::string*) override { return false; }
bool GetFunctionName(uint64_t, std::string*, uint64_t*) override { return false; }
- bool Step(uint64_t, Regs*, Memory*) override { return false; }
+ bool Step(uint64_t, Regs*, Memory*, bool*) override { return false; }
};
template <typename TypeParam>
@@ -62,6 +62,7 @@
uint64_t GetAdjustedPc(uint64_t, Elf*) override { return 0; }
void SetFromRaw() override {}
+ bool SetPcFromReturnAddress(Memory*) override { return false; }
bool StepIfSignalHandler(uint64_t, Elf*, Memory*) override { return false; }
};
diff --git a/libunwindstack/tests/UnwindTest.cpp b/libunwindstack/tests/UnwindTest.cpp
index a4f920a..9f9ca8b 100644
--- a/libunwindstack/tests/UnwindTest.cpp
+++ b/libunwindstack/tests/UnwindTest.cpp
@@ -31,12 +31,13 @@
#include <thread>
#include <vector>
-#include <unwindstack/Elf.h>
-#include <unwindstack/MapInfo.h>
+#include <android-base/stringprintf.h>
+
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsGetLocal.h>
+#include <unwindstack/Unwinder.h>
#include "TestUtils.h"
@@ -56,11 +57,11 @@
g_ucontext = 0;
}
-static std::vector<const char*> kFunctionOrder{"InnerFunction", "MiddleFunction", "OuterFunction"};
+static std::vector<const char*> kFunctionOrder{"OuterFunction", "MiddleFunction", "InnerFunction"};
-static std::vector<const char*> kFunctionSignalOrder{"SignalInnerFunction", "SignalMiddleFunction",
- "SignalOuterFunction", "InnerFunction",
- "MiddleFunction", "OuterFunction"};
+static std::vector<const char*> kFunctionSignalOrder{"OuterFunction", "MiddleFunction",
+ "InnerFunction", "SignalOuterFunction",
+ "SignalMiddleFunction", "SignalInnerFunction"};
static void SignalHandler(int, siginfo_t*, void* sigcontext) {
g_ucontext = reinterpret_cast<uintptr_t>(sigcontext);
@@ -86,62 +87,44 @@
SignalOuterFunction();
}
-static std::string ErrorMsg(const std::vector<const char*>& function_names, size_t index,
- std::stringstream& unwind_stream) {
+static std::string ErrorMsg(const std::vector<const char*>& function_names, Unwinder& unwinder) {
+ std::string unwind;
+ for (size_t i = 0; i < unwinder.NumFrames(); i++) {
+ unwind += unwinder.FormatFrame(i) + '\n';
+ }
+
return std::string(
"Unwind completed without finding all frames\n"
" Looking for function: ") +
- function_names[index] + "\n" + "Unwind data:\n" + unwind_stream.str();
+ function_names.front() + "\n" + "Unwind data:\n" + unwind;
}
static void VerifyUnwind(pid_t pid, Maps* maps, Regs* regs,
- std::vector<const char*>& function_names) {
- size_t function_name_index = 0;
+ std::vector<const char*> expected_function_names) {
+ auto process_memory(Memory::CreateProcessMemory(pid));
- auto process_memory = Memory::CreateProcessMemory(pid);
- std::stringstream unwind_stream;
- unwind_stream << std::hex;
- for (size_t frame_num = 0; frame_num < 64; frame_num++) {
- ASSERT_NE(0U, regs->pc()) << ErrorMsg(function_names, function_name_index, unwind_stream);
- MapInfo* map_info = maps->Find(regs->pc());
- ASSERT_TRUE(map_info != nullptr) << ErrorMsg(function_names, function_name_index, unwind_stream);
+ Unwinder unwinder(512, maps, regs, process_memory);
+ unwinder.Unwind();
- Elf* elf = map_info->GetElf(process_memory, true);
- uint64_t rel_pc = elf->GetRelPc(regs->pc(), map_info);
- uint64_t adjusted_rel_pc = rel_pc;
- if (frame_num != 0) {
- adjusted_rel_pc = regs->GetAdjustedPc(rel_pc, elf);
- }
- unwind_stream << " PC: 0x" << regs->pc() << " Rel: 0x" << adjusted_rel_pc;
- unwind_stream << " Map: ";
- if (!map_info->name.empty()) {
- unwind_stream << map_info->name;
- } else {
- unwind_stream << " anonymous";
- }
- unwind_stream << "<" << map_info->start << "-" << map_info->end << ">";
-
- std::string name;
- uint64_t func_offset;
- if (elf->GetFunctionName(adjusted_rel_pc, &name, &func_offset)) {
- if (name == function_names[function_name_index]) {
- if (++function_name_index == function_names.size()) {
- return;
- }
+ std::string expected_function = expected_function_names.back();
+ expected_function_names.pop_back();
+ for (auto& frame : unwinder.frames()) {
+ if (frame.function_name == expected_function) {
+ if (expected_function_names.empty()) {
+ break;
}
- unwind_stream << " " << name;
+ expected_function = expected_function_names.back();
+ expected_function_names.pop_back();
}
- unwind_stream << "\n";
- ASSERT_TRUE(elf->Step(rel_pc + map_info->elf_offset, regs, process_memory.get()))
- << ErrorMsg(function_names, function_name_index, unwind_stream);
}
- ASSERT_TRUE(false) << ErrorMsg(function_names, function_name_index, unwind_stream);
+
+ ASSERT_TRUE(expected_function_names.empty()) << ErrorMsg(expected_function_names, unwinder);
}
// This test assumes that this code is compiled with optimizations turned
// off. If this doesn't happen, then all of the calls will be optimized
// away.
-extern "C" void InnerFunction(bool local) {
+extern "C" void InnerFunction(bool local, bool trigger_invalid_call) {
if (local) {
LocalMaps maps;
ASSERT_TRUE(maps.Parse());
@@ -152,17 +135,21 @@
} else {
g_ready_for_remote = true;
g_ready = true;
+ if (trigger_invalid_call) {
+ void (*crash_func)() = nullptr;
+ crash_func();
+ }
while (!g_finish.load()) {
}
}
}
-extern "C" void MiddleFunction(bool local) {
- InnerFunction(local);
+extern "C" void MiddleFunction(bool local, bool trigger_invalid_call) {
+ InnerFunction(local, trigger_invalid_call);
}
-extern "C" void OuterFunction(bool local) {
- MiddleFunction(local);
+extern "C" void OuterFunction(bool local, bool trigger_invalid_call) {
+ MiddleFunction(local, trigger_invalid_call);
}
class UnwindTest : public ::testing::Test {
@@ -171,7 +158,7 @@
};
TEST_F(UnwindTest, local) {
- OuterFunction(true);
+ OuterFunction(true, false);
}
void WaitForRemote(pid_t pid, uint64_t addr, bool leave_attached, bool* completed) {
@@ -206,7 +193,7 @@
TEST_F(UnwindTest, remote) {
pid_t pid;
if ((pid = fork()) == 0) {
- OuterFunction(false);
+ OuterFunction(false, false);
exit(0);
}
ASSERT_NE(-1, pid);
@@ -231,7 +218,7 @@
std::atomic_int tid(0);
std::thread thread([&]() {
tid = syscall(__NR_gettid);
- OuterFunction(false);
+ OuterFunction(false, false);
});
struct sigaction act, oldact;
@@ -273,25 +260,27 @@
thread.join();
}
-static void RemoteThroughSignal(unsigned int sa_flags) {
+static void RemoteThroughSignal(int signal, unsigned int sa_flags) {
pid_t pid;
if ((pid = fork()) == 0) {
struct sigaction act, oldact;
memset(&act, 0, sizeof(act));
act.sa_sigaction = SignalCallerHandler;
act.sa_flags = SA_RESTART | SA_ONSTACK | sa_flags;
- ASSERT_EQ(0, sigaction(SIGUSR1, &act, &oldact));
+ ASSERT_EQ(0, sigaction(signal, &act, &oldact));
- OuterFunction(false);
+ OuterFunction(false, signal == SIGSEGV);
exit(0);
}
ASSERT_NE(-1, pid);
TestScopedPidReaper reap(pid);
bool completed;
- WaitForRemote(pid, reinterpret_cast<uint64_t>(&g_ready_for_remote), false, &completed);
- ASSERT_TRUE(completed) << "Timed out waiting for remote process to be ready.";
- ASSERT_EQ(0, kill(pid, SIGUSR1));
+ if (signal != SIGSEGV) {
+ WaitForRemote(pid, reinterpret_cast<uint64_t>(&g_ready_for_remote), false, &completed);
+ ASSERT_TRUE(completed) << "Timed out waiting for remote process to be ready.";
+ ASSERT_EQ(0, kill(pid, SIGUSR1));
+ }
WaitForRemote(pid, reinterpret_cast<uint64_t>(&g_signal_ready_for_remote), true, &completed);
ASSERT_TRUE(completed) << "Timed out waiting for remote process to be in signal handler.";
@@ -307,11 +296,19 @@
}
TEST_F(UnwindTest, remote_through_signal) {
- RemoteThroughSignal(0);
+ RemoteThroughSignal(SIGUSR1, 0);
}
TEST_F(UnwindTest, remote_through_signal_sa_siginfo) {
- RemoteThroughSignal(SA_SIGINFO);
+ RemoteThroughSignal(SIGUSR1, SA_SIGINFO);
+}
+
+TEST_F(UnwindTest, remote_through_signal_with_invalid_func) {
+ RemoteThroughSignal(SIGSEGV, 0);
+}
+
+TEST_F(UnwindTest, remote_through_signal_sa_siginfo_with_invalid_func) {
+ RemoteThroughSignal(SIGSEGV, SA_SIGINFO);
}
} // namespace unwindstack
diff --git a/libunwindstack/tools/unwind.cpp b/libunwindstack/tools/unwind.cpp
index 3614198..faac2ef 100644
--- a/libunwindstack/tools/unwind.cpp
+++ b/libunwindstack/tools/unwind.cpp
@@ -26,7 +26,11 @@
#include <sys/types.h>
#include <unistd.h>
+#include <memory>
#include <string>
+#include <vector>
+
+#include <android-base/stringprintf.h>
#include <unwindstack/Elf.h>
#include <unwindstack/MapInfo.h>
@@ -55,6 +59,62 @@
return ptrace(PTRACE_DETACH, pid, 0, 0) == 0;
}
+std::string GetFrameInfo(size_t frame_num, unwindstack::Regs* regs,
+ const std::shared_ptr<unwindstack::Memory>& process_memory,
+ unwindstack::MapInfo* map_info, uint64_t* rel_pc) {
+ bool bits32;
+ switch (regs->MachineType()) {
+ case EM_ARM:
+ case EM_386:
+ bits32 = true;
+ break;
+
+ default:
+ bits32 = false;
+ }
+
+ if (map_info == nullptr) {
+ if (bits32) {
+ return android::base::StringPrintf(" #%02zu pc %08" PRIx64, frame_num, regs->pc());
+ } else {
+ return android::base::StringPrintf(" #%02zu pc %016" PRIx64, frame_num, regs->pc());
+ }
+ }
+
+ unwindstack::Elf* elf = map_info->GetElf(process_memory, true);
+ *rel_pc = elf->GetRelPc(regs->pc(), map_info);
+ uint64_t adjusted_rel_pc = *rel_pc;
+ // Don't need to adjust the first frame pc.
+ if (frame_num != 0) {
+ adjusted_rel_pc = regs->GetAdjustedPc(*rel_pc, elf);
+ }
+
+ std::string line;
+ if (bits32) {
+ line = android::base::StringPrintf(" #%02zu pc %08" PRIx64, frame_num, adjusted_rel_pc);
+ } else {
+ line = android::base::StringPrintf(" #%02zu pc %016" PRIx64, frame_num, adjusted_rel_pc);
+ }
+ if (!map_info->name.empty()) {
+ line += " " + map_info->name;
+ if (map_info->elf_offset != 0) {
+ line += android::base::StringPrintf(" (offset 0x%" PRIx64 ")", map_info->elf_offset);
+ }
+ } else {
+ line += android::base::StringPrintf(" <anonymous:%" PRIx64 ">", map_info->offset);
+ }
+ uint64_t func_offset;
+ std::string func_name;
+ if (elf->GetFunctionName(adjusted_rel_pc, &func_name, &func_offset)) {
+ line += " (" + func_name;
+ if (func_offset != 0) {
+ line += android::base::StringPrintf("+%" PRId64, func_offset);
+ }
+ line += ')';
+ }
+ return line;
+}
+
void DoUnwind(pid_t pid) {
unwindstack::RemoteMaps remote_maps(pid);
if (!remote_maps.Parse()) {
@@ -68,7 +128,6 @@
return;
}
- bool bits32 = true;
printf("ABI: ");
switch (regs->MachineType()) {
case EM_ARM:
@@ -79,11 +138,9 @@
break;
case EM_AARCH64:
printf("arm64");
- bits32 = false;
break;
case EM_X86_64:
printf("x86_64");
- bits32 = false;
break;
default:
printf("unknown\n");
@@ -92,52 +149,48 @@
printf("\n");
auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
+ bool return_address_attempt = false;
+ std::vector<std::string> frames;
for (size_t frame_num = 0; frame_num < 64; frame_num++) {
- if (regs->pc() == 0) {
- break;
- }
unwindstack::MapInfo* map_info = remote_maps.Find(regs->pc());
+ uint64_t rel_pc;
+ frames.push_back(GetFrameInfo(frame_num, regs, process_memory, map_info, &rel_pc));
+ bool stepped;
if (map_info == nullptr) {
- printf("Failed to find map data for the pc\n");
- break;
- }
-
- unwindstack::Elf* elf = map_info->GetElf(process_memory, true);
-
- uint64_t rel_pc = elf->GetRelPc(regs->pc(), map_info);
- uint64_t adjusted_rel_pc = rel_pc;
- // Don't need to adjust the first frame pc.
- if (frame_num != 0) {
- adjusted_rel_pc = regs->GetAdjustedPc(rel_pc, elf);
- }
-
- std::string name;
- if (bits32) {
- printf(" #%02zu pc %08" PRIx64, frame_num, adjusted_rel_pc);
+ stepped = false;
} else {
- printf(" #%02zu pc %016" PRIx64, frame_num, adjusted_rel_pc);
+ bool finished;
+ stepped =
+ map_info->elf->Step(rel_pc + map_info->elf_offset, regs, process_memory.get(), &finished);
+ if (stepped && finished) {
+ break;
+ }
}
- if (!map_info->name.empty()) {
- printf(" %s", map_info->name.c_str());
- if (map_info->elf_offset != 0) {
- printf(" (offset 0x%" PRIx64 ")", map_info->elf_offset);
+ if (!stepped) {
+ if (return_address_attempt) {
+ // We tried the return address and it didn't work, remove the last
+ // two frames. If this bad frame is the only frame, only remove
+ // the last frame.
+ frames.pop_back();
+ if (frame_num != 1) {
+ frames.pop_back();
+ }
+ break;
+ } else {
+ // Steping didn't work, try this secondary method.
+ if (!regs->SetPcFromReturnAddress(process_memory.get())) {
+ break;
+ }
+ return_address_attempt = true;
}
} else {
- printf(" <anonymous:%" PRIx64 ">", map_info->offset);
+ return_address_attempt = false;
}
- uint64_t func_offset;
- if (elf->GetFunctionName(adjusted_rel_pc, &name, &func_offset)) {
- printf(" (%s", name.c_str());
- if (func_offset != 0) {
- printf("+%" PRId64, func_offset);
- }
- printf(")");
- }
- printf("\n");
+ }
- if (!elf->Step(rel_pc + map_info->elf_offset, regs, process_memory.get())) {
- break;
- }
+ // Print the frames.
+ for (auto& frame : frames) {
+ printf("%s\n", frame.c_str());
}
}