Merge "Add new EpollController class."
diff --git a/.clang-format-2 b/.clang-format-2
index fb967d8..aab4665 100644
--- a/.clang-format-2
+++ b/.clang-format-2
@@ -1,8 +1,4 @@
BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: true
-
-AccessModifierOffset: -1
ColumnLimit: 100
CommentPragmas: NOLINT:.*
DerivePointerAlignment: false
diff --git a/.clang-format-4 b/.clang-format-4
index fc4eb1b..1497447 100644
--- a/.clang-format-4
+++ b/.clang-format-4
@@ -1,7 +1,4 @@
BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
AccessModifierOffset: -2
ColumnLimit: 100
CommentPragmas: NOLINT:.*
diff --git a/adb/.clang-format b/adb/.clang-format
deleted file mode 100644
index fc4eb1b..0000000
--- a/adb/.clang-format
+++ /dev/null
@@ -1,13 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-AccessModifierOffset: -2
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 4
-PointerAlignment: Left
-TabWidth: 4
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/adb/.clang-format b/adb/.clang-format
new file mode 120000
index 0000000..1af4f51
--- /dev/null
+++ b/adb/.clang-format
@@ -0,0 +1 @@
+../.clang-format-4
\ No newline at end of file
diff --git a/adb/jdwp_service.cpp b/adb/jdwp_service.cpp
index 9589d88..f0dff06 100644
--- a/adb/jdwp_service.cpp
+++ b/adb/jdwp_service.cpp
@@ -179,8 +179,6 @@
fdevent* fde = nullptr;
std::vector<unique_fd> out_fds;
- char in_buf[PID_LEN + 1];
- ssize_t in_len = 0;
};
static size_t jdwp_process_list(char* buffer, size_t bufferlen) {
@@ -224,33 +222,16 @@
if (events & FDE_READ) {
if (proc->pid < 0) {
/* read the PID as a 4-hexchar string */
- if (proc->in_len < 0) {
- fatal("attempting to read JDWP pid again?");
- }
-
- char* p = proc->in_buf + proc->in_len;
- size_t size = PID_LEN - proc->in_len;
-
- ssize_t rc = TEMP_FAILURE_RETRY(recv(socket, p, size, 0));
- if (rc < 0) {
- if (errno == EAGAIN) {
- return;
- }
-
+ char buf[PID_LEN + 1];
+ ssize_t rc = TEMP_FAILURE_RETRY(recv(socket, buf, PID_LEN, 0));
+ if (rc != PID_LEN) {
D("failed to read jdwp pid: %s", strerror(errno));
goto CloseProcess;
}
+ buf[PID_LEN] = '\0';
- proc->in_len += rc;
- if (proc->in_len != PID_LEN) {
- return;
- }
-
- proc->in_buf[PID_LEN] = '\0';
- proc->in_len = -1;
-
- if (sscanf(proc->in_buf, "%04x", &proc->pid) != 1) {
- D("could not decode JDWP %p PID number: '%s'", proc, p);
+ if (sscanf(buf, "%04x", &proc->pid) != 1) {
+ D("could not decode JDWP %p PID number: '%s'", proc, buf);
goto CloseProcess;
}
@@ -405,7 +386,7 @@
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, sockname, socknamelen);
- s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ s = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (s < 0) {
D("could not create vm debug control socket. %d: %s", errno, strerror(errno));
return -1;
diff --git a/base/.clang-format b/base/.clang-format
deleted file mode 100644
index 2b83a1f..0000000
--- a/base/.clang-format
+++ /dev/null
@@ -1,11 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 2
-PointerAlignment: Left
-TabWidth: 2
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/base/.clang-format b/base/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/base/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/base/file.cpp b/base/file.cpp
index 81b04d7..378a405 100644
--- a/base/file.cpp
+++ b/base/file.cpp
@@ -212,6 +212,20 @@
}
#endif
+#if !defined(_WIN32)
+bool Realpath(const std::string& path, std::string* result) {
+ result->clear();
+
+ char* realpath_buf = realpath(path.c_str(), nullptr);
+ if (realpath_buf == nullptr) {
+ return false;
+ }
+ result->assign(realpath_buf);
+ free(realpath_buf);
+ return true;
+}
+#endif
+
std::string GetExecutablePath() {
#if defined(__linux__)
std::string path;
diff --git a/base/file_test.cpp b/base/file_test.cpp
index 1021326..266131e 100644
--- a/base/file_test.cpp
+++ b/base/file_test.cpp
@@ -159,6 +159,38 @@
#endif
}
+TEST(file, Realpath) {
+#if !defined(_WIN32)
+ TemporaryDir td;
+ std::string basename = android::base::Basename(td.path);
+ std::string dir_name = android::base::Dirname(td.path);
+ std::string base_dir_name = android::base::Basename(dir_name);
+
+ {
+ std::string path = dir_name + "/../" + base_dir_name + "/" + basename;
+ std::string result;
+ ASSERT_TRUE(android::base::Realpath(path, &result));
+ ASSERT_EQ(td.path, result);
+ }
+
+ {
+ std::string path = std::string(td.path) + "/..";
+ std::string result;
+ ASSERT_TRUE(android::base::Realpath(path, &result));
+ ASSERT_EQ(dir_name, result);
+ }
+
+ {
+ errno = 0;
+ std::string path = std::string(td.path) + "/foo.noent";
+ std::string result = "wrong";
+ ASSERT_TRUE(!android::base::Realpath(path, &result));
+ ASSERT_TRUE(result.empty());
+ ASSERT_EQ(ENOENT, errno);
+ }
+#endif
+}
+
TEST(file, GetExecutableDirectory) {
std::string path = android::base::GetExecutableDirectory();
ASSERT_NE("", path);
diff --git a/base/include/android-base/file.h b/base/include/android-base/file.h
index 33d1ab3..651f529 100644
--- a/base/include/android-base/file.h
+++ b/base/include/android-base/file.h
@@ -47,6 +47,7 @@
bool RemoveFileIfExists(const std::string& path, std::string* err = nullptr);
#if !defined(_WIN32)
+bool Realpath(const std::string& path, std::string* result);
bool Readlink(const std::string& path, std::string* result);
#endif
diff --git a/debuggerd/.clang-format b/debuggerd/.clang-format
deleted file mode 100644
index 9b7478c..0000000
--- a/debuggerd/.clang-format
+++ /dev/null
@@ -1,15 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 2
-ContinuationIndentWidth: 2
-PointerAlignment: Left
-TabWidth: 2
-UseTab: Never
-PenaltyExcessCharacter: 32
-
-Cpp11BracedListStyle: false
diff --git a/debuggerd/.clang-format b/debuggerd/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/debuggerd/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index b385ea5..2d6c7f5 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -1,5 +1,6 @@
cc_defaults {
name: "debuggerd_defaults",
+ defaults: ["linux_bionic_supported"],
cflags: [
"-Wall",
"-Wextra",
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 38b711f..88f390b 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -27,6 +27,7 @@
#include <unistd.h>
#include <limits>
+#include <map>
#include <memory>
#include <set>
#include <vector>
@@ -36,6 +37,7 @@
#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <cutils/sockets.h>
#include <log/log.h>
@@ -52,7 +54,21 @@
#include "debuggerd/util.h"
using android::base::unique_fd;
+using android::base::ReadFileToString;
using android::base::StringPrintf;
+using android::base::Trim;
+
+static std::string get_process_name(pid_t pid) {
+ std::string result = "<unknown>";
+ ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &result);
+ return result;
+}
+
+static std::string get_thread_name(pid_t tid) {
+ std::string result = "<unknown>";
+ ReadFileToString(StringPrintf("/proc/%d/comm", tid), &result);
+ return Trim(result);
+}
static bool pid_contains_tid(int pid_proc_fd, pid_t tid) {
struct stat st;
@@ -253,7 +269,7 @@
}
// Seize the siblings.
- std::set<pid_t> attached_siblings;
+ std::map<pid_t, std::string> threads;
{
std::set<pid_t> siblings;
if (!android::procinfo::GetProcessTids(target, &siblings)) {
@@ -269,12 +285,12 @@
if (!ptrace_seize_thread(target_proc_fd, sibling_tid, &attach_error)) {
LOG(WARNING) << attach_error;
} else {
- attached_siblings.insert(sibling_tid);
+ threads.emplace(sibling_tid, get_thread_name(sibling_tid));
}
}
}
- // Collect the backtrace map and open files, while the process still has PR_GET_DUMPABLE=1
+ // Collect the backtrace map, open files, and process/thread names, while we still have caps.
std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
if (!backtrace_map) {
LOG(FATAL) << "failed to create backtrace map";
@@ -284,6 +300,9 @@
OpenFilesList open_files;
populate_open_files_list(target, &open_files);
+ std::string process_name = get_process_name(main_tid);
+ threads.emplace(main_tid, get_thread_name(main_tid));
+
// Drop our capabilities now that we've attached to the threads we care about.
drop_capabilities();
@@ -341,10 +360,10 @@
std::string amfd_data;
if (backtrace) {
- dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
+ dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, process_name, threads, 0);
} else {
engrave_tombstone(output_fd.get(), backtrace_map.get(), &open_files, target, main_tid,
- &attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
+ process_name, threads, abort_address, fatal_signal ? &amfd_data : nullptr);
}
// We don't actually need to PTRACE_DETACH, as long as our tracees aren't in
diff --git a/debuggerd/libdebuggerd/backtrace.cpp b/debuggerd/libdebuggerd/backtrace.cpp
index df49aef..334d97f 100644
--- a/debuggerd/libdebuggerd/backtrace.cpp
+++ b/debuggerd/libdebuggerd/backtrace.cpp
@@ -38,18 +38,7 @@
#include "utility.h"
-static void dump_process_header(log_t* log, pid_t pid) {
- char path[PATH_MAX];
- char procnamebuf[1024];
- char* procname = NULL;
- FILE* fp;
-
- snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
- if ((fp = fopen(path, "r"))) {
- procname = fgets(procnamebuf, sizeof(procnamebuf), fp);
- fclose(fp);
- }
-
+static void dump_process_header(log_t* log, pid_t pid, const char* process_name) {
time_t t = time(NULL);
struct tm tm;
localtime_r(&t, &tm);
@@ -57,8 +46,8 @@
strftime(timestr, sizeof(timestr), "%F %T", &tm);
_LOG(log, logtype::BACKTRACE, "\n\n----- pid %d at %s -----\n", pid, timestr);
- if (procname) {
- _LOG(log, logtype::BACKTRACE, "Cmd line: %s\n", procname);
+ if (process_name) {
+ _LOG(log, logtype::BACKTRACE, "Cmd line: %s\n", process_name);
}
_LOG(log, logtype::BACKTRACE, "ABI: '%s'\n", ABI_STRING);
}
@@ -67,28 +56,13 @@
_LOG(log, logtype::BACKTRACE, "\n----- end %d -----\n", pid);
}
-static void log_thread_name(log_t* log, pid_t tid) {
- FILE* fp;
- char buf[1024];
- char path[PATH_MAX];
- char* threadname = NULL;
-
- snprintf(path, sizeof(path), "/proc/%d/comm", tid);
- if ((fp = fopen(path, "r"))) {
- threadname = fgets(buf, sizeof(buf), fp);
- fclose(fp);
- if (threadname) {
- size_t len = strlen(threadname);
- if (len && threadname[len - 1] == '\n') {
- threadname[len - 1] = '\0';
- }
- }
- }
- _LOG(log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", threadname ? threadname : "<unknown>", tid);
+static void log_thread_name(log_t* log, pid_t tid, const char* thread_name) {
+ _LOG(log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", thread_name, tid);
}
-static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid) {
- log_thread_name(log, tid);
+static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid,
+ const std::string& thread_name) {
+ log_thread_name(log, tid, thread_name.c_str());
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
if (backtrace->Unwind(0)) {
@@ -99,17 +73,21 @@
}
}
-void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid,
- const std::set<pid_t>& siblings, std::string* amfd_data) {
+void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid, const std::string& process_name,
+ const std::map<pid_t, std::string>& threads, std::string* amfd_data) {
log_t log;
log.tfd = fd;
log.amfd_data = amfd_data;
- dump_process_header(&log, pid);
- dump_thread(&log, map, pid, tid);
+ dump_process_header(&log, pid, process_name.c_str());
+ dump_thread(&log, map, pid, tid, threads.find(tid)->second.c_str());
- for (pid_t sibling : siblings) {
- dump_thread(&log, map, pid, sibling);
+ for (const auto& it : threads) {
+ pid_t thread_tid = it.first;
+ const std::string& thread_name = it.second;
+ if (thread_tid != tid) {
+ dump_thread(&log, map, pid, thread_tid, thread_name.c_str());
+ }
}
dump_process_footer(&log, pid);
@@ -123,7 +101,9 @@
log.tfd = output_fd;
log.amfd_data = nullptr;
- log_thread_name(&log, tid);
+ char thread_name[16];
+ read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
+ log_thread_name(&log, tid, thread_name);
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
if (backtrace->Unwind(0, ucontext)) {
@@ -139,7 +119,9 @@
log.tfd = output_fd;
log.amfd_data = nullptr;
- dump_process_header(&log, getpid());
+ char process_name[128];
+ read_with_default("/proc/self/cmdline", process_name, sizeof(process_name), "<unknown>");
+ dump_process_header(&log, getpid(), process_name);
}
void dump_backtrace_footer(int output_fd) {
diff --git a/debuggerd/libdebuggerd/include/backtrace.h b/debuggerd/libdebuggerd/include/backtrace.h
index 5bfdac8..fe738f1 100644
--- a/debuggerd/libdebuggerd/include/backtrace.h
+++ b/debuggerd/libdebuggerd/include/backtrace.h
@@ -20,7 +20,7 @@
#include <sys/types.h>
#include <sys/ucontext.h>
-#include <set>
+#include <map>
#include <string>
#include "utility.h"
@@ -30,8 +30,8 @@
// Dumps a backtrace using a format similar to what Dalvik uses so that the result
// can be intermixed in a bug report.
-void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid,
- const std::set<pid_t>& siblings, std::string* amfd_data);
+void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid, const std::string& process_name,
+ const std::map<pid_t, std::string>& threads, std::string* amfd_data);
/* Dumps the backtrace in the backtrace data structure to the log. */
void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix);
diff --git a/debuggerd/libdebuggerd/include/tombstone.h b/debuggerd/libdebuggerd/include/tombstone.h
index d2a4a4b..79743b6 100644
--- a/debuggerd/libdebuggerd/include/tombstone.h
+++ b/debuggerd/libdebuggerd/include/tombstone.h
@@ -20,7 +20,8 @@
#include <stdbool.h>
#include <stddef.h>
#include <sys/types.h>
-#include <set>
+
+#include <map>
#include <string>
#include "open_files_list.h"
@@ -34,9 +35,9 @@
int open_tombstone(std::string* path);
/* Creates a tombstone file and writes the crash dump to it. */
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map,
- const OpenFilesList* open_files, pid_t pid, pid_t tid,
- const std::set<pid_t>* siblings, uintptr_t abort_msg_address,
+void engrave_tombstone(int tombstone_fd, BacktraceMap* map, const OpenFilesList* open_files,
+ pid_t pid, pid_t tid, const std::string& process_name,
+ const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address,
std::string* amfd_data);
void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
diff --git a/debuggerd/libdebuggerd/include/utility.h b/debuggerd/libdebuggerd/include/utility.h
index bbc4546..e5e5106 100644
--- a/debuggerd/libdebuggerd/include/utility.h
+++ b/debuggerd/libdebuggerd/include/utility.h
@@ -83,4 +83,6 @@
void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...);
+void read_with_default(const char* path, char* buf, size_t len, const char* default_value);
+
#endif // _DEBUGGERD_UTILITY_H
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index c05ccc3..c23da44 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -32,8 +32,10 @@
#include <memory>
#include <string>
-#include <android/log.h>
+#include <android-base/file.h>
#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+#include <android/log.h>
#include <backtrace/Backtrace.h>
#include <backtrace/BacktraceMap.h>
#include <cutils/properties.h>
@@ -247,41 +249,16 @@
dump_signal_info(log, &si);
}
-static void dump_thread_info(log_t* log, pid_t pid, pid_t tid) {
- char path[64];
- char threadnamebuf[1024];
- char* threadname = nullptr;
- FILE *fp;
-
- snprintf(path, sizeof(path), "/proc/%d/comm", tid);
- if ((fp = fopen(path, "r"))) {
- threadname = fgets(threadnamebuf, sizeof(threadnamebuf), fp);
- fclose(fp);
- if (threadname) {
- size_t len = strlen(threadname);
- if (len && threadname[len - 1] == '\n') {
- threadname[len - 1] = '\0';
- }
- }
- }
+static void dump_thread_info(log_t* log, pid_t pid, pid_t tid, const char* process_name,
+ const char* thread_name) {
// Blacklist logd, logd.reader, logd.writer, logd.auditd, logd.control ...
- static const char logd[] = "logd";
- if (threadname != nullptr && !strncmp(threadname, logd, sizeof(logd) - 1)
- && (!threadname[sizeof(logd) - 1] || (threadname[sizeof(logd) - 1] == '.'))) {
+ // TODO: Why is this controlled by thread name?
+ if (strcmp(thread_name, "logd") == 0 || strncmp(thread_name, "logd.", 4) == 0) {
log->should_retrieve_logcat = false;
}
- char procnamebuf[1024];
- char* procname = nullptr;
-
- snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
- if ((fp = fopen(path, "r"))) {
- procname = fgets(procnamebuf, sizeof(procnamebuf), fp);
- fclose(fp);
- }
-
- _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s >>> %s <<<\n", pid, tid,
- threadname ? threadname : "UNKNOWN", procname ? procname : "UNKNOWN");
+ _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s >>> %s <<<\n", pid, tid, thread_name,
+ process_name);
}
static void dump_stack_segment(
@@ -493,13 +470,14 @@
}
}
-static void dump_thread(log_t* log, pid_t pid, pid_t tid, BacktraceMap* map,
+static void dump_thread(log_t* log, pid_t pid, pid_t tid, const std::string& process_name,
+ const std::string& thread_name, BacktraceMap* map,
uintptr_t abort_msg_address, bool primary_thread) {
log->current_tid = tid;
if (!primary_thread) {
_LOG(log, logtype::THREAD, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
}
- dump_thread_info(log, pid, tid);
+ dump_thread_info(log, pid, tid, process_name.c_str(), thread_name.c_str());
dump_signal_info(log, tid);
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
@@ -654,9 +632,9 @@
}
// Dumps all information about the specified pid to the tombstone.
-static void dump_crash(log_t* log, BacktraceMap* map,
- const OpenFilesList* open_files, pid_t pid, pid_t tid,
- const std::set<pid_t>* siblings, uintptr_t abort_msg_address) {
+static void dump_crash(log_t* log, BacktraceMap* map, const OpenFilesList* open_files, pid_t pid,
+ pid_t tid, const std::string& process_name,
+ const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address) {
// don't copy log messages to tombstone unless this is a dev device
char value[PROPERTY_VALUE_MAX];
property_get("ro.debuggable", value, "0");
@@ -665,14 +643,17 @@
_LOG(log, logtype::HEADER,
"*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
dump_header_info(log);
- dump_thread(log, pid, tid, map, abort_msg_address, true);
+ dump_thread(log, pid, tid, process_name, threads.find(tid)->second, map, abort_msg_address, true);
if (want_logs) {
dump_logs(log, pid, 5);
}
- if (siblings && !siblings->empty()) {
- for (pid_t sibling : *siblings) {
- dump_thread(log, pid, sibling, map, 0, false);
+ for (const auto& it : threads) {
+ pid_t thread_tid = it.first;
+ const std::string& thread_name = it.second;
+
+ if (thread_tid != tid) {
+ dump_thread(log, pid, thread_tid, process_name, thread_name, map, 0, false);
}
}
@@ -739,16 +720,16 @@
return fd;
}
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map,
- const OpenFilesList* open_files, pid_t pid, pid_t tid,
- const std::set<pid_t>* siblings, uintptr_t abort_msg_address,
+void engrave_tombstone(int tombstone_fd, BacktraceMap* map, const OpenFilesList* open_files,
+ pid_t pid, pid_t tid, const std::string& process_name,
+ const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address,
std::string* amfd_data) {
log_t log;
log.current_tid = tid;
log.crashed_tid = tid;
log.tfd = tombstone_fd;
log.amfd_data = amfd_data;
- dump_crash(&log, map, open_files, pid, tid, siblings, abort_msg_address);
+ dump_crash(&log, map, open_files, pid, tid, process_name, threads, abort_msg_address);
}
void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
@@ -762,7 +743,13 @@
log.tfd = tombstone_fd;
log.amfd_data = nullptr;
- dump_thread_info(&log, pid, tid);
+ char thread_name[16];
+ char process_name[128];
+
+ read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
+ read_with_default("/proc/self/cmdline", process_name, sizeof(process_name), "<unknown>");
+
+ dump_thread_info(&log, pid, tid, thread_name, process_name);
dump_signal_info(&log, siginfo);
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 744cd72..22fde5e 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -28,6 +28,7 @@
#include <string>
#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
#include <backtrace/Backtrace.h>
#include <log/log.h>
@@ -202,3 +203,20 @@
_LOG(log, logtype::MEMORY, "%s %s\n", logline.c_str(), ascii.c_str());
}
}
+
+void read_with_default(const char* path, char* buf, size_t len, const char* default_value) {
+ android::base::unique_fd fd(open(path, O_RDONLY));
+ if (fd != -1) {
+ int rc = TEMP_FAILURE_RETRY(read(fd.get(), buf, len - 1));
+ if (rc != -1) {
+ buf[rc] = '\0';
+
+ // Trim trailing newlines.
+ if (rc > 0 && buf[rc - 1] == '\n') {
+ buf[rc - 1] = '\0';
+ }
+ return;
+ }
+ }
+ strcpy(buf, default_value);
+}
diff --git a/fastboot/.clang-format b/fastboot/.clang-format
deleted file mode 100644
index bcb8d8a..0000000
--- a/fastboot/.clang-format
+++ /dev/null
@@ -1,15 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: Inline
-
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 4
-ContinuationIndentWidth: 8
-ConstructorInitializerIndentWidth: 8
-AccessModifierOffset: -2
-PointerAlignment: Left
-TabWidth: 4
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/fastboot/.clang-format b/fastboot/.clang-format
new file mode 120000
index 0000000..1af4f51
--- /dev/null
+++ b/fastboot/.clang-format
@@ -0,0 +1 @@
+../.clang-format-4
\ No newline at end of file
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index a4a0b52..2927b16 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -1245,20 +1245,17 @@
return 0;
}
-static int do_oem_command(int argc, char **argv)
-{
- char command[256];
+static int do_oem_command(int argc, char** argv) {
if (argc <= 1) return 0;
- command[0] = 0;
- while(1) {
- strcat(command,*argv);
+ std::string command;
+ while (argc > 0) {
+ command += *argv;
skip(1);
- if(argc == 0) break;
- strcat(command," ");
+ if (argc != 0) command += " ";
}
- fb_queue_command(command,"");
+ fb_queue_command(command.c_str(), "");
return 0;
}
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 6646a3c..67cc5be 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -650,7 +650,7 @@
{
std::string fstab_buf = read_fstab_from_dt();
if (fstab_buf.empty()) {
- LERROR << __FUNCTION__ << "(): failed to read fstab from dt";
+ LINFO << __FUNCTION__ << "(): failed to read fstab from dt";
return nullptr;
}
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 8e2bc1c..d200070 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -123,11 +123,13 @@
#define AID_DNS_TETHER 1052 /* DNS resolution daemon (tether: dnsmasq) */
#define AID_WEBVIEW_ZYGOTE 1053 /* WebView zygote process */
#define AID_VEHICLE_NETWORK 1054 /* Vehicle network service */
-#define AID_MEDIA_AUDIO 1055 /* GID for audio files on internal media storage */
-#define AID_MEDIA_VIDEO 1056 /* GID for video files on internal media storage */
-#define AID_MEDIA_IMAGE 1057 /* GID for image files on internal media storage */
+#define AID_MEDIA_AUDIO 1055 /* GID for audio files on internal media storage */
+#define AID_MEDIA_VIDEO 1056 /* GID for video files on internal media storage */
+#define AID_MEDIA_IMAGE 1057 /* GID for image files on internal media storage */
#define AID_TOMBSTONED 1058 /* tombstoned user */
-#define AID_MEDIA_OBB 1059 /* GID for OBB files on internal media storage */
+#define AID_MEDIA_OBB 1059 /* GID for OBB files on internal media storage */
+#define AID_ESE 1060 /* embedded secure element (eSE) subsystem */
+#define AID_OTA_UPDATE 1061 /* resource tracking UID for OTA updates */
/* Changes to this file must be made in AOSP, *not* in internal branches. */
#define AID_SHELL 2000 /* adb and debug shell user */
diff --git a/init/init.cpp b/init/init.cpp
index 4e31865..d095685 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -1108,27 +1108,26 @@
return watchdogd_main(argc, argv);
}
- boot_clock::time_point start_time = boot_clock::now();
-
- // Clear the umask.
- umask(0);
-
add_environment("PATH", _PATH_DEFPATH);
bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
- // Don't expose the raw commandline to unprivileged processes.
- chmod("/proc/cmdline", 0440);
-
- // Get the basic filesystem setup we need put together in the initramdisk
- // on / and then we'll let the rc file figure out the rest.
if (is_first_stage) {
+ boot_clock::time_point start_time = boot_clock::now();
+
+ // Clear the umask.
+ umask(0);
+
+ // Get the basic filesystem setup we need put together in the initramdisk
+ // on / and then we'll let the rc file figure out the rest.
mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
mkdir("/dev/pts", 0755);
mkdir("/dev/socket", 0755);
mount("devpts", "/dev/pts", "devpts", 0, NULL);
#define MAKE_STR(x) __STRING(x)
mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
+ // Don't expose the raw commandline to unprivileged processes.
+ chmod("/proc/cmdline", 0440);
gid_t groups[] = { AID_READPROC };
setgroups(arraysize(groups), groups);
mount("sysfs", "/sys", "sysfs", 0, NULL);
@@ -1136,15 +1135,13 @@
mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
- }
- // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
- // talk to the outside world...
- InitKernelLogging(argv);
+ // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
+ // talk to the outside world...
+ InitKernelLogging(argv);
- LOG(INFO) << "init " << (is_first_stage ? "first" : "second") << " stage started!";
+ LOG(INFO) << "init first stage started!";
- if (is_first_stage) {
if (!early_mount()) {
LOG(ERROR) << "Failed to mount required partitions early ...";
panic();
@@ -1168,41 +1165,47 @@
char* path = argv[0];
char* args[] = { path, nullptr };
- if (execv(path, args) == -1) {
- PLOG(ERROR) << "execv(\"" << path << "\") failed";
- security_failure();
- }
- } else {
- // Indicate that booting is in progress to background fw loaders, etc.
- close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
+ execv(path, args);
- property_init();
-
- // If arguments are passed both on the command line and in DT,
- // properties set in DT always have priority over the command-line ones.
- process_kernel_dt();
- process_kernel_cmdline();
-
- // Propagate the kernel variables to internal variables
- // used by init as well as the current required properties.
- export_kernel_boot_props();
-
- // Make the time that init started available for bootstat to log.
- property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
- property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
-
- // Set libavb version for Framework-only OTA match in Treble build.
- property_set("ro.boot.init.avb_version", std::to_string(AVB_MAJOR_VERSION).c_str());
-
- // Clean up our environment.
- unsetenv("INIT_SECOND_STAGE");
- unsetenv("INIT_STARTED_AT");
- unsetenv("INIT_SELINUX_TOOK");
-
- // Now set up SELinux for second stage.
- selinux_initialize(false);
+ // execv() only returns if an error happened, in which case we
+ // panic and never fall through this conditional.
+ PLOG(ERROR) << "execv(\"" << path << "\") failed";
+ security_failure();
}
+ // At this point we're in the second stage of init.
+ InitKernelLogging(argv);
+ LOG(INFO) << "init second stage started!";
+
+ // Indicate that booting is in progress to background fw loaders, etc.
+ close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
+
+ property_init();
+
+ // If arguments are passed both on the command line and in DT,
+ // properties set in DT always have priority over the command-line ones.
+ process_kernel_dt();
+ process_kernel_cmdline();
+
+ // Propagate the kernel variables to internal variables
+ // used by init as well as the current required properties.
+ export_kernel_boot_props();
+
+ // Make the time that init started available for bootstat to log.
+ property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
+ property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
+
+ // Set libavb version for Framework-only OTA match in Treble build.
+ property_set("ro.boot.init.avb_version", std::to_string(AVB_MAJOR_VERSION).c_str());
+
+ // Clean up our environment.
+ unsetenv("INIT_SECOND_STAGE");
+ unsetenv("INIT_STARTED_AT");
+ unsetenv("INIT_SELINUX_TOOK");
+
+ // Now set up SELinux for second stage.
+ selinux_initialize(false);
+
// These directories were necessarily created before initial policy load
// and therefore need their security context restored to the proper value.
// This must happen before /dev is populated by ueventd.
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index 5b31ecb..0e7c6f3 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -80,6 +80,18 @@
static_libs: ["libcutils"],
host_ldlibs: ["-lrt"],
},
+ linux_bionic: {
+ enabled: true,
+ srcs: libbacktrace_sources,
+
+ shared_libs: [
+ "libbase",
+ "liblog",
+ "libunwind",
+ ],
+
+ static_libs: ["libcutils"],
+ },
android: {
srcs: libbacktrace_sources,
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index cf31195..f668f18 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -41,9 +41,12 @@
host_supported: true,
export_include_dirs: ["include"],
target: {
- windows: {
- enabled: true,
- },
+ linux_bionic: {
+ enabled: true,
+ },
+ windows: {
+ enabled: true,
+ },
},
}
@@ -68,11 +71,14 @@
"threads.c",
],
-
target: {
host: {
srcs: ["dlmalloc_stubs.c"],
},
+ linux_bionic: {
+ enabled: true,
+ exclude_srcs: ["dlmalloc_stubs.c"],
+ },
not_windows: {
srcs: libcutils_nonwindows_sources + [
"ashmem-host.c",
diff --git a/libcutils/include/cutils/qtaguid.h b/libcutils/include/cutils/qtaguid.h
index f8550fd..803fe0d 100644
--- a/libcutils/include/cutils/qtaguid.h
+++ b/libcutils/include/cutils/qtaguid.h
@@ -26,13 +26,15 @@
#endif
/*
- * Set tags (and owning UIDs) for network sockets.
-*/
+ * Set tags (and owning UIDs) for network sockets. The socket must be untagged
+ * by calling qtaguid_untagSocket() before closing it, otherwise the qtaguid
+ * module will keep a reference to it even after close.
+ */
extern int qtaguid_tagSocket(int sockfd, int tag, uid_t uid);
/*
* Untag a network socket before closing.
-*/
+ */
extern int qtaguid_untagSocket(int sockfd);
/*
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index 5a52377..cc95425 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -42,7 +42,10 @@
#include <private/android_logger.h>
#ifndef TEST_PREFIX
-#ifdef __ANDROID__ // make sure we always run code if compiled for android
+#ifdef TEST_LOGGER
+#define TEST_PREFIX android_set_log_transport(TEST_LOGGER);
+// make sure we always run code despite overrides if compiled for android
+#elif defined(__ANDROID__)
#define TEST_PREFIX
#endif
#endif
@@ -1778,7 +1781,14 @@
// liblog.android_logger_get_ is one of those tests that has no recourse
// and that would be adversely affected by emptying the log if it was run
// right after this test.
- system("stop logd");
+ if (getuid() != AID_ROOT) {
+ fprintf(
+ stderr,
+ "WARNING: test conditions request being run as root and not AID=%d\n",
+ getuid());
+ }
+
+ system((getuid() == AID_ROOT) ? "stop logd" : "su 0 stop logd");
usleep(1000000);
// A clean stop like we are testing returns -ENOENT, but in the _real_
@@ -1789,20 +1799,20 @@
int ret = __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts));
std::string content = android::base::StringPrintf(
"__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) = %d %s\n",
- ret, strerror(-ret));
+ ret, (ret <= 0) ? strerror(-ret) : "(content sent)");
EXPECT_TRUE(
IsOk((ret == -ENOENT) || (ret == -ENOTCONN) || (ret == -ECONNREFUSED),
content));
ret = __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts));
content = android::base::StringPrintf(
"__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) = %d %s\n",
- ret, strerror(-ret));
+ ret, (ret <= 0) ? strerror(-ret) : "(content sent)");
EXPECT_TRUE(
IsOk((ret == -ENOENT) || (ret == -ENOTCONN) || (ret == -ECONNREFUSED),
content));
EXPECT_EQ(0, count_matching_ts(ts));
- system("start logd");
+ system((getuid() == AID_ROOT) ? "start logd" : "su 0 start logd");
usleep(1000000);
EXPECT_EQ(0, count_matching_ts(ts));
@@ -1831,14 +1841,24 @@
char persist[PROP_VALUE_MAX];
char readonly[PROP_VALUE_MAX];
+ // First part of this test requires the test itself to have the appropriate
+ // permissions. If we do not have them, we can not override them, so we
+ // bail rather than give a failing grade.
property_get(persist_key, persist, "");
+ fprintf(stderr, "INFO: getprop %s -> %s\n", persist_key, persist);
property_get(readonly_key, readonly, nothing_val);
+ fprintf(stderr, "INFO: getprop %s -> %s\n", readonly_key, readonly);
if (!strcmp(readonly, nothing_val)) {
EXPECT_FALSE(__android_log_security());
- fprintf(stderr, "Warning, setting ro.device_owner to a domain\n");
- property_set(readonly_key, "com.google.android.SecOps.DeviceOwner");
+ fprintf(stderr, "WARNING: setting ro.device_owner to a domain\n");
+ static const char domain[] = "com.google.android.SecOps.DeviceOwner";
+ property_set(readonly_key, domain);
+ usleep(20000); // property system does not guarantee performance, rest ...
+ property_get(readonly_key, readonly, nothing_val);
+ EXPECT_STREQ(readonly, domain);
} else if (!strcasecmp(readonly, "false") || !readonly[0]) {
+ // not enough permissions to run
EXPECT_FALSE(__android_log_security());
return;
}
@@ -2120,10 +2140,19 @@
}
#endif
+// Make multiple tests and re-tests orthogonal to prevent falsing.
+#ifdef TEST_LOGGER
+#define UNIQUE_TAG(X) \
+ (0x12340000 + (((X) + sizeof(int) + sizeof(void*)) << 8) + TEST_LOGGER)
+#else
+#define UNIQUE_TAG(X) \
+ (0x12340000 + (((X) + sizeof(int) + sizeof(void*)) << 8) + 0xBA)
+#endif
+
TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__typical) {
#ifdef TEST_PREFIX
int count;
- android_errorWriteWithInfoLog_helper(123456781, "test-subtag", -1,
+ android_errorWriteWithInfoLog_helper(UNIQUE_TAG(1), "test-subtag", -1,
max_payload_buf, 200, count);
EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
@@ -2135,7 +2164,7 @@
android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
#ifdef TEST_PREFIX
int count;
- android_errorWriteWithInfoLog_helper(123456782, "test-subtag", -1,
+ android_errorWriteWithInfoLog_helper(UNIQUE_TAG(2), "test-subtag", -1,
max_payload_buf, sizeof(max_payload_buf),
count);
EXPECT_EQ(SUPPORTS_END_TO_END, count);
@@ -2148,8 +2177,8 @@
android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
#ifdef TEST_PREFIX
int count;
- android_errorWriteWithInfoLog_helper(123456783, "test-subtag", -1, NULL, 200,
- count);
+ android_errorWriteWithInfoLog_helper(UNIQUE_TAG(3), "test-subtag", -1, NULL,
+ 200, count);
EXPECT_EQ(0, count);
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2161,7 +2190,7 @@
#ifdef TEST_PREFIX
int count;
android_errorWriteWithInfoLog_helper(
- 123456784, "abcdefghijklmnopqrstuvwxyz now i know my abc", -1,
+ UNIQUE_TAG(4), "abcdefghijklmnopqrstuvwxyz now i know my abc", -1,
max_payload_buf, 200, count);
EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
@@ -2296,7 +2325,7 @@
TEST(liblog, android_errorWriteLog__android_logger_list_read__success) {
#ifdef TEST_PREFIX
int count;
- android_errorWriteLog_helper(123456785, "test-subtag", count);
+ android_errorWriteLog_helper(UNIQUE_TAG(5), "test-subtag", count);
EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -2306,7 +2335,7 @@
TEST(liblog, android_errorWriteLog__android_logger_list_read__null_subtag) {
#ifdef TEST_PREFIX
int count;
- android_errorWriteLog_helper(123456786, NULL, count);
+ android_errorWriteLog_helper(UNIQUE_TAG(6), NULL, count);
EXPECT_EQ(0, count);
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/liblog/tests/liblog_test_default.cpp b/liblog/tests/liblog_test_default.cpp
index cbd0d25..9fc443c 100644
--- a/liblog/tests/liblog_test_default.cpp
+++ b/liblog/tests/liblog_test_default.cpp
@@ -1,5 +1,5 @@
#ifdef __ANDROID__
#include <log/log_transport.h>
-#define TEST_PREFIX android_set_log_transport(LOGGER_DEFAULT);
+#define TEST_LOGGER LOGGER_DEFAULT
#endif
#include "liblog_test.cpp"
diff --git a/liblog/tests/liblog_test_local.cpp b/liblog/tests/liblog_test_local.cpp
index 9d7b3d7..451beca 100644
--- a/liblog/tests/liblog_test_local.cpp
+++ b/liblog/tests/liblog_test_local.cpp
@@ -1,4 +1,4 @@
#include <log/log_transport.h>
#define liblog liblog_local
-#define TEST_PREFIX android_set_log_transport(LOGGER_LOCAL);
+#define TEST_LOGGER LOGGER_LOCAL
#include "liblog_test.cpp"
diff --git a/liblog/tests/liblog_test_stderr.cpp b/liblog/tests/liblog_test_stderr.cpp
index f9e4e1f..abc1b9c 100644
--- a/liblog/tests/liblog_test_stderr.cpp
+++ b/liblog/tests/liblog_test_stderr.cpp
@@ -1,5 +1,5 @@
#include <log/log_transport.h>
#define liblog liblog_stderr
-#define TEST_PREFIX android_set_log_transport(LOGGER_STDERR);
+#define TEST_LOGGER LOGGER_STDERR
#define USING_LOGGER_STDERR
#include "liblog_test.cpp"
diff --git a/liblog/tests/liblog_test_stderr_local.cpp b/liblog/tests/liblog_test_stderr_local.cpp
index 21406ca..bb5c7ae 100644
--- a/liblog/tests/liblog_test_stderr_local.cpp
+++ b/liblog/tests/liblog_test_stderr_local.cpp
@@ -1,4 +1,4 @@
#include <log/log_transport.h>
#define liblog liblog_stderr_local
-#define TEST_PREFIX android_set_log_transport(LOGGER_LOCAL | LOGGER_STDERR);
+#define TEST_LOGGER (LOGGER_LOCAL | LOGGER_STDERR)
#include "liblog_test.cpp"
diff --git a/libprocinfo/.clang-format b/libprocinfo/.clang-format
deleted file mode 100644
index b8c6428..0000000
--- a/libprocinfo/.clang-format
+++ /dev/null
@@ -1,14 +0,0 @@
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
-
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 2
-PointerAlignment: Left
-TabWidth: 2
-UseTab: Never
-PenaltyExcessCharacter: 32
-
-Cpp11BracedListStyle: false
diff --git a/libprocinfo/.clang-format b/libprocinfo/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/libprocinfo/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/libprocinfo/Android.bp b/libprocinfo/Android.bp
index 8e17f1b..c13ffe9 100644
--- a/libprocinfo/Android.bp
+++ b/libprocinfo/Android.bp
@@ -35,6 +35,9 @@
darwin: {
enabled: false,
},
+ linux_bionic: {
+ enabled: true,
+ },
windows: {
enabled: false,
},
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 9bb1304..ece623b 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -30,6 +30,15 @@
enabled: false,
},
},
+
+ multilib: {
+ lib32: {
+ suffix: "32",
+ },
+ lib64: {
+ suffix: "64",
+ },
+ },
}
cc_defaults {
@@ -38,8 +47,12 @@
srcs: [
"ArmExidx.cpp",
- "Memory.cpp",
+ "Elf.cpp",
+ "ElfInterface.cpp",
+ "ElfInterfaceArm.cpp",
"Log.cpp",
+ "Regs.cpp",
+ "Memory.cpp",
],
shared_libs: [
@@ -74,6 +87,9 @@
srcs: [
"tests/ArmExidxDecodeTest.cpp",
"tests/ArmExidxExtractTest.cpp",
+ "tests/ElfInterfaceArmTest.cpp",
+ "tests/ElfInterfaceTest.cpp",
+ "tests/ElfTest.cpp",
"tests/LogFake.cpp",
"tests/MemoryFake.cpp",
"tests/MemoryFileTest.cpp",
@@ -93,15 +109,6 @@
"liblog",
],
- multilib: {
- lib32: {
- suffix: "32",
- },
- lib64: {
- suffix: "64",
- },
- },
-
target: {
linux: {
host_ldlibs: [
@@ -130,3 +137,31 @@
"libunwindstack_debug",
],
}
+
+//-------------------------------------------------------------------------
+// Utility Executables
+//-------------------------------------------------------------------------
+cc_defaults {
+ name: "libunwindstack_executables",
+ defaults: ["libunwindstack_flags"],
+
+ shared_libs: [
+ "libunwindstack",
+ "libbase",
+ ],
+
+ static_libs: [
+ "liblog",
+ ],
+
+ compile_multilib: "both",
+}
+
+cc_binary {
+ name: "unwind_info",
+ defaults: ["libunwindstack_executables"],
+
+ srcs: [
+ "unwind_info.cpp",
+ ],
+}
diff --git a/libunwindstack/ArmExidx.cpp b/libunwindstack/ArmExidx.cpp
index 3b78918..12adf57 100644
--- a/libunwindstack/ArmExidx.cpp
+++ b/libunwindstack/ArmExidx.cpp
@@ -25,6 +25,8 @@
#include "ArmExidx.h"
#include "Log.h"
#include "Machine.h"
+#include "Memory.h"
+#include "Regs.h"
void ArmExidx::LogRawData() {
std::string log_str("Raw Data:");
@@ -216,10 +218,16 @@
cfa_ += 4;
}
}
+
// If the sp register is modified, change the cfa value.
if (registers & (1 << ARM_REG_SP)) {
cfa_ = (*regs_)[ARM_REG_SP];
}
+
+ // Indicate if the pc register was set.
+ if (registers & (1 << ARM_REG_PC)) {
+ pc_set_ = true;
+ }
return true;
}
@@ -296,9 +304,6 @@
return false;
}
}
- if (!(*regs_)[ARM_REG_PC]) {
- (*regs_)[ARM_REG_PC] = (*regs_)[ARM_REG_LR];
- }
status_ = ARM_STATUS_FINISH;
return false;
}
@@ -675,6 +680,7 @@
}
bool ArmExidx::Eval() {
+ pc_set_ = false;
while (Decode());
return status_ == ARM_STATUS_FINISH;
}
diff --git a/libunwindstack/ArmExidx.h b/libunwindstack/ArmExidx.h
index a92caef..8c7f15a 100644
--- a/libunwindstack/ArmExidx.h
+++ b/libunwindstack/ArmExidx.h
@@ -21,8 +21,9 @@
#include <deque>
-#include "Memory.h"
-#include "Regs.h"
+// Forward declarations.
+class Memory;
+class RegsArm;
enum ArmStatus : size_t {
ARM_STATUS_NONE = 0,
@@ -43,7 +44,7 @@
class ArmExidx {
public:
- ArmExidx(Regs32* regs, Memory* elf_memory, Memory* process_memory)
+ ArmExidx(RegsArm* regs, Memory* elf_memory, Memory* process_memory)
: regs_(regs), elf_memory_(elf_memory), process_memory_(process_memory) {}
virtual ~ArmExidx() {}
@@ -59,11 +60,14 @@
ArmStatus status() { return status_; }
- Regs32* regs() { return regs_; }
+ RegsArm* regs() { return regs_; }
uint32_t cfa() { return cfa_; }
void set_cfa(uint32_t cfa) { cfa_ = cfa; }
+ bool pc_set() { return pc_set_; }
+ void set_pc_set(bool pc_set) { pc_set_ = pc_set; }
+
void set_log(bool log) { log_ = log; }
void set_log_skip_execution(bool skip_execution) { log_skip_execution_ = skip_execution; }
void set_log_indent(uint8_t indent) { log_indent_ = indent; }
@@ -87,7 +91,7 @@
bool DecodePrefix_11_010(uint8_t byte);
bool DecodePrefix_11(uint8_t byte);
- Regs32* regs_ = nullptr;
+ RegsArm* regs_ = nullptr;
uint32_t cfa_ = 0;
std::deque<uint8_t> data_;
ArmStatus status_ = ARM_STATUS_NONE;
@@ -98,6 +102,7 @@
bool log_ = false;
uint8_t log_indent_ = 0;
bool log_skip_execution_ = false;
+ bool pc_set_ = false;
};
#endif // _LIBUNWINDSTACK_ARM_EXIDX_H
diff --git a/libunwindstack/Elf.cpp b/libunwindstack/Elf.cpp
new file mode 100644
index 0000000..272b5f0
--- /dev/null
+++ b/libunwindstack/Elf.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2016 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 <string.h>
+
+#include <memory>
+#include <string>
+
+#define LOG_TAG "unwind"
+#include <log/log.h>
+
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+#include "Machine.h"
+#include "Memory.h"
+#include "Regs.h"
+
+bool Elf::Init() {
+ if (!memory_) {
+ return false;
+ }
+
+ interface_.reset(CreateInterfaceFromMemory(memory_.get()));
+ if (!interface_) {
+ return false;
+ }
+
+ valid_ = interface_->Init();
+ if (valid_) {
+ interface_->InitHeaders();
+ } else {
+ interface_.reset(nullptr);
+ }
+ return valid_;
+}
+
+bool Elf::IsValidElf(Memory* memory) {
+ if (memory == nullptr) {
+ return false;
+ }
+
+ // Verify that this is a valid elf file.
+ uint8_t e_ident[SELFMAG + 1];
+ if (!memory->Read(0, e_ident, SELFMAG)) {
+ return false;
+ }
+
+ if (memcmp(e_ident, ELFMAG, SELFMAG) != 0) {
+ return false;
+ }
+ return true;
+}
+
+ElfInterface* Elf::CreateInterfaceFromMemory(Memory* memory) {
+ if (!IsValidElf(memory)) {
+ return nullptr;
+ }
+
+ std::unique_ptr<ElfInterface> interface;
+ if (!memory->Read(EI_CLASS, &class_type_, 1)) {
+ return nullptr;
+ }
+ if (class_type_ == ELFCLASS32) {
+ Elf32_Half e_machine;
+ if (!memory->Read(EI_NIDENT + sizeof(Elf32_Half), &e_machine, sizeof(e_machine))) {
+ return nullptr;
+ }
+
+ if (e_machine != EM_ARM && e_machine != EM_386) {
+ // Unsupported.
+ ALOGI("32 bit elf that is neither arm nor x86: e_machine = %d\n", e_machine);
+ return nullptr;
+ }
+
+ machine_type_ = e_machine;
+ if (e_machine == EM_ARM) {
+ interface.reset(new ElfInterfaceArm(memory));
+ } else {
+ interface.reset(new ElfInterface32(memory));
+ }
+ } else if (class_type_ == ELFCLASS64) {
+ Elf64_Half e_machine;
+ if (!memory->Read(EI_NIDENT + sizeof(Elf64_Half), &e_machine, sizeof(e_machine))) {
+ return nullptr;
+ }
+
+ if (e_machine != EM_AARCH64 && e_machine != EM_X86_64) {
+ // Unsupported.
+ ALOGI("64 bit elf that is neither aarch64 nor x86_64: e_machine = %d\n", e_machine);
+ return nullptr;
+ }
+
+ machine_type_ = e_machine;
+ interface.reset(new ElfInterface64(memory));
+ }
+
+ return interface.release();
+}
diff --git a/libunwindstack/Elf.h b/libunwindstack/Elf.h
new file mode 100644
index 0000000..7bf45b8
--- /dev/null
+++ b/libunwindstack/Elf.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2016 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_ELF_H
+#define _LIBUNWINDSTACK_ELF_H
+
+#include <stddef.h>
+
+#include <memory>
+#include <string>
+
+#include "ElfInterface.h"
+#include "Memory.h"
+
+#if !defined(EM_AARCH64)
+#define EM_AARCH64 183
+#endif
+
+// Forward declaration.
+class Regs;
+
+class Elf {
+ public:
+ Elf(Memory* memory) : memory_(memory) {}
+ virtual ~Elf() = default;
+
+ bool Init();
+
+ void InitGnuDebugdata();
+
+ bool GetSoname(std::string* name) {
+ return valid_ && interface_->GetSoname(name);
+ }
+
+ bool GetFunctionName(uint64_t, std::string*, uint64_t*) {
+ return false;
+ }
+
+ bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory) {
+ return valid_ && interface_->Step(rel_pc, regs, process_memory);
+ }
+
+ ElfInterface* CreateInterfaceFromMemory(Memory* memory);
+
+ bool valid() { return valid_; }
+
+ uint32_t machine_type() { return machine_type_; }
+
+ uint8_t class_type() { return class_type_; }
+
+ Memory* memory() { return memory_.get(); }
+
+ ElfInterface* interface() { return interface_.get(); }
+
+ static bool IsValidElf(Memory* memory);
+
+ protected:
+ bool valid_ = false;
+ std::unique_ptr<ElfInterface> interface_;
+ std::unique_ptr<Memory> memory_;
+ uint32_t machine_type_;
+ uint8_t class_type_;
+};
+
+#endif // _LIBUNWINDSTACK_ELF_H
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
new file mode 100644
index 0000000..d59e9d8
--- /dev/null
+++ b/libunwindstack/ElfInterface.cpp
@@ -0,0 +1,223 @@
+/*
+ * 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 <stdint.h>
+
+#include <memory>
+#include <string>
+
+#include "ElfInterface.h"
+#include "Memory.h"
+#include "Regs.h"
+
+template <typename EhdrType, typename PhdrType, typename ShdrType>
+bool ElfInterface::ReadAllHeaders() {
+ EhdrType ehdr;
+ if (!memory_->Read(0, &ehdr, sizeof(ehdr))) {
+ return false;
+ }
+
+ if (!ReadProgramHeaders<EhdrType, PhdrType>(ehdr)) {
+ return false;
+ }
+ return ReadSectionHeaders<EhdrType, ShdrType>(ehdr);
+}
+
+template <typename EhdrType, typename PhdrType>
+bool ElfInterface::ReadProgramHeaders(const EhdrType& ehdr) {
+ uint64_t offset = ehdr.e_phoff;
+ for (size_t i = 0; i < ehdr.e_phnum; i++, offset += ehdr.e_phentsize) {
+ PhdrType phdr;
+ if (!memory_->Read(offset, &phdr, &phdr.p_type, sizeof(phdr.p_type))) {
+ return false;
+ }
+
+ if (HandleType(offset, phdr.p_type)) {
+ continue;
+ }
+
+ switch (phdr.p_type) {
+ case PT_LOAD:
+ {
+ // Get the flags first, if this isn't an executable header, ignore it.
+ if (!memory_->Read(offset, &phdr, &phdr.p_flags, sizeof(phdr.p_flags))) {
+ return false;
+ }
+ if ((phdr.p_flags & PF_X) == 0) {
+ continue;
+ }
+
+ if (!memory_->Read(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+ return false;
+ }
+ if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+ return false;
+ }
+ if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+ return false;
+ }
+ pt_loads_[phdr.p_offset] = LoadInfo{phdr.p_offset, phdr.p_vaddr,
+ static_cast<size_t>(phdr.p_memsz)};
+ if (phdr.p_offset == 0) {
+ load_bias_ = phdr.p_vaddr;
+ }
+ break;
+ }
+
+ case PT_GNU_EH_FRAME:
+ if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+ return false;
+ }
+ eh_frame_offset_ = phdr.p_offset;
+ if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+ return false;
+ }
+ eh_frame_size_ = phdr.p_memsz;
+ break;
+
+ case PT_DYNAMIC:
+ if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+ return false;
+ }
+ dynamic_offset_ = phdr.p_offset;
+ if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+ return false;
+ }
+ dynamic_size_ = phdr.p_memsz;
+ break;
+ }
+ }
+ return true;
+}
+
+template <typename EhdrType, typename ShdrType>
+bool ElfInterface::ReadSectionHeaders(const EhdrType& ehdr) {
+ uint64_t offset = ehdr.e_shoff;
+ uint64_t sec_offset = 0;
+ uint64_t sec_size = 0;
+
+ // Get the location of the section header names.
+ // If something is malformed in the header table data, we aren't going
+ // to terminate, we'll simply ignore this part.
+ ShdrType shdr;
+ if (ehdr.e_shstrndx < ehdr.e_shnum) {
+ uint64_t sh_offset = offset + ehdr.e_shstrndx * ehdr.e_shentsize;
+ if (memory_->Read(sh_offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset))
+ && memory_->Read(sh_offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
+ sec_offset = shdr.sh_offset;
+ sec_size = shdr.sh_size;
+ }
+ }
+
+ // Skip the first header, it's always going to be NULL.
+ for (size_t i = 1; i < ehdr.e_shnum; i++, offset += ehdr.e_shentsize) {
+ if (!memory_->Read(offset, &shdr, &shdr.sh_type, sizeof(shdr.sh_type))) {
+ return false;
+ }
+
+ if (shdr.sh_type == SHT_PROGBITS) {
+ // Look for the .debug_frame and .gnu_debugdata.
+ if (!memory_->Read(offset, &shdr, &shdr.sh_name, sizeof(shdr.sh_name))) {
+ return false;
+ }
+ if (shdr.sh_name < sec_size) {
+ std::string name;
+ if (memory_->ReadString(sec_offset + shdr.sh_name, &name)) {
+ if (name == ".debug_frame") {
+ if (memory_->Read(offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset))
+ && memory_->Read(offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
+ debug_frame_offset_ = shdr.sh_offset;
+ debug_frame_size_ = shdr.sh_size;
+ }
+ } else if (name == ".gnu_debugdata") {
+ if (memory_->Read(offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset))
+ && memory_->Read(offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
+ gnu_debugdata_offset_ = shdr.sh_offset;
+ gnu_debugdata_size_ = shdr.sh_size;
+ }
+ }
+ }
+ }
+ }
+ }
+ return true;
+}
+
+template <typename DynType>
+bool ElfInterface::GetSonameWithTemplate(std::string* soname) {
+ if (soname_type_ == SONAME_INVALID) {
+ return false;
+ }
+ if (soname_type_ == SONAME_VALID) {
+ *soname = soname_;
+ return true;
+ }
+
+ soname_type_ = SONAME_INVALID;
+
+ uint64_t soname_offset = 0;
+ uint64_t strtab_offset = 0;
+ uint64_t strtab_size = 0;
+
+ // Find the soname location from the dynamic headers section.
+ DynType dyn;
+ uint64_t offset = dynamic_offset_;
+ uint64_t max_offset = offset + dynamic_size_;
+ for (uint64_t offset = dynamic_offset_; offset < max_offset; offset += sizeof(DynType)) {
+ if (!memory_->Read(offset, &dyn, sizeof(dyn))) {
+ return false;
+ }
+
+ if (dyn.d_tag == DT_STRTAB) {
+ strtab_offset = dyn.d_un.d_ptr;
+ } else if (dyn.d_tag == DT_STRSZ) {
+ strtab_size = dyn.d_un.d_val;
+ } else if (dyn.d_tag == DT_SONAME) {
+ soname_offset = dyn.d_un.d_val;
+ } else if (dyn.d_tag == DT_NULL) {
+ break;
+ }
+ }
+
+ soname_offset += strtab_offset;
+ if (soname_offset >= strtab_offset + strtab_size) {
+ return false;
+ }
+ if (!memory_->ReadString(soname_offset, &soname_)) {
+ return false;
+ }
+ soname_type_ = SONAME_VALID;
+ *soname = soname_;
+ return true;
+}
+
+bool ElfInterface::Step(uint64_t, Regs*, Memory*) {
+ return false;
+}
+
+// Instantiate all of the needed template functions.
+template bool ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>();
+template bool ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>();
+
+template bool ElfInterface::ReadProgramHeaders<Elf32_Ehdr, Elf32_Phdr>(const Elf32_Ehdr&);
+template bool ElfInterface::ReadProgramHeaders<Elf64_Ehdr, Elf64_Phdr>(const Elf64_Ehdr&);
+
+template bool ElfInterface::ReadSectionHeaders<Elf32_Ehdr, Elf32_Shdr>(const Elf32_Ehdr&);
+template bool ElfInterface::ReadSectionHeaders<Elf64_Ehdr, Elf64_Shdr>(const Elf64_Ehdr&);
+
+template bool ElfInterface::GetSonameWithTemplate<Elf32_Dyn>(std::string*);
+template bool ElfInterface::GetSonameWithTemplate<Elf64_Dyn>(std::string*);
diff --git a/libunwindstack/ElfInterface.h b/libunwindstack/ElfInterface.h
new file mode 100644
index 0000000..944146c
--- /dev/null
+++ b/libunwindstack/ElfInterface.h
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2016 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_ELF_INTERFACE_H
+#define _LIBUNWINDSTACK_ELF_INTERFACE_H
+
+#include <elf.h>
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+// Forward declarations.
+class Memory;
+class Regs;
+
+struct LoadInfo {
+ uint64_t offset;
+ uint64_t table_offset;
+ size_t table_size;
+};
+
+enum : uint8_t {
+ SONAME_UNKNOWN = 0,
+ SONAME_VALID,
+ SONAME_INVALID,
+};
+
+class ElfInterface {
+ public:
+ ElfInterface(Memory* memory) : memory_(memory) {}
+ virtual ~ElfInterface() = default;
+
+ virtual bool Init() = 0;
+
+ virtual void InitHeaders() = 0;
+
+ virtual bool GetSoname(std::string* name) = 0;
+
+ 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);
+
+ Memory* CreateGnuDebugdataMemory();
+
+ Memory* memory() { return memory_; }
+
+ const std::unordered_map<uint64_t, LoadInfo>& pt_loads() { return pt_loads_; }
+ uint64_t load_bias() { return load_bias_; }
+ void set_load_bias(uint64_t load_bias) { load_bias_ = load_bias; }
+
+ uint64_t dynamic_offset() { return dynamic_offset_; }
+ uint64_t dynamic_size() { return dynamic_size_; }
+ uint64_t eh_frame_offset() { return eh_frame_offset_; }
+ uint64_t eh_frame_size() { return eh_frame_size_; }
+ uint64_t gnu_debugdata_offset() { return gnu_debugdata_offset_; }
+ uint64_t gnu_debugdata_size() { return gnu_debugdata_size_; }
+
+ protected:
+ template <typename EhdrType, typename PhdrType, typename ShdrType>
+ bool ReadAllHeaders();
+
+ template <typename EhdrType, typename PhdrType>
+ bool ReadProgramHeaders(const EhdrType& ehdr);
+
+ template <typename EhdrType, typename ShdrType>
+ bool ReadSectionHeaders(const EhdrType& ehdr);
+
+ template <typename DynType>
+ bool GetSonameWithTemplate(std::string* soname);
+
+ virtual bool HandleType(uint64_t, uint32_t) { return false; }
+
+ Memory* memory_;
+ std::unordered_map<uint64_t, LoadInfo> pt_loads_;
+ uint64_t load_bias_ = 0;
+
+ // Stored elf data.
+ uint64_t dynamic_offset_ = 0;
+ uint64_t dynamic_size_ = 0;
+
+ uint64_t eh_frame_offset_ = 0;
+ uint64_t eh_frame_size_ = 0;
+
+ uint64_t debug_frame_offset_ = 0;
+ uint64_t debug_frame_size_ = 0;
+
+ uint64_t gnu_debugdata_offset_ = 0;
+ uint64_t gnu_debugdata_size_ = 0;
+
+ uint8_t soname_type_ = SONAME_UNKNOWN;
+ std::string soname_;
+};
+
+class ElfInterface32 : public ElfInterface {
+ public:
+ ElfInterface32(Memory* memory) : ElfInterface(memory) {}
+ virtual ~ElfInterface32() = default;
+
+ bool Init() override {
+ return ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>();
+ }
+
+ void InitHeaders() override {
+ }
+
+ bool GetSoname(std::string* soname) override {
+ return ElfInterface::GetSonameWithTemplate<Elf32_Dyn>(soname);
+ }
+
+ bool GetFunctionName(uint64_t, std::string*, uint64_t*) override {
+ return false;
+ }
+};
+
+class ElfInterface64 : public ElfInterface {
+ public:
+ ElfInterface64(Memory* memory) : ElfInterface(memory) {}
+ virtual ~ElfInterface64() = default;
+
+ bool Init() override {
+ return ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>();
+ }
+
+ void InitHeaders() override {
+ }
+
+ bool GetSoname(std::string* soname) override {
+ return ElfInterface::GetSonameWithTemplate<Elf64_Dyn>(soname);
+ }
+
+ bool GetFunctionName(uint64_t, std::string*, uint64_t*) override {
+ return false;
+ }
+};
+
+#endif // _LIBUNWINDSTACK_ELF_INTERFACE_H
diff --git a/libunwindstack/ElfInterfaceArm.cpp b/libunwindstack/ElfInterfaceArm.cpp
new file mode 100644
index 0000000..e157320
--- /dev/null
+++ b/libunwindstack/ElfInterfaceArm.cpp
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2016 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 <stdint.h>
+
+#include "ArmExidx.h"
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+#include "Machine.h"
+#include "Memory.h"
+#include "Regs.h"
+
+bool ElfInterfaceArm::FindEntry(uint32_t pc, uint64_t* entry_offset) {
+ if (start_offset_ == 0 || total_entries_ == 0) {
+ return false;
+ }
+
+ // Need to subtract the load_bias from the pc.
+ if (pc < load_bias_) {
+ return false;
+ }
+ pc -= load_bias_;
+
+ size_t first = 0;
+ size_t last = total_entries_;
+ while (first < last) {
+ size_t current = (first + last) / 2;
+ uint32_t addr = addrs_[current];
+ if (addr == 0) {
+ if (!GetPrel31Addr(start_offset_ + current * 8, &addr)) {
+ return false;
+ }
+ addrs_[current] = addr;
+ }
+ if (pc == addr) {
+ *entry_offset = start_offset_ + current * 8;
+ return true;
+ }
+ if (pc < addr) {
+ last = current;
+ } else {
+ first = current + 1;
+ }
+ }
+ if (last != 0) {
+ *entry_offset = start_offset_ + (last - 1) * 8;
+ return true;
+ }
+ return false;
+}
+
+bool ElfInterfaceArm::GetPrel31Addr(uint32_t offset, uint32_t* addr) {
+ uint32_t data;
+ if (!memory_->Read32(offset, &data)) {
+ return false;
+ }
+
+ // Sign extend the value if necessary.
+ int32_t value = (static_cast<int32_t>(data) << 1) >> 1;
+ *addr = offset + value;
+ return true;
+}
+
+#if !defined(PT_ARM_EXIDX)
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+bool ElfInterfaceArm::HandleType(uint64_t offset, uint32_t type) {
+ if (type != PT_ARM_EXIDX) {
+ return false;
+ }
+
+ Elf32_Phdr phdr;
+ if (!memory_->Read(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+ return true;
+ }
+ if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+ return true;
+ }
+ // The load_bias_ should always be set by this time.
+ start_offset_ = phdr.p_vaddr - load_bias_;
+ total_entries_ = phdr.p_memsz / 8;
+ return true;
+}
+
+bool ElfInterfaceArm::Step(uint64_t pc, Regs* regs, Memory* process_memory) {
+ return StepExidx(pc, regs, process_memory) ||
+ ElfInterface32::Step(pc, regs, process_memory);
+}
+
+bool ElfInterfaceArm::StepExidx(uint64_t pc, Regs* regs, Memory* process_memory) {
+ RegsArm* regs_arm = reinterpret_cast<RegsArm*>(regs);
+ // First try arm, then try dwarf.
+ uint64_t entry_offset;
+ if (!FindEntry(pc, &entry_offset)) {
+ return false;
+ }
+ ArmExidx arm(regs_arm, memory_, process_memory);
+ arm.set_cfa(regs_arm->sp());
+ 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()) {
+ regs_arm->set_pc((*regs_arm)[ARM_REG_LR]);
+ (*regs_arm)[ARM_REG_PC] = regs_arm->pc();
+ } else {
+ regs_arm->set_pc((*regs_arm)[ARM_REG_PC]);
+ }
+ regs_arm->set_sp(arm.cfa());
+ (*regs_arm)[ARM_REG_SP] = regs_arm->sp();
+ return true;
+ }
+ return false;
+}
diff --git a/libunwindstack/ElfInterfaceArm.h b/libunwindstack/ElfInterfaceArm.h
new file mode 100644
index 0000000..ece694f
--- /dev/null
+++ b/libunwindstack/ElfInterfaceArm.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2016 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_ELF_INTERFACE_ARM_H
+#define _LIBUNWINDSTACK_ELF_INTERFACE_ARM_H
+
+#include <elf.h>
+#include <stdint.h>
+
+#include <iterator>
+#include <unordered_map>
+
+#include "ElfInterface.h"
+#include "Memory.h"
+
+class ElfInterfaceArm : public ElfInterface32 {
+ public:
+ ElfInterfaceArm(Memory* memory) : ElfInterface32(memory) {}
+ virtual ~ElfInterfaceArm() = default;
+
+ class iterator : public std::iterator<std::bidirectional_iterator_tag, uint32_t> {
+ public:
+ iterator(ElfInterfaceArm* interface, size_t index) : interface_(interface), index_(index) { }
+
+ iterator& operator++() { index_++; return *this; }
+ iterator& operator++(int increment) { index_ += increment; return *this; }
+ iterator& operator--() { index_--; return *this; }
+ iterator& operator--(int decrement) { index_ -= decrement; return *this; }
+
+ bool operator==(const iterator& rhs) { return this->index_ == rhs.index_; }
+ bool operator!=(const iterator& rhs) { return this->index_ != rhs.index_; }
+
+ uint32_t operator*() {
+ uint32_t addr = interface_->addrs_[index_];
+ if (addr == 0) {
+ if (!interface_->GetPrel31Addr(interface_->start_offset_ + index_ * 8, &addr)) {
+ return 0;
+ }
+ interface_->addrs_[index_] = addr;
+ }
+ return addr;
+ }
+
+ private:
+ ElfInterfaceArm* interface_ = nullptr;
+ size_t index_ = 0;
+ };
+
+ iterator begin() { return iterator(this, 0); }
+ iterator end() { return iterator(this, total_entries_); }
+
+ bool GetPrel31Addr(uint32_t offset, uint32_t* addr);
+
+ bool FindEntry(uint32_t pc, uint64_t* entry_offset);
+
+ bool HandleType(uint64_t offset, uint32_t type) override;
+
+ bool Step(uint64_t pc, Regs* regs, Memory* process_memory) override;
+
+ bool StepExidx(uint64_t pc, Regs* regs, Memory* process_memory);
+
+ uint64_t start_offset() { return start_offset_; }
+
+ void set_start_offset(uint64_t start_offset) { start_offset_ = start_offset; }
+
+ size_t total_entries() { return total_entries_; }
+
+ void set_total_entries(size_t total_entries) { total_entries_ = total_entries; }
+
+ private:
+ uint64_t start_offset_ = 0;
+ size_t total_entries_ = 0;
+
+ std::unordered_map<size_t, uint32_t> addrs_;
+};
+
+#endif // _LIBUNWINDSTACK_ELF_INTERFACE_ARM_H
diff --git a/libunwindstack/Machine.h b/libunwindstack/Machine.h
index db84271..323ce80 100644
--- a/libunwindstack/Machine.h
+++ b/libunwindstack/Machine.h
@@ -19,8 +19,6 @@
#include <stdint.h>
-class Regs;
-
enum ArmReg : uint16_t {
ARM_REG_R0 = 0,
ARM_REG_R1,
diff --git a/libunwindstack/MapInfo.h b/libunwindstack/MapInfo.h
new file mode 100644
index 0000000..8342904
--- /dev/null
+++ b/libunwindstack/MapInfo.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2016 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_MAP_INFO_H
+#define _LIBUNWINDSTACK_MAP_INFO_H
+
+#include <stdint.h>
+
+#include <string>
+
+// Forward declarations.
+class Elf;
+class Memory;
+
+struct MapInfo {
+ uint64_t start;
+ uint64_t end;
+ uint64_t offset;
+ uint16_t flags;
+ std::string name;
+ Elf* elf = nullptr;
+ // This value is only non-zero if the offset is non-zero but there is
+ // no elf signature found at that offset. This indicates that the
+ // entire file is represented by the Memory object returned by CreateMemory,
+ // instead of a portion of the file.
+ uint64_t elf_offset;
+
+ Memory* CreateMemory(pid_t pid);
+};
+
+#endif // _LIBUNWINDSTACK_MAP_INFO_H
diff --git a/libunwindstack/Memory.cpp b/libunwindstack/Memory.cpp
index 336e4fe..1fcf842 100644
--- a/libunwindstack/Memory.cpp
+++ b/libunwindstack/Memory.cpp
@@ -48,14 +48,40 @@
return false;
}
+bool MemoryBuffer::Read(uint64_t addr, void* dst, size_t size) {
+ uint64_t last_read_byte;
+ if (__builtin_add_overflow(size, addr, &last_read_byte)) {
+ return false;
+ }
+ if (last_read_byte > raw_.size()) {
+ return false;
+ }
+ memcpy(dst, &raw_[addr], size);
+ return true;
+}
+
+uint8_t* MemoryBuffer::GetPtr(size_t offset) {
+ if (offset < raw_.size()) {
+ return &raw_[offset];
+ }
+ return nullptr;
+}
+
MemoryFileAtOffset::~MemoryFileAtOffset() {
+ Clear();
+}
+
+void MemoryFileAtOffset::Clear() {
if (data_) {
munmap(&data_[-offset_], size_ + offset_);
data_ = nullptr;
}
}
-bool MemoryFileAtOffset::Init(const std::string& file, uint64_t offset) {
+bool MemoryFileAtOffset::Init(const std::string& file, uint64_t offset, uint64_t size) {
+ // Clear out any previous data if it exists.
+ Clear();
+
android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC)));
if (fd == -1) {
return false;
@@ -71,6 +97,10 @@
offset_ = offset & (getpagesize() - 1);
uint64_t aligned_offset = offset & ~(getpagesize() - 1);
size_ = buf.st_size - aligned_offset;
+ if (size < (UINT64_MAX - offset_) && size + offset_ < size_) {
+ // Truncate the mapped size.
+ size_ = size + offset_;
+ }
void* map = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, aligned_offset);
if (map == MAP_FAILED) {
return false;
@@ -91,6 +121,12 @@
}
static bool PtraceRead(pid_t pid, uint64_t addr, long* value) {
+#if !defined(__LP64__)
+ // Cannot read an address greater than 32 bits.
+ if (addr > UINT32_MAX) {
+ return false;
+ }
+#endif
// ptrace() returns -1 and sets errno when the operation fails.
// To disambiguate -1 from a valid result, we clear errno beforehand.
errno = 0;
diff --git a/libunwindstack/Memory.h b/libunwindstack/Memory.h
index 5ab031d..c5316a1 100644
--- a/libunwindstack/Memory.h
+++ b/libunwindstack/Memory.h
@@ -22,10 +22,7 @@
#include <unistd.h>
#include <string>
-
-#include <android-base/unique_fd.h>
-
-constexpr bool kMemoryStatsEnabled = true;
+#include <vector>
class Memory {
public:
@@ -50,15 +47,34 @@
}
};
+class MemoryBuffer : public Memory {
+ public:
+ MemoryBuffer() = default;
+ virtual ~MemoryBuffer() = default;
+
+ bool Read(uint64_t addr, void* dst, size_t size) override;
+
+ uint8_t* GetPtr(size_t offset);
+
+ void Resize(size_t size) { raw_.resize(size); }
+
+ uint64_t Size() { return raw_.size(); }
+
+ private:
+ std::vector<uint8_t> raw_;
+};
+
class MemoryFileAtOffset : public Memory {
public:
MemoryFileAtOffset() = default;
virtual ~MemoryFileAtOffset();
- bool Init(const std::string& file, uint64_t offset);
+ bool Init(const std::string& file, uint64_t offset, uint64_t size = UINT64_MAX);
bool Read(uint64_t addr, void* dst, size_t size) override;
+ void Clear();
+
protected:
size_t size_ = 0;
size_t offset_ = 0;
diff --git a/libunwindstack/Regs.cpp b/libunwindstack/Regs.cpp
new file mode 100644
index 0000000..adb6522
--- /dev/null
+++ b/libunwindstack/Regs.cpp
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2016 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 <assert.h>
+#include <elf.h>
+#include <stdint.h>
+#include <sys/ptrace.h>
+#include <sys/uio.h>
+
+#include <vector>
+
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "Machine.h"
+#include "MapInfo.h"
+#include "Regs.h"
+#include "User.h"
+
+template <typename AddressType>
+uint64_t RegsTmpl<AddressType>::GetRelPc(Elf* elf, const MapInfo* map_info) {
+ uint64_t load_bias = 0;
+ if (elf->valid()) {
+ load_bias = elf->interface()->load_bias();
+ }
+
+ return pc_ - map_info->start + load_bias + map_info->elf_offset;
+}
+
+template <typename AddressType>
+bool RegsTmpl<AddressType>::GetReturnAddressFromDefault(Memory* memory, uint64_t* value) {
+ switch (return_loc_.type) {
+ case LOCATION_REGISTER:
+ assert(return_loc_.value < total_regs_);
+ *value = regs_[return_loc_.value];
+ return true;
+ case LOCATION_SP_OFFSET:
+ AddressType return_value;
+ if (!memory->Read(sp_ + return_loc_.value, &return_value, sizeof(return_value))) {
+ return false;
+ }
+ *value = return_value;
+ return true;
+ case LOCATION_UNKNOWN:
+ default:
+ return false;
+ }
+}
+
+RegsArm::RegsArm() : RegsTmpl<uint32_t>(ARM_REG_LAST, ARM_REG_SP,
+ Location(LOCATION_REGISTER, ARM_REG_LR)) {
+}
+
+uint64_t RegsArm::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+ if (!elf->valid()) {
+ return rel_pc;
+ }
+
+ uint64_t load_bias = elf->interface()->load_bias();
+ if (rel_pc < load_bias) {
+ return rel_pc;
+ }
+ uint64_t adjusted_rel_pc = rel_pc - load_bias;
+
+ if (adjusted_rel_pc < 5) {
+ return rel_pc;
+ }
+
+ if (adjusted_rel_pc & 1) {
+ // This is a thumb instruction, it could be 2 or 4 bytes.
+ uint32_t value;
+ if (rel_pc < 5 || !elf->memory()->Read(adjusted_rel_pc - 5, &value, sizeof(value)) ||
+ (value & 0xe000f000) != 0xe000f000) {
+ return rel_pc - 2;
+ }
+ }
+ return rel_pc - 4;
+}
+
+RegsArm64::RegsArm64() : RegsTmpl<uint64_t>(ARM64_REG_LAST, ARM64_REG_SP,
+ Location(LOCATION_REGISTER, ARM64_REG_LR)) {
+}
+
+uint64_t RegsArm64::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+ if (!elf->valid()) {
+ return rel_pc;
+ }
+
+ if (rel_pc < 4) {
+ return rel_pc;
+ }
+ return rel_pc - 4;
+}
+
+RegsX86::RegsX86() : RegsTmpl<uint32_t>(X86_REG_LAST, X86_REG_SP,
+ Location(LOCATION_SP_OFFSET, -4)) {
+}
+
+uint64_t RegsX86::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+ if (!elf->valid()) {
+ return rel_pc;
+ }
+
+ if (rel_pc == 0) {
+ return 0;
+ }
+ return rel_pc - 1;
+}
+
+RegsX86_64::RegsX86_64() : RegsTmpl<uint64_t>(X86_64_REG_LAST, X86_64_REG_SP,
+ Location(LOCATION_SP_OFFSET, -8)) {
+}
+
+uint64_t RegsX86_64::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
+ if (!elf->valid()) {
+ return rel_pc;
+ }
+
+ if (rel_pc == 0) {
+ return 0;
+ }
+
+ return rel_pc - 1;
+}
+
+static Regs* ReadArm(void* remote_data) {
+ arm_user_regs* user = reinterpret_cast<arm_user_regs*>(remote_data);
+
+ RegsArm* regs = new RegsArm();
+ memcpy(regs->RawData(), &user->regs[0], ARM_REG_LAST * sizeof(uint32_t));
+
+ regs->set_pc(user->regs[ARM_REG_PC]);
+ regs->set_sp(user->regs[ARM_REG_SP]);
+
+ return regs;
+}
+
+static Regs* ReadArm64(void* remote_data) {
+ arm64_user_regs* user = reinterpret_cast<arm64_user_regs*>(remote_data);
+
+ RegsArm64* regs = new RegsArm64();
+ memcpy(regs->RawData(), &user->regs[0], (ARM64_REG_R31 + 1) * sizeof(uint64_t));
+ regs->set_pc(user->pc);
+ regs->set_sp(user->sp);
+
+ return regs;
+}
+
+static Regs* ReadX86(void* remote_data) {
+ x86_user_regs* user = reinterpret_cast<x86_user_regs*>(remote_data);
+
+ RegsX86* regs = new RegsX86();
+ (*regs)[X86_REG_EAX] = user->eax;
+ (*regs)[X86_REG_EBX] = user->ebx;
+ (*regs)[X86_REG_ECX] = user->ecx;
+ (*regs)[X86_REG_EDX] = user->edx;
+ (*regs)[X86_REG_EBP] = user->ebp;
+ (*regs)[X86_REG_EDI] = user->edi;
+ (*regs)[X86_REG_ESI] = user->esi;
+ (*regs)[X86_REG_ESP] = user->esp;
+ (*regs)[X86_REG_EIP] = user->eip;
+
+ regs->set_pc(user->eip);
+ regs->set_sp(user->esp);
+
+ return regs;
+}
+
+static Regs* ReadX86_64(void* remote_data) {
+ x86_64_user_regs* user = reinterpret_cast<x86_64_user_regs*>(remote_data);
+
+ RegsX86_64* regs = new RegsX86_64();
+ (*regs)[X86_64_REG_RAX] = user->rax;
+ (*regs)[X86_64_REG_RBX] = user->rbx;
+ (*regs)[X86_64_REG_RCX] = user->rcx;
+ (*regs)[X86_64_REG_RDX] = user->rdx;
+ (*regs)[X86_64_REG_R8] = user->r8;
+ (*regs)[X86_64_REG_R9] = user->r9;
+ (*regs)[X86_64_REG_R10] = user->r10;
+ (*regs)[X86_64_REG_R11] = user->r11;
+ (*regs)[X86_64_REG_R12] = user->r12;
+ (*regs)[X86_64_REG_R13] = user->r13;
+ (*regs)[X86_64_REG_R14] = user->r14;
+ (*regs)[X86_64_REG_R15] = user->r15;
+ (*regs)[X86_64_REG_RDI] = user->rdi;
+ (*regs)[X86_64_REG_RSI] = user->rsi;
+ (*regs)[X86_64_REG_RBP] = user->rbp;
+ (*regs)[X86_64_REG_RSP] = user->rsp;
+ (*regs)[X86_64_REG_RIP] = user->rip;
+
+ regs->set_pc(user->rip);
+ regs->set_sp(user->rsp);
+
+ return regs;
+}
+
+// This function assumes that reg_data is already aligned to a 64 bit value.
+// If not this could crash with an unaligned access.
+Regs* Regs::RemoteGet(pid_t pid, uint32_t* machine_type) {
+ // Make the buffer large enough to contain the largest registers type.
+ std::vector<uint64_t> buffer(MAX_USER_REGS_SIZE / sizeof(uint64_t));
+ struct iovec io;
+ io.iov_base = buffer.data();
+ io.iov_len = buffer.size() * sizeof(uint64_t);
+
+ if (ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, reinterpret_cast<void*>(&io)) == -1) {
+ return nullptr;
+ }
+
+ switch (io.iov_len) {
+ case sizeof(x86_user_regs):
+ *machine_type = EM_386;
+ return ReadX86(buffer.data());
+ case sizeof(x86_64_user_regs):
+ *machine_type = EM_X86_64;
+ return ReadX86_64(buffer.data());
+ case sizeof(arm_user_regs):
+ *machine_type = EM_ARM;
+ return ReadArm(buffer.data());
+ case sizeof(arm64_user_regs):
+ *machine_type = EM_AARCH64;
+ return ReadArm64(buffer.data());
+ }
+ return nullptr;
+}
diff --git a/libunwindstack/Regs.h b/libunwindstack/Regs.h
index 2766c6f..718fc85 100644
--- a/libunwindstack/Regs.h
+++ b/libunwindstack/Regs.h
@@ -21,57 +21,107 @@
#include <vector>
+// Forward declarations.
+class Elf;
+struct MapInfo;
+
class Regs {
public:
- Regs(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
- : pc_reg_(pc_reg), sp_reg_(sp_reg), total_regs_(total_regs) {
- }
+ enum LocationEnum : uint8_t {
+ LOCATION_UNKNOWN = 0,
+ LOCATION_REGISTER,
+ LOCATION_SP_OFFSET,
+ };
+
+ struct Location {
+ Location(LocationEnum type, int16_t value) : type(type), value(value) {}
+
+ LocationEnum type;
+ int16_t value;
+ };
+
+ Regs(uint16_t total_regs, uint16_t sp_reg, const Location& return_loc)
+ : total_regs_(total_regs), sp_reg_(sp_reg), return_loc_(return_loc) {}
virtual ~Regs() = default;
- uint16_t pc_reg() { return pc_reg_; }
- uint16_t sp_reg() { return sp_reg_; }
- uint16_t total_regs() { return total_regs_; }
-
- virtual void* raw_data() = 0;
+ virtual void* RawData() = 0;
virtual uint64_t pc() = 0;
virtual uint64_t sp() = 0;
+ virtual bool GetReturnAddressFromDefault(Memory* memory, uint64_t* value) = 0;
+
+ virtual uint64_t GetRelPc(Elf* elf, const MapInfo* map_info) = 0;
+
+ virtual uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) = 0;
+
+ uint16_t sp_reg() { return sp_reg_; }
+ uint16_t total_regs() { return total_regs_; }
+
+ static Regs* RemoteGet(pid_t pid, uint32_t* machine_type);
+
protected:
- uint16_t pc_reg_;
- uint16_t sp_reg_;
uint16_t total_regs_;
+ uint16_t sp_reg_;
+ Location return_loc_;
};
template <typename AddressType>
class RegsTmpl : public Regs {
public:
- RegsTmpl(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
- : Regs(pc_reg, sp_reg, total_regs), regs_(total_regs) {}
+ RegsTmpl(uint16_t total_regs, uint16_t sp_reg, Location return_loc)
+ : Regs(total_regs, sp_reg, return_loc), regs_(total_regs) {}
virtual ~RegsTmpl() = default;
- uint64_t pc() override { return regs_[pc_reg_]; }
- uint64_t sp() override { return regs_[sp_reg_]; }
+ uint64_t GetRelPc(Elf* elf, const MapInfo* map_info) override;
+
+ bool GetReturnAddressFromDefault(Memory* memory, uint64_t* value) override;
+
+ uint64_t pc() override { return pc_; }
+ uint64_t sp() override { return sp_; }
+
+ void set_pc(AddressType pc) { pc_ = pc; }
+ void set_sp(AddressType sp) { sp_ = sp; }
inline AddressType& operator[](size_t reg) { return regs_[reg]; }
- void* raw_data() override { return regs_.data(); }
+ void* RawData() override { return regs_.data(); }
- private:
+ protected:
+ AddressType pc_;
+ AddressType sp_;
std::vector<AddressType> regs_;
};
-class Regs32 : public RegsTmpl<uint32_t> {
+class RegsArm : public RegsTmpl<uint32_t> {
public:
- Regs32(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
- : RegsTmpl(pc_reg, sp_reg, total_regs) {}
- virtual ~Regs32() = default;
+ RegsArm();
+ virtual ~RegsArm() = default;
+
+ uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
};
-class Regs64 : public RegsTmpl<uint64_t> {
+class RegsArm64 : public RegsTmpl<uint64_t> {
public:
- Regs64(uint16_t pc_reg, uint16_t sp_reg, uint16_t total_regs)
- : RegsTmpl(pc_reg, sp_reg, total_regs) {}
- virtual ~Regs64() = default;
+ RegsArm64();
+ virtual ~RegsArm64() = default;
+
+ uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
+};
+
+class RegsX86 : public RegsTmpl<uint32_t> {
+ public:
+ RegsX86();
+ virtual ~RegsX86() = default;
+
+ uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
+};
+
+class RegsX86_64 : public RegsTmpl<uint64_t> {
+ public:
+ RegsX86_64();
+ virtual ~RegsX86_64() = default;
+
+ uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) override;
};
#endif // _LIBUNWINDSTACK_REGS_H
diff --git a/libunwindstack/User.h b/libunwindstack/User.h
new file mode 100644
index 0000000..a695467
--- /dev/null
+++ b/libunwindstack/User.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef _LIBUNWINDSTACK_USER_H
+#define _LIBUNWINDSTACK_USER_H
+
+struct x86_user_regs {
+ uint32_t ebx;
+ uint32_t ecx;
+ uint32_t edx;
+ uint32_t esi;
+ uint32_t edi;
+ uint32_t ebp;
+ uint32_t eax;
+ uint32_t xds;
+ uint32_t xes;
+ uint32_t xfs;
+ uint32_t xgs;
+ uint32_t orig_eax;
+ uint32_t eip;
+ uint32_t xcs;
+ uint32_t eflags;
+ uint32_t esp;
+ uint32_t xss;
+};
+
+struct x86_64_user_regs {
+ uint64_t r15;
+ uint64_t r14;
+ uint64_t r13;
+ uint64_t r12;
+ uint64_t rbp;
+ uint64_t rbx;
+ uint64_t r11;
+ uint64_t r10;
+ uint64_t r9;
+ uint64_t r8;
+ uint64_t rax;
+ uint64_t rcx;
+ uint64_t rdx;
+ uint64_t rsi;
+ uint64_t rdi;
+ uint64_t orig_rax;
+ uint64_t rip;
+ uint64_t cs;
+ uint64_t eflags;
+ uint64_t rsp;
+ uint64_t ss;
+ uint64_t fs_base;
+ uint64_t gs_base;
+ uint64_t ds;
+ uint64_t es;
+ uint64_t fs;
+ uint64_t gs;
+};
+
+struct arm_user_regs {
+ uint32_t regs[18];
+};
+
+struct arm64_user_regs {
+ uint64_t regs[31];
+ uint64_t sp;
+ uint64_t pc;
+ uint64_t pstate;
+};
+
+// The largest user structure.
+constexpr size_t MAX_USER_REGS_SIZE = sizeof(arm64_user_regs) + 10;
+
+#endif // _LIBUNWINDSTACK_USER_H
diff --git a/libunwindstack/tests/ArmExidxDecodeTest.cpp b/libunwindstack/tests/ArmExidxDecodeTest.cpp
index 9ea917a..4fff48e 100644
--- a/libunwindstack/tests/ArmExidxDecodeTest.cpp
+++ b/libunwindstack/tests/ArmExidxDecodeTest.cpp
@@ -24,6 +24,7 @@
#include <gtest/gtest.h>
#include "ArmExidx.h"
+#include "Regs.h"
#include "Log.h"
#include "LogFake.h"
@@ -38,12 +39,14 @@
process_memory = &process_memory_;
}
- regs32_.reset(new Regs32(0, 1, 32));
- for (size_t i = 0; i < 32; i++) {
- (*regs32_)[i] = 0;
+ regs_arm_.reset(new RegsArm());
+ for (size_t i = 0; i < regs_arm_->total_regs(); i++) {
+ (*regs_arm_)[i] = 0;
}
+ regs_arm_->set_pc(0);
+ regs_arm_->set_sp(0);
- exidx_.reset(new ArmExidx(regs32_.get(), &elf_memory_, process_memory));
+ exidx_.reset(new ArmExidx(regs_arm_.get(), &elf_memory_, process_memory));
if (log_) {
exidx_->set_log(true);
exidx_->set_log_indent(0);
@@ -66,7 +69,7 @@
}
std::unique_ptr<ArmExidx> exidx_;
- std::unique_ptr<Regs32> regs32_;
+ std::unique_ptr<RegsArm> regs_arm_;
std::deque<uint8_t>* data_;
MemoryFake elf_memory_;
@@ -78,6 +81,7 @@
// 00xxxxxx: vsp = vsp + (xxxxxx << 2) + 4
data_->push_back(0x00);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp + 4\n", GetFakeLogPrint());
@@ -90,6 +94,7 @@
data_->clear();
data_->push_back(0x01);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp + 8\n", GetFakeLogPrint());
@@ -102,6 +107,7 @@
data_->clear();
data_->push_back(0x3f);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp + 256\n", GetFakeLogPrint());
@@ -115,6 +121,7 @@
// 01xxxxxx: vsp = vsp - (xxxxxx << 2) + 4
data_->push_back(0x40);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp - 4\n", GetFakeLogPrint());
@@ -127,6 +134,7 @@
data_->clear();
data_->push_back(0x41);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp - 8\n", GetFakeLogPrint());
@@ -139,6 +147,7 @@
data_->clear();
data_->push_back(0x7f);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp - 256\n", GetFakeLogPrint());
@@ -164,26 +173,29 @@
TEST_P(ArmExidxDecodeTest, pop_up_to_12) {
// 1000iiii iiiiiiii: Pop up to 12 integer registers
- data_->push_back(0x80);
- data_->push_back(0x01);
- process_memory_.SetData(0x10000, 0x10);
+ data_->push_back(0x88);
+ data_->push_back(0x00);
+ process_memory_.SetData32(0x10000, 0x10);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_TRUE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
- ASSERT_EQ("4 unwind pop {r4}\n", GetFakeLogPrint());
+ ASSERT_EQ("4 unwind pop {r15}\n", GetFakeLogPrint());
} else {
ASSERT_EQ("", GetFakeLogPrint());
}
ASSERT_EQ(0x10004U, exidx_->cfa());
- ASSERT_EQ(0x10U, (*exidx_->regs())[4]);
+ ASSERT_EQ(0x10U, (*exidx_->regs())[15]);
ResetLogs();
data_->push_back(0x8f);
data_->push_back(0xff);
for (size_t i = 0; i < 12; i++) {
- process_memory_.SetData(0x10004 + i * 4, i + 0x20);
+ process_memory_.SetData32(0x10004 + i * 4, i + 0x20);
}
+ exidx_->set_pc_set(false);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_TRUE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15}\n",
@@ -211,10 +223,12 @@
exidx_->set_cfa(0x10034);
data_->push_back(0x81);
data_->push_back(0x28);
- process_memory_.SetData(0x10034, 0x11);
- process_memory_.SetData(0x10038, 0x22);
- process_memory_.SetData(0x1003c, 0x33);
+ process_memory_.SetData32(0x10034, 0x11);
+ process_memory_.SetData32(0x10038, 0x22);
+ process_memory_.SetData32(0x1003c, 0x33);
+ exidx_->set_pc_set(false);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r7, r9, r12}\n", GetFakeLogPrint());
@@ -231,11 +245,12 @@
// 1001nnnn: Set vsp = r[nnnn] (nnnn != 13, 15)
exidx_->set_cfa(0x100);
for (size_t i = 0; i < 15; i++) {
- (*regs32_)[i] = i + 1;
+ (*regs_arm_)[i] = i + 1;
}
data_->push_back(0x90);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = r0\n", GetFakeLogPrint());
@@ -247,6 +262,7 @@
ResetLogs();
data_->push_back(0x93);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = r3\n", GetFakeLogPrint());
@@ -258,6 +274,7 @@
ResetLogs();
data_->push_back(0x9e);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = r14\n", GetFakeLogPrint());
@@ -295,8 +312,9 @@
TEST_P(ArmExidxDecodeTest, pop_registers) {
// 10100nnn: Pop r4-r[4+nnn]
data_->push_back(0xa0);
- process_memory_.SetData(0x10000, 0x14);
+ process_memory_.SetData32(0x10000, 0x14);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4}\n", GetFakeLogPrint());
@@ -308,11 +326,12 @@
ResetLogs();
data_->push_back(0xa3);
- process_memory_.SetData(0x10004, 0x20);
- process_memory_.SetData(0x10008, 0x30);
- process_memory_.SetData(0x1000c, 0x40);
- process_memory_.SetData(0x10010, 0x50);
+ process_memory_.SetData32(0x10004, 0x20);
+ process_memory_.SetData32(0x10008, 0x30);
+ process_memory_.SetData32(0x1000c, 0x40);
+ process_memory_.SetData32(0x10010, 0x50);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4-r7}\n", GetFakeLogPrint());
@@ -327,15 +346,16 @@
ResetLogs();
data_->push_back(0xa7);
- process_memory_.SetData(0x10014, 0x41);
- process_memory_.SetData(0x10018, 0x51);
- process_memory_.SetData(0x1001c, 0x61);
- process_memory_.SetData(0x10020, 0x71);
- process_memory_.SetData(0x10024, 0x81);
- process_memory_.SetData(0x10028, 0x91);
- process_memory_.SetData(0x1002c, 0xa1);
- process_memory_.SetData(0x10030, 0xb1);
+ process_memory_.SetData32(0x10014, 0x41);
+ process_memory_.SetData32(0x10018, 0x51);
+ process_memory_.SetData32(0x1001c, 0x61);
+ process_memory_.SetData32(0x10020, 0x71);
+ process_memory_.SetData32(0x10024, 0x81);
+ process_memory_.SetData32(0x10028, 0x91);
+ process_memory_.SetData32(0x1002c, 0xa1);
+ process_memory_.SetData32(0x10030, 0xb1);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4-r11}\n", GetFakeLogPrint());
@@ -356,9 +376,10 @@
TEST_P(ArmExidxDecodeTest, pop_registers_with_r14) {
// 10101nnn: Pop r4-r[4+nnn], r14
data_->push_back(0xa8);
- process_memory_.SetData(0x10000, 0x12);
- process_memory_.SetData(0x10004, 0x22);
+ process_memory_.SetData32(0x10000, 0x12);
+ process_memory_.SetData32(0x10004, 0x22);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4, r14}\n", GetFakeLogPrint());
@@ -371,12 +392,13 @@
ResetLogs();
data_->push_back(0xab);
- process_memory_.SetData(0x10008, 0x1);
- process_memory_.SetData(0x1000c, 0x2);
- process_memory_.SetData(0x10010, 0x3);
- process_memory_.SetData(0x10014, 0x4);
- process_memory_.SetData(0x10018, 0x5);
+ process_memory_.SetData32(0x10008, 0x1);
+ process_memory_.SetData32(0x1000c, 0x2);
+ process_memory_.SetData32(0x10010, 0x3);
+ process_memory_.SetData32(0x10014, 0x4);
+ process_memory_.SetData32(0x10018, 0x5);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4-r7, r14}\n", GetFakeLogPrint());
@@ -392,16 +414,17 @@
ResetLogs();
data_->push_back(0xaf);
- process_memory_.SetData(0x1001c, 0x1a);
- process_memory_.SetData(0x10020, 0x2a);
- process_memory_.SetData(0x10024, 0x3a);
- process_memory_.SetData(0x10028, 0x4a);
- process_memory_.SetData(0x1002c, 0x5a);
- process_memory_.SetData(0x10030, 0x6a);
- process_memory_.SetData(0x10034, 0x7a);
- process_memory_.SetData(0x10038, 0x8a);
- process_memory_.SetData(0x1003c, 0x9a);
+ process_memory_.SetData32(0x1001c, 0x1a);
+ process_memory_.SetData32(0x10020, 0x2a);
+ process_memory_.SetData32(0x10024, 0x3a);
+ process_memory_.SetData32(0x10028, 0x4a);
+ process_memory_.SetData32(0x1002c, 0x5a);
+ process_memory_.SetData32(0x10030, 0x6a);
+ process_memory_.SetData32(0x10034, 0x7a);
+ process_memory_.SetData32(0x10038, 0x8a);
+ process_memory_.SetData32(0x1003c, 0x9a);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r4-r11, r14}\n", GetFakeLogPrint());
@@ -550,8 +573,9 @@
// 10110001 0000iiii: Pop integer registers {r0, r1, r2, r3}
data_->push_back(0xb1);
data_->push_back(0x01);
- process_memory_.SetData(0x10000, 0x45);
+ process_memory_.SetData32(0x10000, 0x45);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r0}\n", GetFakeLogPrint());
@@ -564,9 +588,10 @@
ResetLogs();
data_->push_back(0xb1);
data_->push_back(0x0a);
- process_memory_.SetData(0x10004, 0x23);
- process_memory_.SetData(0x10008, 0x24);
+ process_memory_.SetData32(0x10004, 0x23);
+ process_memory_.SetData32(0x10008, 0x24);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r1, r3}\n", GetFakeLogPrint());
@@ -580,11 +605,12 @@
ResetLogs();
data_->push_back(0xb1);
data_->push_back(0x0f);
- process_memory_.SetData(0x1000c, 0x65);
- process_memory_.SetData(0x10010, 0x54);
- process_memory_.SetData(0x10014, 0x43);
- process_memory_.SetData(0x10018, 0x32);
+ process_memory_.SetData32(0x1000c, 0x65);
+ process_memory_.SetData32(0x10010, 0x54);
+ process_memory_.SetData32(0x10014, 0x43);
+ process_memory_.SetData32(0x10018, 0x32);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {r0, r1, r2, r3}\n", GetFakeLogPrint());
@@ -603,6 +629,7 @@
data_->push_back(0xb2);
data_->push_back(0x7f);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp + 1024\n", GetFakeLogPrint());
@@ -616,6 +643,7 @@
data_->push_back(0xff);
data_->push_back(0x02);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp + 2048\n", GetFakeLogPrint());
@@ -630,6 +658,7 @@
data_->push_back(0x82);
data_->push_back(0x30);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind vsp = vsp + 3147776\n", GetFakeLogPrint());
@@ -644,6 +673,7 @@
data_->push_back(0xb3);
data_->push_back(0x00);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d0}\n", GetFakeLogPrint());
@@ -656,6 +686,7 @@
data_->push_back(0xb3);
data_->push_back(0x48);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d4-d12}\n", GetFakeLogPrint());
@@ -669,6 +700,7 @@
// 10111nnn: Pop VFP double precision registers D[8]-D[8+nnn] by FSTMFDX
data_->push_back(0xb8);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d8}\n", GetFakeLogPrint());
@@ -680,6 +712,7 @@
ResetLogs();
data_->push_back(0xbb);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d8-d11}\n", GetFakeLogPrint());
@@ -691,6 +724,7 @@
ResetLogs();
data_->push_back(0xbf);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d8-d15}\n", GetFakeLogPrint());
@@ -704,6 +738,7 @@
// 11000nnn: Intel Wireless MMX pop wR[10]-wR[10+nnn] (nnn != 6, 7)
data_->push_back(0xc0);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wR10}\n", GetFakeLogPrint());
@@ -715,6 +750,7 @@
ResetLogs();
data_->push_back(0xc2);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wR10-wR12}\n", GetFakeLogPrint());
@@ -726,6 +762,7 @@
ResetLogs();
data_->push_back(0xc5);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wR10-wR15}\n", GetFakeLogPrint());
@@ -740,6 +777,7 @@
data_->push_back(0xc6);
data_->push_back(0x00);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wR0}\n", GetFakeLogPrint());
@@ -752,6 +790,7 @@
data_->push_back(0xc6);
data_->push_back(0x25);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wR2-wR7}\n", GetFakeLogPrint());
@@ -764,6 +803,7 @@
data_->push_back(0xc6);
data_->push_back(0xff);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wR15-wR30}\n", GetFakeLogPrint());
@@ -778,6 +818,7 @@
data_->push_back(0xc7);
data_->push_back(0x01);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wCGR0}\n", GetFakeLogPrint());
@@ -790,6 +831,7 @@
data_->push_back(0xc7);
data_->push_back(0x0a);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wCGR1, wCGR3}\n", GetFakeLogPrint());
@@ -802,6 +844,7 @@
data_->push_back(0xc7);
data_->push_back(0x0f);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {wCGR0, wCGR1, wCGR2, wCGR3}\n", GetFakeLogPrint());
@@ -816,6 +859,7 @@
data_->push_back(0xc8);
data_->push_back(0x00);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d16}\n", GetFakeLogPrint());
@@ -828,6 +872,7 @@
data_->push_back(0xc8);
data_->push_back(0x14);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d17-d21}\n", GetFakeLogPrint());
@@ -840,6 +885,7 @@
data_->push_back(0xc8);
data_->push_back(0xff);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d31-d46}\n", GetFakeLogPrint());
@@ -854,6 +900,7 @@
data_->push_back(0xc9);
data_->push_back(0x00);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d0}\n", GetFakeLogPrint());
@@ -866,6 +913,7 @@
data_->push_back(0xc9);
data_->push_back(0x23);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d2-d5}\n", GetFakeLogPrint());
@@ -878,6 +926,7 @@
data_->push_back(0xc9);
data_->push_back(0xff);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d15-d30}\n", GetFakeLogPrint());
@@ -891,6 +940,7 @@
// 11010nnn: Pop VFP double precision registers D[8]-D[8+nnn] by VPUSH
data_->push_back(0xd0);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d8}\n", GetFakeLogPrint());
@@ -902,6 +952,7 @@
ResetLogs();
data_->push_back(0xd2);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d8-d10}\n", GetFakeLogPrint());
@@ -913,6 +964,7 @@
ResetLogs();
data_->push_back(0xd7);
ASSERT_TRUE(exidx_->Decode());
+ ASSERT_FALSE(exidx_->pc_set());
ASSERT_EQ("", GetFakeLogBuf());
if (log_) {
ASSERT_EQ("4 unwind pop {d8-d15}\n", GetFakeLogPrint());
@@ -989,4 +1041,54 @@
}
}
+TEST_P(ArmExidxDecodeTest, eval_multiple_decodes) {
+ // vsp = vsp + 4
+ data_->push_back(0x00);
+ // vsp = vsp + 8
+ data_->push_back(0x02);
+ // Finish
+ data_->push_back(0xb0);
+
+ ASSERT_TRUE(exidx_->Eval());
+ if (log_) {
+ ASSERT_EQ("4 unwind vsp = vsp + 4\n"
+ "4 unwind vsp = vsp + 12\n"
+ "4 unwind finish\n", GetFakeLogPrint());
+ } else {
+ ASSERT_EQ("", GetFakeLogPrint());
+ }
+ ASSERT_EQ(0x10010U, exidx_->cfa());
+ ASSERT_FALSE(exidx_->pc_set());
+}
+
+TEST_P(ArmExidxDecodeTest, eval_pc_set) {
+ // vsp = vsp + 4
+ data_->push_back(0x00);
+ // vsp = vsp + 8
+ data_->push_back(0x02);
+ // Pop {r15}
+ data_->push_back(0x88);
+ data_->push_back(0x00);
+ // vsp = vsp + 8
+ data_->push_back(0x02);
+ // Finish
+ data_->push_back(0xb0);
+
+ process_memory_.SetData32(0x10010, 0x10);
+
+ ASSERT_TRUE(exidx_->Eval());
+ if (log_) {
+ ASSERT_EQ("4 unwind vsp = vsp + 4\n"
+ "4 unwind vsp = vsp + 12\n"
+ "4 unwind pop {r15}\n"
+ "4 unwind vsp = vsp + 12\n"
+ "4 unwind finish\n", GetFakeLogPrint());
+ } else {
+ ASSERT_EQ("", GetFakeLogPrint());
+ }
+ ASSERT_EQ(0x10020U, exidx_->cfa());
+ ASSERT_TRUE(exidx_->pc_set());
+ ASSERT_EQ(0x10U, (*exidx_->regs())[15]);
+}
+
INSTANTIATE_TEST_CASE_P(, ArmExidxDecodeTest, ::testing::Values("logging", "no_logging"));
diff --git a/libunwindstack/tests/ArmExidxExtractTest.cpp b/libunwindstack/tests/ArmExidxExtractTest.cpp
index 021765a..aed75bf 100644
--- a/libunwindstack/tests/ArmExidxExtractTest.cpp
+++ b/libunwindstack/tests/ArmExidxExtractTest.cpp
@@ -53,16 +53,16 @@
}
TEST_F(ArmExidxExtractTest, cant_unwind) {
- elf_memory_.SetData(0x1000, 0x7fff2340);
- elf_memory_.SetData(0x1004, 1);
+ elf_memory_.SetData32(0x1000, 0x7fff2340);
+ elf_memory_.SetData32(0x1004, 1);
ASSERT_FALSE(exidx_->ExtractEntryData(0x1000));
ASSERT_EQ(ARM_STATUS_NO_UNWIND, exidx_->status());
ASSERT_TRUE(data_->empty());
}
TEST_F(ArmExidxExtractTest, compact) {
- elf_memory_.SetData(0x4000, 0x7ffa3000);
- elf_memory_.SetData(0x4004, 0x80a8b0b0);
+ elf_memory_.SetData32(0x4000, 0x7ffa3000);
+ elf_memory_.SetData32(0x4004, 0x80a8b0b0);
ASSERT_TRUE(exidx_->ExtractEntryData(0x4000));
ASSERT_EQ(3U, data_->size());
ASSERT_EQ(0xa8, data_->at(0));
@@ -71,8 +71,8 @@
// Missing finish gets added.
elf_memory_.Clear();
- elf_memory_.SetData(0x534, 0x7ffa3000);
- elf_memory_.SetData(0x538, 0x80a1a2a3);
+ elf_memory_.SetData32(0x534, 0x7ffa3000);
+ elf_memory_.SetData32(0x538, 0x80a1a2a3);
ASSERT_TRUE(exidx_->ExtractEntryData(0x534));
ASSERT_EQ(4U, data_->size());
ASSERT_EQ(0xa1, data_->at(0));
@@ -82,29 +82,29 @@
}
TEST_F(ArmExidxExtractTest, compact_non_zero_personality) {
- elf_memory_.SetData(0x4000, 0x7ffa3000);
+ elf_memory_.SetData32(0x4000, 0x7ffa3000);
uint32_t compact_value = 0x80a8b0b0;
for (size_t i = 1; i < 16; i++) {
- elf_memory_.SetData(0x4004, compact_value | (i << 24));
+ elf_memory_.SetData32(0x4004, compact_value | (i << 24));
ASSERT_FALSE(exidx_->ExtractEntryData(0x4000));
ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
}
}
TEST_F(ArmExidxExtractTest, second_read_compact_personality_1_2) {
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x8100f3b0);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x8100f3b0);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(2U, data_->size());
ASSERT_EQ(0xf3, data_->at(0));
ASSERT_EQ(0xb0, data_->at(1));
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x8200f3f4);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x8200f3f4);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(3U, data_->size());
ASSERT_EQ(0xf3, data_->at(0));
@@ -112,10 +112,10 @@
ASSERT_EQ(0xb0, data_->at(2));
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x8201f3f4);
- elf_memory_.SetData(0x6238, 0x102030b0);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x8201f3f4);
+ elf_memory_.SetData32(0x6238, 0x102030b0);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(6U, data_->size());
ASSERT_EQ(0xf3, data_->at(0));
@@ -126,12 +126,12 @@
ASSERT_EQ(0xb0, data_->at(5));
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x8103f3f4);
- elf_memory_.SetData(0x6238, 0x10203040);
- elf_memory_.SetData(0x623c, 0x50607080);
- elf_memory_.SetData(0x6240, 0x90a0c0d0);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x8103f3f4);
+ elf_memory_.SetData32(0x6238, 0x10203040);
+ elf_memory_.SetData32(0x623c, 0x50607080);
+ elf_memory_.SetData32(0x6240, 0x90a0c0d0);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(15U, data_->size());
ASSERT_EQ(0xf3, data_->at(0));
@@ -152,33 +152,33 @@
}
TEST_F(ArmExidxExtractTest, second_read_compact_personality_illegal) {
- elf_memory_.SetData(0x5000, 0x7ffa1e48);
- elf_memory_.SetData(0x5004, 0x1230);
- elf_memory_.SetData(0x6234, 0x832132b0);
+ elf_memory_.SetData32(0x5000, 0x7ffa1e48);
+ elf_memory_.SetData32(0x5004, 0x1230);
+ elf_memory_.SetData32(0x6234, 0x832132b0);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x7ffa1e48);
- elf_memory_.SetData(0x5004, 0x1230);
- elf_memory_.SetData(0x6234, 0x842132b0);
+ elf_memory_.SetData32(0x5000, 0x7ffa1e48);
+ elf_memory_.SetData32(0x5004, 0x1230);
+ elf_memory_.SetData32(0x6234, 0x842132b0);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
}
TEST_F(ArmExidxExtractTest, second_read_offset_is_negative) {
- elf_memory_.SetData(0x5000, 0x7ffa1e48);
- elf_memory_.SetData(0x5004, 0x7fffb1e0);
- elf_memory_.SetData(0x1e4, 0x842132b0);
+ elf_memory_.SetData32(0x5000, 0x7ffa1e48);
+ elf_memory_.SetData32(0x5004, 0x7fffb1e0);
+ elf_memory_.SetData32(0x1e4, 0x842132b0);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_INVALID_PERSONALITY, exidx_->status());
}
TEST_F(ArmExidxExtractTest, second_read_not_compact) {
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x1);
- elf_memory_.SetData(0x6238, 0x001122b0);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x1);
+ elf_memory_.SetData32(0x6238, 0x001122b0);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(3U, data_->size());
ASSERT_EQ(0x11, data_->at(0));
@@ -186,10 +186,10 @@
ASSERT_EQ(0xb0, data_->at(2));
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x2);
- elf_memory_.SetData(0x6238, 0x00112233);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x2);
+ elf_memory_.SetData32(0x6238, 0x00112233);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(4U, data_->size());
ASSERT_EQ(0x11, data_->at(0));
@@ -198,11 +198,11 @@
ASSERT_EQ(0xb0, data_->at(3));
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x3);
- elf_memory_.SetData(0x6238, 0x01112233);
- elf_memory_.SetData(0x623c, 0x445566b0);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x3);
+ elf_memory_.SetData32(0x6238, 0x01112233);
+ elf_memory_.SetData32(0x623c, 0x445566b0);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(7U, data_->size());
ASSERT_EQ(0x11, data_->at(0));
@@ -214,15 +214,15 @@
ASSERT_EQ(0xb0, data_->at(6));
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x3);
- elf_memory_.SetData(0x6238, 0x05112233);
- elf_memory_.SetData(0x623c, 0x01020304);
- elf_memory_.SetData(0x6240, 0x05060708);
- elf_memory_.SetData(0x6244, 0x090a0b0c);
- elf_memory_.SetData(0x6248, 0x0d0e0f10);
- elf_memory_.SetData(0x624c, 0x11121314);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x3);
+ elf_memory_.SetData32(0x6238, 0x05112233);
+ elf_memory_.SetData32(0x623c, 0x01020304);
+ elf_memory_.SetData32(0x6240, 0x05060708);
+ elf_memory_.SetData32(0x6244, 0x090a0b0c);
+ elf_memory_.SetData32(0x6248, 0x0d0e0f10);
+ elf_memory_.SetData32(0x624c, 0x11121314);
ASSERT_TRUE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(24U, data_->size());
ASSERT_EQ(0x11, data_->at(0));
@@ -255,43 +255,43 @@
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
- elf_memory_.SetData(0x5000, 0x100);
+ elf_memory_.SetData32(0x5000, 0x100);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
- elf_memory_.SetData(0x5004, 0x100);
+ elf_memory_.SetData32(0x5004, 0x100);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
- elf_memory_.SetData(0x5104, 0x1);
+ elf_memory_.SetData32(0x5104, 0x1);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
- elf_memory_.SetData(0x5108, 0x01010203);
+ elf_memory_.SetData32(0x5108, 0x01010203);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_READ_FAILED, exidx_->status());
}
TEST_F(ArmExidxExtractTest, malformed) {
- elf_memory_.SetData(0x5000, 0x100);
- elf_memory_.SetData(0x5004, 0x100);
- elf_memory_.SetData(0x5104, 0x1);
- elf_memory_.SetData(0x5108, 0x06010203);
+ elf_memory_.SetData32(0x5000, 0x100);
+ elf_memory_.SetData32(0x5004, 0x100);
+ elf_memory_.SetData32(0x5104, 0x1);
+ elf_memory_.SetData32(0x5108, 0x06010203);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_MALFORMED, exidx_->status());
elf_memory_.Clear();
- elf_memory_.SetData(0x5000, 0x100);
- elf_memory_.SetData(0x5004, 0x100);
- elf_memory_.SetData(0x5104, 0x1);
- elf_memory_.SetData(0x5108, 0x81060203);
+ elf_memory_.SetData32(0x5000, 0x100);
+ elf_memory_.SetData32(0x5004, 0x100);
+ elf_memory_.SetData32(0x5104, 0x1);
+ elf_memory_.SetData32(0x5108, 0x81060203);
ASSERT_FALSE(exidx_->ExtractEntryData(0x5000));
ASSERT_EQ(ARM_STATUS_MALFORMED, exidx_->status());
}
TEST_F(ArmExidxExtractTest, cant_unwind_log) {
- elf_memory_.SetData(0x1000, 0x7fff2340);
- elf_memory_.SetData(0x1004, 1);
+ elf_memory_.SetData32(0x1000, 0x7fff2340);
+ elf_memory_.SetData32(0x1004, 1);
exidx_->set_log(true);
exidx_->set_log_indent(0);
@@ -305,8 +305,8 @@
}
TEST_F(ArmExidxExtractTest, raw_data_compact) {
- elf_memory_.SetData(0x4000, 0x7ffa3000);
- elf_memory_.SetData(0x4004, 0x80a8b0b0);
+ elf_memory_.SetData32(0x4000, 0x7ffa3000);
+ elf_memory_.SetData32(0x4004, 0x80a8b0b0);
exidx_->set_log(true);
exidx_->set_log_indent(0);
@@ -317,10 +317,10 @@
}
TEST_F(ArmExidxExtractTest, raw_data_non_compact) {
- elf_memory_.SetData(0x5000, 0x1234);
- elf_memory_.SetData(0x5004, 0x00001230);
- elf_memory_.SetData(0x6234, 0x2);
- elf_memory_.SetData(0x6238, 0x00112233);
+ elf_memory_.SetData32(0x5000, 0x1234);
+ elf_memory_.SetData32(0x5004, 0x00001230);
+ elf_memory_.SetData32(0x6234, 0x2);
+ elf_memory_.SetData32(0x6238, 0x00112233);
exidx_->set_log(true);
exidx_->set_log_indent(0);
diff --git a/libunwindstack/tests/ElfInterfaceArmTest.cpp b/libunwindstack/tests/ElfInterfaceArmTest.cpp
new file mode 100644
index 0000000..67c9a6b
--- /dev/null
+++ b/libunwindstack/tests/ElfInterfaceArmTest.cpp
@@ -0,0 +1,372 @@
+/*
+ * Copyright (C) 2016 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 <gtest/gtest.h>
+
+#include <vector>
+
+#include "ElfInterfaceArm.h"
+#include "Machine.h"
+#include "Regs.h"
+
+#include "MemoryFake.h"
+
+class ElfInterfaceArmTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ memory_.Clear();
+ process_memory_.Clear();
+ }
+
+ MemoryFake memory_;
+ MemoryFake process_memory_;
+};
+
+TEST_F(ElfInterfaceArmTest, GetPrel32Addr) {
+ ElfInterfaceArm interface(&memory_);
+ memory_.SetData32(0x1000, 0x230000);
+
+ uint32_t value;
+ ASSERT_TRUE(interface.GetPrel31Addr(0x1000, &value));
+ ASSERT_EQ(0x231000U, value);
+
+ memory_.SetData32(0x1000, 0x80001000);
+ ASSERT_TRUE(interface.GetPrel31Addr(0x1000, &value));
+ ASSERT_EQ(0x2000U, value);
+
+ memory_.SetData32(0x1000, 0x70001000);
+ ASSERT_TRUE(interface.GetPrel31Addr(0x1000, &value));
+ ASSERT_EQ(0xf0002000U, value);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_start_zero) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0);
+ interface.set_total_entries(10);
+
+ uint64_t entry_offset;
+ ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_no_entries) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x100);
+ interface.set_total_entries(0);
+
+ uint64_t entry_offset;
+ ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_no_valid_memory) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x100);
+ interface.set_total_entries(2);
+
+ uint64_t entry_offset;
+ ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_ip_before_first) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(1);
+ memory_.SetData32(0x1000, 0x6000);
+
+ uint64_t entry_offset;
+ ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_single_entry_negative_value) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x8000);
+ interface.set_total_entries(1);
+ memory_.SetData32(0x8000, 0x7fffff00);
+
+ uint64_t entry_offset;
+ ASSERT_TRUE(interface.FindEntry(0x7ff0, &entry_offset));
+ ASSERT_EQ(0x8000U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_two_entries) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(2);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1008, 0x7000);
+
+ uint64_t entry_offset;
+ ASSERT_TRUE(interface.FindEntry(0x7000, &entry_offset));
+ ASSERT_EQ(0x1000U, entry_offset);
+}
+
+
+TEST_F(ElfInterfaceArmTest, FindEntry_last_check_single_entry) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(1);
+ memory_.SetData32(0x1000, 0x6000);
+
+ uint64_t entry_offset;
+ ASSERT_TRUE(interface.FindEntry(0x7000, &entry_offset));
+ ASSERT_EQ(0x1000U, entry_offset);
+
+ // To guarantee that we are using the cache on the second run,
+ // set the memory to a different value.
+ memory_.SetData32(0x1000, 0x8000);
+ ASSERT_TRUE(interface.FindEntry(0x7004, &entry_offset));
+ ASSERT_EQ(0x1000U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_last_check_multiple_entries) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(2);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1008, 0x8000);
+
+ uint64_t entry_offset;
+ ASSERT_TRUE(interface.FindEntry(0x9008, &entry_offset));
+ ASSERT_EQ(0x1008U, entry_offset);
+
+ // To guarantee that we are using the cache on the second run,
+ // set the memory to a different value.
+ memory_.SetData32(0x1000, 0x16000);
+ memory_.SetData32(0x1008, 0x18000);
+ ASSERT_TRUE(interface.FindEntry(0x9100, &entry_offset));
+ ASSERT_EQ(0x1008U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_multiple_entries_even) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(4);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1008, 0x7000);
+ memory_.SetData32(0x1010, 0x8000);
+ memory_.SetData32(0x1018, 0x9000);
+
+ uint64_t entry_offset;
+ ASSERT_TRUE(interface.FindEntry(0x9100, &entry_offset));
+ ASSERT_EQ(0x1010U, entry_offset);
+
+ // To guarantee that we are using the cache on the second run,
+ // set the memory to a different value.
+ memory_.SetData32(0x1000, 0x16000);
+ memory_.SetData32(0x1008, 0x17000);
+ memory_.SetData32(0x1010, 0x18000);
+ memory_.SetData32(0x1018, 0x19000);
+ ASSERT_TRUE(interface.FindEntry(0x9100, &entry_offset));
+ ASSERT_EQ(0x1010U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_multiple_entries_odd) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(5);
+ memory_.SetData32(0x1000, 0x5000);
+ memory_.SetData32(0x1008, 0x6000);
+ memory_.SetData32(0x1010, 0x7000);
+ memory_.SetData32(0x1018, 0x8000);
+ memory_.SetData32(0x1020, 0x9000);
+
+ uint64_t entry_offset;
+ ASSERT_TRUE(interface.FindEntry(0x8100, &entry_offset));
+ ASSERT_EQ(0x1010U, entry_offset);
+
+ // To guarantee that we are using the cache on the second run,
+ // set the memory to a different value.
+ memory_.SetData32(0x1000, 0x15000);
+ memory_.SetData32(0x1008, 0x16000);
+ memory_.SetData32(0x1010, 0x17000);
+ memory_.SetData32(0x1018, 0x18000);
+ memory_.SetData32(0x1020, 0x19000);
+ ASSERT_TRUE(interface.FindEntry(0x8100, &entry_offset));
+ ASSERT_EQ(0x1010U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, iterate) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(5);
+ memory_.SetData32(0x1000, 0x5000);
+ memory_.SetData32(0x1008, 0x6000);
+ memory_.SetData32(0x1010, 0x7000);
+ memory_.SetData32(0x1018, 0x8000);
+ memory_.SetData32(0x1020, 0x9000);
+
+ std::vector<uint32_t> entries;
+ for (auto addr : interface) {
+ entries.push_back(addr);
+ }
+ ASSERT_EQ(5U, entries.size());
+ ASSERT_EQ(0x6000U, entries[0]);
+ ASSERT_EQ(0x7008U, entries[1]);
+ ASSERT_EQ(0x8010U, entries[2]);
+ ASSERT_EQ(0x9018U, entries[3]);
+ ASSERT_EQ(0xa020U, entries[4]);
+
+ // Make sure the iterate cached the entries.
+ memory_.SetData32(0x1000, 0x11000);
+ memory_.SetData32(0x1008, 0x12000);
+ memory_.SetData32(0x1010, 0x13000);
+ memory_.SetData32(0x1018, 0x14000);
+ memory_.SetData32(0x1020, 0x15000);
+
+ entries.clear();
+ for (auto addr : interface) {
+ entries.push_back(addr);
+ }
+ ASSERT_EQ(5U, entries.size());
+ ASSERT_EQ(0x6000U, entries[0]);
+ ASSERT_EQ(0x7008U, entries[1]);
+ ASSERT_EQ(0x8010U, entries[2]);
+ ASSERT_EQ(0x9018U, entries[3]);
+ ASSERT_EQ(0xa020U, entries[4]);
+}
+
+TEST_F(ElfInterfaceArmTest, FindEntry_load_bias) {
+ ElfInterfaceArm interface(&memory_);
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(2);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1008, 0x8000);
+
+ uint64_t entry_offset;
+ interface.set_load_bias(0x2000);
+ ASSERT_FALSE(interface.FindEntry(0x1000, &entry_offset));
+ ASSERT_FALSE(interface.FindEntry(0x8000, &entry_offset));
+ ASSERT_FALSE(interface.FindEntry(0x8fff, &entry_offset));
+ ASSERT_TRUE(interface.FindEntry(0x9000, &entry_offset));
+ ASSERT_EQ(0x1000U, entry_offset);
+ ASSERT_TRUE(interface.FindEntry(0xb007, &entry_offset));
+ ASSERT_EQ(0x1000U, entry_offset);
+ ASSERT_TRUE(interface.FindEntry(0xb008, &entry_offset));
+ ASSERT_EQ(0x1008U, entry_offset);
+}
+
+TEST_F(ElfInterfaceArmTest, HandleType_not_arm_exidx) {
+ ElfInterfaceArm interface(&memory_);
+
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_NULL));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_LOAD));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_DYNAMIC));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_INTERP));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_NOTE));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_SHLIB));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_PHDR));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_TLS));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_LOOS));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_HIOS));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_LOPROC));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_HIPROC));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_GNU_EH_FRAME));
+ ASSERT_FALSE(interface.HandleType(0x1000, PT_GNU_STACK));
+}
+
+TEST_F(ElfInterfaceArmTest, HandleType_arm_exidx) {
+ ElfInterfaceArm interface(&memory_);
+
+ Elf32_Phdr phdr;
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(100);
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 0xa00;
+
+ // Verify that if reads fail, we don't set the values but still get true.
+ ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+ ASSERT_EQ(0x1000U, interface.start_offset());
+ ASSERT_EQ(100U, interface.total_entries());
+
+ // Verify that if the second read fails, we still don't set the values.
+ memory_.SetData32(
+ 0x1000 + reinterpret_cast<uint64_t>(&phdr.p_vaddr) - reinterpret_cast<uint64_t>(&phdr),
+ phdr.p_vaddr);
+ ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+ ASSERT_EQ(0x1000U, interface.start_offset());
+ ASSERT_EQ(100U, interface.total_entries());
+
+ // Everything is correct and present.
+ memory_.SetData32(
+ 0x1000 + reinterpret_cast<uint64_t>(&phdr.p_memsz) - reinterpret_cast<uint64_t>(&phdr),
+ phdr.p_memsz);
+ ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+ ASSERT_EQ(0x2000U, interface.start_offset());
+ ASSERT_EQ(320U, interface.total_entries());
+
+ // Non-zero load bias.
+ interface.set_load_bias(0x1000);
+ ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
+ ASSERT_EQ(0x1000U, interface.start_offset());
+ ASSERT_EQ(320U, interface.total_entries());
+}
+
+TEST_F(ElfInterfaceArmTest, StepExidx) {
+ ElfInterfaceArm interface(&memory_);
+
+ // FindEntry fails.
+ ASSERT_FALSE(interface.StepExidx(0x7000, nullptr, nullptr));
+
+ // ExtractEntry should fail.
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(2);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1008, 0x8000);
+
+ RegsArm regs;
+ regs[ARM_REG_SP] = 0x1000;
+ regs[ARM_REG_LR] = 0x20000;
+ regs.set_sp(regs[ARM_REG_SP]);
+ regs.set_pc(0x1234);
+ ASSERT_FALSE(interface.StepExidx(0x7000, ®s, &process_memory_));
+
+ // Eval should fail.
+ memory_.SetData32(0x1004, 0x81000000);
+ ASSERT_FALSE(interface.StepExidx(0x7000, ®s, &process_memory_));
+
+ // Everything should pass.
+ memory_.SetData32(0x1004, 0x80b0b0b0);
+ ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_));
+ ASSERT_EQ(0x1000U, regs.sp());
+ ASSERT_EQ(0x1000U, regs[ARM_REG_SP]);
+ ASSERT_EQ(0x20000U, regs.pc());
+ ASSERT_EQ(0x20000U, regs[ARM_REG_PC]);
+}
+
+TEST_F(ElfInterfaceArmTest, StepExidx_pc_set) {
+ ElfInterfaceArm interface(&memory_);
+
+ interface.set_start_offset(0x1000);
+ interface.set_total_entries(2);
+ memory_.SetData32(0x1000, 0x6000);
+ memory_.SetData32(0x1004, 0x808800b0);
+ memory_.SetData32(0x1008, 0x8000);
+ process_memory_.SetData32(0x10000, 0x10);
+
+ RegsArm regs;
+ regs[ARM_REG_SP] = 0x10000;
+ regs[ARM_REG_LR] = 0x20000;
+ regs.set_sp(regs[ARM_REG_SP]);
+ regs.set_pc(0x1234);
+
+ // Everything should pass.
+ ASSERT_TRUE(interface.StepExidx(0x7000, ®s, &process_memory_));
+ ASSERT_EQ(0x10004U, regs.sp());
+ ASSERT_EQ(0x10004U, regs[ARM_REG_SP]);
+ ASSERT_EQ(0x10U, regs.pc());
+ ASSERT_EQ(0x10U, regs[ARM_REG_PC]);
+}
diff --git a/libunwindstack/tests/ElfInterfaceTest.cpp b/libunwindstack/tests/ElfInterfaceTest.cpp
new file mode 100644
index 0000000..c31903d
--- /dev/null
+++ b/libunwindstack/tests/ElfInterfaceTest.cpp
@@ -0,0 +1,573 @@
+/*
+ * Copyright (C) 2016 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 <memory>
+
+#include <gtest/gtest.h>
+
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+
+#include "MemoryFake.h"
+
+#if !defined(PT_ARM_EXIDX)
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+#if !defined(EM_AARCH64)
+#define EM_AARCH64 183
+#endif
+
+class ElfInterfaceTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ memory_.Clear();
+ }
+
+ void SetStringMemory(uint64_t offset, const char* string) {
+ memory_.SetMemory(offset, string, strlen(string) + 1);
+ }
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void SinglePtLoad();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void MultipleExecutablePtLoads();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void NonExecutablePtLoads();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void ManyPhdrs();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void Soname();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void SonameAfterDtNull();
+
+ template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+ void SonameSize();
+
+ MemoryFake memory_;
+};
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::SinglePtLoad() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 1;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1000;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ ASSERT_TRUE(elf->Init());
+
+ const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+ ASSERT_EQ(1U, pt_loads.size());
+ LoadInfo load_data = pt_loads.at(0);
+ ASSERT_EQ(0U, load_data.offset);
+ ASSERT_EQ(0x2000U, load_data.table_offset);
+ ASSERT_EQ(0x10000U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_single_pt_load) {
+ SinglePtLoad<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_single_pt_load) {
+ SinglePtLoad<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::MultipleExecutablePtLoads() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 3;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1000;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0x1000;
+ phdr.p_vaddr = 0x2001;
+ phdr.p_memsz = 0x10001;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1001;
+ memory_.SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0x2000;
+ phdr.p_vaddr = 0x2002;
+ phdr.p_memsz = 0x10002;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1002;
+ memory_.SetMemory(0x100 + 2 * sizeof(phdr), &phdr, sizeof(phdr));
+
+ ASSERT_TRUE(elf->Init());
+
+ const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+ ASSERT_EQ(3U, pt_loads.size());
+
+ LoadInfo load_data = pt_loads.at(0);
+ ASSERT_EQ(0U, load_data.offset);
+ ASSERT_EQ(0x2000U, load_data.table_offset);
+ ASSERT_EQ(0x10000U, load_data.table_size);
+
+ load_data = pt_loads.at(0x1000);
+ ASSERT_EQ(0x1000U, load_data.offset);
+ ASSERT_EQ(0x2001U, load_data.table_offset);
+ ASSERT_EQ(0x10001U, load_data.table_size);
+
+ load_data = pt_loads.at(0x2000);
+ ASSERT_EQ(0x2000U, load_data.offset);
+ ASSERT_EQ(0x2002U, load_data.table_offset);
+ ASSERT_EQ(0x10002U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_multiple_executable_pt_loads) {
+ MultipleExecutablePtLoads<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_multiple_executable_pt_loads) {
+ MultipleExecutablePtLoads<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 3;
+ ehdr.e_phentsize = sizeof(Phdr) + 100;
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1000;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0x1000;
+ phdr.p_vaddr = 0x2001;
+ phdr.p_memsz = 0x10001;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1001;
+ memory_.SetMemory(0x100 + sizeof(phdr) + 100, &phdr, sizeof(phdr));
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0x2000;
+ phdr.p_vaddr = 0x2002;
+ phdr.p_memsz = 0x10002;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1002;
+ memory_.SetMemory(0x100 + 2 * (sizeof(phdr) + 100), &phdr, sizeof(phdr));
+
+ ASSERT_TRUE(elf->Init());
+
+ const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+ ASSERT_EQ(3U, pt_loads.size());
+
+ LoadInfo load_data = pt_loads.at(0);
+ ASSERT_EQ(0U, load_data.offset);
+ ASSERT_EQ(0x2000U, load_data.table_offset);
+ ASSERT_EQ(0x10000U, load_data.table_size);
+
+ load_data = pt_loads.at(0x1000);
+ ASSERT_EQ(0x1000U, load_data.offset);
+ ASSERT_EQ(0x2001U, load_data.table_offset);
+ ASSERT_EQ(0x10001U, load_data.table_size);
+
+ load_data = pt_loads.at(0x2000);
+ ASSERT_EQ(0x2000U, load_data.offset);
+ ASSERT_EQ(0x2002U, load_data.table_offset);
+ ASSERT_EQ(0x10002U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_multiple_executable_pt_loads_increments_not_size_of_phdr) {
+ MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn,
+ ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_multiple_executable_pt_loads_increments_not_size_of_phdr) {
+ MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn,
+ ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::NonExecutablePtLoads() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 3;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R;
+ phdr.p_align = 0x1000;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0x1000;
+ phdr.p_vaddr = 0x2001;
+ phdr.p_memsz = 0x10001;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1001;
+ memory_.SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0x2000;
+ phdr.p_vaddr = 0x2002;
+ phdr.p_memsz = 0x10002;
+ phdr.p_flags = PF_R;
+ phdr.p_align = 0x1002;
+ memory_.SetMemory(0x100 + 2 * sizeof(phdr), &phdr, sizeof(phdr));
+
+ ASSERT_TRUE(elf->Init());
+
+ const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+ ASSERT_EQ(1U, pt_loads.size());
+
+ LoadInfo load_data = pt_loads.at(0x1000);
+ ASSERT_EQ(0x1000U, load_data.offset);
+ ASSERT_EQ(0x2001U, load_data.table_offset);
+ ASSERT_EQ(0x10001U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_non_executable_pt_loads) {
+ NonExecutablePtLoads<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_non_executable_pt_loads) {
+ NonExecutablePtLoads<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::ManyPhdrs() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 7;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ uint64_t phdr_offset = 0x100;
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1000;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_GNU_EH_FRAME;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_DYNAMIC;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_INTERP;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_NOTE;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_SHLIB;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_GNU_EH_FRAME;
+ memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+ phdr_offset += sizeof(phdr);
+
+ ASSERT_TRUE(elf->Init());
+
+ const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
+ ASSERT_EQ(1U, pt_loads.size());
+
+ LoadInfo load_data = pt_loads.at(0);
+ ASSERT_EQ(0U, load_data.offset);
+ ASSERT_EQ(0x2000U, load_data.table_offset);
+ ASSERT_EQ(0x10000U, load_data.table_size);
+}
+
+TEST_F(ElfInterfaceTest, elf32_many_phdrs) {
+ ElfInterfaceTest::ManyPhdrs<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_many_phdrs) {
+ ElfInterfaceTest::ManyPhdrs<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+TEST_F(ElfInterfaceTest, elf32_arm) {
+ ElfInterfaceArm elf_arm(&memory_);
+
+ Elf32_Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 1;
+ ehdr.e_phentsize = sizeof(Elf32_Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Elf32_Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_ARM_EXIDX;
+ phdr.p_vaddr = 0x2000;
+ phdr.p_memsz = 16;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ // Add arm exidx entries.
+ memory_.SetData32(0x2000, 0x1000);
+ memory_.SetData32(0x2008, 0x1000);
+
+ ASSERT_TRUE(elf_arm.Init());
+
+ std::vector<uint32_t> entries;
+ for (auto addr : elf_arm) {
+ entries.push_back(addr);
+ }
+ ASSERT_EQ(2U, entries.size());
+ ASSERT_EQ(0x3000U, entries[0]);
+ ASSERT_EQ(0x3008U, entries[1]);
+
+ ASSERT_EQ(0x2000U, elf_arm.start_offset());
+ ASSERT_EQ(2U, elf_arm.total_entries());
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::Soname() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 1;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_DYNAMIC;
+ phdr.p_offset = 0x2000;
+ phdr.p_memsz = sizeof(Dyn) * 3;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ uint64_t offset = 0x2000;
+ Dyn dyn;
+
+ dyn.d_tag = DT_STRTAB;
+ dyn.d_un.d_ptr = 0x10000;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_STRSZ;
+ dyn.d_un.d_val = 0x1000;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_SONAME;
+ dyn.d_un.d_val = 0x10;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_NULL;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+
+ SetStringMemory(0x10010, "fake_soname.so");
+
+ ASSERT_TRUE(elf->Init());
+ std::string name;
+ ASSERT_TRUE(elf->GetSoname(&name));
+ ASSERT_STREQ("fake_soname.so", name.c_str());
+}
+
+TEST_F(ElfInterfaceTest, elf32_soname) {
+ Soname<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_soname) {
+ Soname<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::SonameAfterDtNull() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 1;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_DYNAMIC;
+ phdr.p_offset = 0x2000;
+ phdr.p_memsz = sizeof(Dyn) * 3;
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ Dyn dyn;
+ uint64_t offset = 0x2000;
+
+ dyn.d_tag = DT_STRTAB;
+ dyn.d_un.d_ptr = 0x10000;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_STRSZ;
+ dyn.d_un.d_val = 0x1000;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_NULL;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_SONAME;
+ dyn.d_un.d_val = 0x10;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ SetStringMemory(0x10010, "fake_soname.so");
+
+ ASSERT_TRUE(elf->Init());
+ std::string name;
+ ASSERT_FALSE(elf->GetSoname(&name));
+}
+
+TEST_F(ElfInterfaceTest, elf32_soname_after_dt_null) {
+ SonameAfterDtNull<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_soname_after_dt_null) {
+ SonameAfterDtNull<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
+
+template <typename Ehdr, typename Phdr, typename Dyn, typename ElfInterfaceType>
+void ElfInterfaceTest::SonameSize() {
+ std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+ Ehdr ehdr;
+ memset(&ehdr, 0, sizeof(ehdr));
+ ehdr.e_phoff = 0x100;
+ ehdr.e_phnum = 1;
+ ehdr.e_phentsize = sizeof(Phdr);
+ memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_DYNAMIC;
+ phdr.p_offset = 0x2000;
+ phdr.p_memsz = sizeof(Dyn);
+ memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+ Dyn dyn;
+ uint64_t offset = 0x2000;
+
+ dyn.d_tag = DT_STRTAB;
+ dyn.d_un.d_ptr = 0x10000;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_STRSZ;
+ dyn.d_un.d_val = 0x10;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_SONAME;
+ dyn.d_un.d_val = 0x10;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+ offset += sizeof(dyn);
+
+ dyn.d_tag = DT_NULL;
+ memory_.SetMemory(offset, &dyn, sizeof(dyn));
+
+ SetStringMemory(0x10010, "fake_soname.so");
+
+ ASSERT_TRUE(elf->Init());
+ std::string name;
+ ASSERT_FALSE(elf->GetSoname(&name));
+}
+
+TEST_F(ElfInterfaceTest, elf32_soname_size) {
+ SonameSize<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, elf64_soname_size) {
+ SonameSize<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
+}
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
new file mode 100644
index 0000000..25fec8e
--- /dev/null
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -0,0 +1,210 @@
+/*
+ * Copyright (C) 2016 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 <gtest/gtest.h>
+
+#include "Elf.h"
+
+#include "MemoryFake.h"
+
+#if !defined(PT_ARM_EXIDX)
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+#if !defined(EM_AARCH64)
+#define EM_AARCH64 183
+#endif
+
+class ElfTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ memory_ = new MemoryFake;
+ }
+
+ template <typename Ehdr>
+ void InitEhdr(Ehdr* ehdr) {
+ memset(ehdr, 0, sizeof(Ehdr));
+ memcpy(&ehdr->e_ident[0], ELFMAG, SELFMAG);
+ ehdr->e_ident[EI_DATA] = ELFDATA2LSB;
+ ehdr->e_ident[EI_VERSION] = EV_CURRENT;
+ ehdr->e_ident[EI_OSABI] = ELFOSABI_SYSV;
+ }
+
+ void InitElf32(uint32_t type) {
+ Elf32_Ehdr ehdr;
+
+ InitEhdr<Elf32_Ehdr>(&ehdr);
+ ehdr.e_ident[EI_CLASS] = ELFCLASS32;
+
+ ehdr.e_type = ET_DYN;
+ ehdr.e_machine = type;
+ ehdr.e_version = EV_CURRENT;
+ ehdr.e_entry = 0;
+ ehdr.e_phoff = 0x100;
+ ehdr.e_shoff = 0;
+ ehdr.e_flags = 0;
+ ehdr.e_ehsize = sizeof(ehdr);
+ ehdr.e_phentsize = sizeof(Elf32_Phdr);
+ ehdr.e_phnum = 1;
+ ehdr.e_shentsize = sizeof(Elf32_Shdr);
+ ehdr.e_shnum = 0;
+ ehdr.e_shstrndx = 0;
+ if (type == EM_ARM) {
+ ehdr.e_flags = 0x5000200;
+ ehdr.e_phnum = 2;
+ }
+ memory_->SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Elf32_Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0;
+ phdr.p_vaddr = 0;
+ phdr.p_paddr = 0;
+ phdr.p_filesz = 0x10000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1000;
+ memory_->SetMemory(0x100, &phdr, sizeof(phdr));
+
+ if (type == EM_ARM) {
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_ARM_EXIDX;
+ phdr.p_offset = 0x30000;
+ phdr.p_vaddr = 0x30000;
+ phdr.p_paddr = 0x30000;
+ phdr.p_filesz = 16;
+ phdr.p_memsz = 16;
+ phdr.p_flags = PF_R;
+ phdr.p_align = 0x4;
+ memory_->SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+ }
+ }
+
+ void InitElf64(uint32_t type) {
+ Elf64_Ehdr ehdr;
+
+ InitEhdr<Elf64_Ehdr>(&ehdr);
+ ehdr.e_ident[EI_CLASS] = ELFCLASS64;
+
+ ehdr.e_type = ET_DYN;
+ ehdr.e_machine = type;
+ ehdr.e_version = EV_CURRENT;
+ ehdr.e_entry = 0;
+ ehdr.e_phoff = 0x100;
+ ehdr.e_shoff = 0;
+ ehdr.e_flags = 0x5000200;
+ ehdr.e_ehsize = sizeof(ehdr);
+ ehdr.e_phentsize = sizeof(Elf64_Phdr);
+ ehdr.e_phnum = 1;
+ ehdr.e_shentsize = sizeof(Elf64_Shdr);
+ ehdr.e_shnum = 0;
+ ehdr.e_shstrndx = 0;
+ memory_->SetMemory(0, &ehdr, sizeof(ehdr));
+
+ Elf64_Phdr phdr;
+ memset(&phdr, 0, sizeof(phdr));
+ phdr.p_type = PT_LOAD;
+ phdr.p_offset = 0;
+ phdr.p_vaddr = 0;
+ phdr.p_paddr = 0;
+ phdr.p_filesz = 0x10000;
+ phdr.p_memsz = 0x10000;
+ phdr.p_flags = PF_R | PF_X;
+ phdr.p_align = 0x1000;
+ memory_->SetMemory(0x100, &phdr, sizeof(phdr));
+ }
+
+ MemoryFake* memory_;
+};
+
+TEST_F(ElfTest, invalid_memory) {
+ Elf elf(memory_);
+
+ ASSERT_FALSE(elf.Init());
+ ASSERT_FALSE(elf.valid());
+}
+
+TEST_F(ElfTest, elf_invalid) {
+ Elf elf(memory_);
+
+ InitElf32(EM_386);
+
+ // Corrupt the ELF signature.
+ memory_->SetData32(0, 0x7f000000);
+
+ ASSERT_FALSE(elf.Init());
+ ASSERT_FALSE(elf.valid());
+ ASSERT_TRUE(elf.interface() == nullptr);
+
+ std::string name;
+ ASSERT_FALSE(elf.GetSoname(&name));
+
+ uint64_t func_offset;
+ ASSERT_FALSE(elf.GetFunctionName(0, &name, &func_offset));
+
+ ASSERT_FALSE(elf.Step(0, nullptr, nullptr));
+}
+
+TEST_F(ElfTest, elf_arm) {
+ Elf elf(memory_);
+
+ InitElf32(EM_ARM);
+
+ ASSERT_TRUE(elf.Init());
+ ASSERT_TRUE(elf.valid());
+ ASSERT_EQ(static_cast<uint32_t>(EM_ARM), elf.machine_type());
+ ASSERT_EQ(ELFCLASS32, elf.class_type());
+ ASSERT_TRUE(elf.interface() != nullptr);
+}
+
+TEST_F(ElfTest, elf_x86) {
+ Elf elf(memory_);
+
+ InitElf32(EM_386);
+
+ ASSERT_TRUE(elf.Init());
+ ASSERT_TRUE(elf.valid());
+ ASSERT_EQ(static_cast<uint32_t>(EM_386), elf.machine_type());
+ ASSERT_EQ(ELFCLASS32, elf.class_type());
+ ASSERT_TRUE(elf.interface() != nullptr);
+}
+
+TEST_F(ElfTest, elf_arm64) {
+ Elf elf(memory_);
+
+ InitElf64(EM_AARCH64);
+
+ ASSERT_TRUE(elf.Init());
+ ASSERT_TRUE(elf.valid());
+ ASSERT_EQ(static_cast<uint32_t>(EM_AARCH64), elf.machine_type());
+ ASSERT_EQ(ELFCLASS64, elf.class_type());
+ ASSERT_TRUE(elf.interface() != nullptr);
+}
+
+TEST_F(ElfTest, elf_x86_64) {
+ Elf elf(memory_);
+
+ InitElf64(EM_X86_64);
+
+ ASSERT_TRUE(elf.Init());
+ ASSERT_TRUE(elf.valid());
+ ASSERT_EQ(static_cast<uint32_t>(EM_X86_64), elf.machine_type());
+ ASSERT_EQ(ELFCLASS64, elf.class_type());
+ ASSERT_TRUE(elf.interface() != nullptr);
+}
diff --git a/libunwindstack/tests/MapsTest.cpp b/libunwindstack/tests/MapsTest.cpp
deleted file mode 100644
index 216873f..0000000
--- a/libunwindstack/tests/MapsTest.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2016 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 <sys/mman.h>
-
-#include <android-base/file.h>
-#include <android-base/test_utils.h>
-#include <gtest/gtest.h>
-
-#include "Maps.h"
-
-#include "LogFake.h"
-
-class MapsTest : public ::testing::Test {
- protected:
- void SetUp() override {
- ResetLogs();
- }
-};
-
-TEST_F(MapsTest, parse_permissions) {
- MapsBuffer maps("1000-2000 ---- 00000000 00:00 0\n"
- "2000-3000 r--- 00000000 00:00 0\n"
- "3000-4000 -w-- 00000000 00:00 0\n"
- "4000-5000 --x- 00000000 00:00 0\n"
- "5000-6000 rwx- 00000000 00:00 0\n");
-
- ASSERT_TRUE(maps.Parse());
- ASSERT_EQ(5U, maps.Total());
- auto it = maps.begin();
- ASSERT_EQ(PROT_NONE, it->flags);
- ASSERT_EQ(0x1000U, it->start);
- ASSERT_EQ(0x2000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ("", it->name);
- ++it;
- ASSERT_EQ(PROT_READ, it->flags);
- ASSERT_EQ(0x2000U, it->start);
- ASSERT_EQ(0x3000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ("", it->name);
- ++it;
- ASSERT_EQ(PROT_WRITE, it->flags);
- ASSERT_EQ(0x3000U, it->start);
- ASSERT_EQ(0x4000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ("", it->name);
- ++it;
- ASSERT_EQ(PROT_EXEC, it->flags);
- ASSERT_EQ(0x4000U, it->start);
- ASSERT_EQ(0x5000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ("", it->name);
- ++it;
- ASSERT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, it->flags);
- ASSERT_EQ(0x5000U, it->start);
- ASSERT_EQ(0x6000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ("", it->name);
- ++it;
- ASSERT_EQ(it, maps.end());
-}
-
-TEST_F(MapsTest, parse_name) {
- MapsBuffer maps("720b29b000-720b29e000 rw-p 00000000 00:00 0\n"
- "720b29e000-720b29f000 rw-p 00000000 00:00 0 /system/lib/fake.so\n"
- "720b29f000-720b2a0000 rw-p 00000000 00:00 0");
-
- ASSERT_TRUE(maps.Parse());
- ASSERT_EQ(3U, maps.Total());
- auto it = maps.begin();
- ASSERT_EQ("", it->name);
- ASSERT_EQ(0x720b29b000U, it->start);
- ASSERT_EQ(0x720b29e000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
- ++it;
- ASSERT_EQ("/system/lib/fake.so", it->name);
- ASSERT_EQ(0x720b29e000U, it->start);
- ASSERT_EQ(0x720b29f000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
- ++it;
- ASSERT_EQ("", it->name);
- ASSERT_EQ(0x720b29f000U, it->start);
- ASSERT_EQ(0x720b2a0000U, it->end);
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
- ++it;
- ASSERT_EQ(it, maps.end());
-}
-
-TEST_F(MapsTest, parse_offset) {
- MapsBuffer maps("a000-e000 rw-p 00000000 00:00 0 /system/lib/fake.so\n"
- "e000-f000 rw-p 00a12345 00:00 0 /system/lib/fake.so\n");
-
- ASSERT_TRUE(maps.Parse());
- ASSERT_EQ(2U, maps.Total());
- auto it = maps.begin();
- ASSERT_EQ(0U, it->offset);
- ASSERT_EQ(0xa000U, it->start);
- ASSERT_EQ(0xe000U, it->end);
- ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
- ASSERT_EQ("/system/lib/fake.so", it->name);
- ++it;
- ASSERT_EQ(0xa12345U, it->offset);
- ASSERT_EQ(0xe000U, it->start);
- ASSERT_EQ(0xf000U, it->end);
- ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
- ASSERT_EQ("/system/lib/fake.so", it->name);
- ++it;
- ASSERT_EQ(maps.end(), it);
-}
-
-TEST_F(MapsTest, file_smoke) {
- TemporaryFile tf;
- ASSERT_TRUE(tf.fd != -1);
-
- ASSERT_TRUE(android::base::WriteStringToFile(
- "720b29b000-720b29e000 r-xp a0000000 00:00 0 /fake.so\n"
- "720b2b0000-720b2e0000 r-xp b0000000 00:00 0 /fake2.so\n"
- "720b2e0000-720b2f0000 r-xp c0000000 00:00 0 /fake3.so\n",
- tf.path, 0660, getuid(), getgid()));
-
- MapsFile maps(tf.path);
-
- ASSERT_TRUE(maps.Parse());
- ASSERT_EQ(3U, maps.Total());
- auto it = maps.begin();
- ASSERT_EQ(0x720b29b000U, it->start);
- ASSERT_EQ(0x720b29e000U, it->end);
- ASSERT_EQ(0xa0000000U, it->offset);
- ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
- ASSERT_EQ("/fake.so", it->name);
- ++it;
- ASSERT_EQ(0x720b2b0000U, it->start);
- ASSERT_EQ(0x720b2e0000U, it->end);
- ASSERT_EQ(0xb0000000U, it->offset);
- ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
- ASSERT_EQ("/fake2.so", it->name);
- ++it;
- ASSERT_EQ(0x720b2e0000U, it->start);
- ASSERT_EQ(0x720b2f0000U, it->end);
- ASSERT_EQ(0xc0000000U, it->offset);
- ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
- ASSERT_EQ("/fake3.so", it->name);
- ++it;
- ASSERT_EQ(it, maps.end());
-}
-
-TEST_F(MapsTest, find) {
- MapsBuffer maps("1000-2000 r--p 00000010 00:00 0 /system/lib/fake1.so\n"
- "3000-4000 -w-p 00000020 00:00 0 /system/lib/fake2.so\n"
- "6000-8000 --xp 00000030 00:00 0 /system/lib/fake3.so\n"
- "a000-b000 rw-p 00000040 00:00 0 /system/lib/fake4.so\n"
- "e000-f000 rwxp 00000050 00:00 0 /system/lib/fake5.so\n");
- ASSERT_TRUE(maps.Parse());
- ASSERT_EQ(5U, maps.Total());
-
- ASSERT_TRUE(maps.Find(0x500) == nullptr);
- ASSERT_TRUE(maps.Find(0x2000) == nullptr);
- ASSERT_TRUE(maps.Find(0x5010) == nullptr);
- ASSERT_TRUE(maps.Find(0x9a00) == nullptr);
- ASSERT_TRUE(maps.Find(0xf000) == nullptr);
- ASSERT_TRUE(maps.Find(0xf010) == nullptr);
-
- MapInfo* info = maps.Find(0x1000);
- ASSERT_TRUE(info != nullptr);
- ASSERT_EQ(0x1000U, info->start);
- ASSERT_EQ(0x2000U, info->end);
- ASSERT_EQ(0x10U, info->offset);
- ASSERT_EQ(PROT_READ, info->flags);
- ASSERT_EQ("/system/lib/fake1.so", info->name);
-
- info = maps.Find(0x3020);
- ASSERT_TRUE(info != nullptr);
- ASSERT_EQ(0x3000U, info->start);
- ASSERT_EQ(0x4000U, info->end);
- ASSERT_EQ(0x20U, info->offset);
- ASSERT_EQ(PROT_WRITE, info->flags);
- ASSERT_EQ("/system/lib/fake2.so", info->name);
-
- info = maps.Find(0x6020);
- ASSERT_TRUE(info != nullptr);
- ASSERT_EQ(0x6000U, info->start);
- ASSERT_EQ(0x8000U, info->end);
- ASSERT_EQ(0x30U, info->offset);
- ASSERT_EQ(PROT_EXEC, info->flags);
- ASSERT_EQ("/system/lib/fake3.so", info->name);
-
- info = maps.Find(0xafff);
- ASSERT_TRUE(info != nullptr);
- ASSERT_EQ(0xa000U, info->start);
- ASSERT_EQ(0xb000U, info->end);
- ASSERT_EQ(0x40U, info->offset);
- ASSERT_EQ(PROT_READ | PROT_WRITE, info->flags);
- ASSERT_EQ("/system/lib/fake4.so", info->name);
-
- info = maps.Find(0xe500);
- ASSERT_TRUE(info != nullptr);
- ASSERT_EQ(0xe000U, info->start);
- ASSERT_EQ(0xf000U, info->end);
- ASSERT_EQ(0x50U, info->offset);
- ASSERT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, info->flags);
- ASSERT_EQ("/system/lib/fake5.so", info->name);
-}
diff --git a/libunwindstack/tests/MemoryFake.h b/libunwindstack/tests/MemoryFake.h
index 4f898fa..e05736b 100644
--- a/libunwindstack/tests/MemoryFake.h
+++ b/libunwindstack/tests/MemoryFake.h
@@ -34,7 +34,19 @@
void SetMemory(uint64_t addr, const void* memory, size_t length);
- void SetData(uint64_t addr, uint32_t value) {
+ void SetData8(uint64_t addr, uint8_t value) {
+ SetMemory(addr, &value, sizeof(value));
+ }
+
+ void SetData16(uint64_t addr, uint16_t value) {
+ SetMemory(addr, &value, sizeof(value));
+ }
+
+ void SetData32(uint64_t addr, uint32_t value) {
+ SetMemory(addr, &value, sizeof(value));
+ }
+
+ void SetData64(uint64_t addr, uint64_t value) {
SetMemory(addr, &value, sizeof(value));
}
diff --git a/libunwindstack/tests/MemoryFileTest.cpp b/libunwindstack/tests/MemoryFileTest.cpp
index ebc6118..870ca19 100644
--- a/libunwindstack/tests/MemoryFileTest.cpp
+++ b/libunwindstack/tests/MemoryFileTest.cpp
@@ -20,12 +20,9 @@
#include "Memory.h"
-#include "LogFake.h"
-
class MemoryFileTest : public ::testing::Test {
protected:
void SetUp() override {
- ResetLogs();
tf_ = new TemporaryFile;
}
@@ -86,6 +83,7 @@
data += static_cast<char>((i % 10) + '0');
}
ASSERT_TRUE(android::base::WriteStringToFd(data, tf_->fd));
+
ASSERT_TRUE(memory_.Init(tf_->path, 2 * pagesize));
std::vector<char> buffer(11);
ASSERT_TRUE(memory_.Read(0, buffer.data(), 10));
@@ -106,6 +104,7 @@
data += static_cast<char>((i % 10) + '0');
}
ASSERT_TRUE(android::base::WriteStringToFd(data, tf_->fd));
+
ASSERT_TRUE(memory_.Init(tf_->path, 2 * pagesize + 10));
std::vector<char> buffer(11);
ASSERT_TRUE(memory_.Read(0, buffer.data(), 10));
@@ -165,3 +164,111 @@
// This should fail because there is no terminating \0
ASSERT_FALSE(memory_.ReadString(0, &name));
}
+
+TEST_F(MemoryFileTest, read_past_file_within_mapping) {
+ size_t pagesize = getpagesize();
+
+ ASSERT_TRUE(pagesize > 100);
+ std::vector<uint8_t> buffer(pagesize - 100);
+ for (size_t i = 0; i < pagesize - 100; i++) {
+ buffer[i] = static_cast<uint8_t>((i % 0x5e) + 0x20);
+ }
+ ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+ ASSERT_TRUE(memory_.Init(tf_->path, 0));
+
+ for (size_t i = 0; i < 100; i++) {
+ uint8_t value;
+ ASSERT_FALSE(memory_.Read(buffer.size() + i, &value, 1)) << "Should have failed at value " << i;
+ }
+}
+
+TEST_F(MemoryFileTest, map_partial_offset_aligned) {
+ size_t pagesize = getpagesize();
+ std::vector<uint8_t> buffer(pagesize * 10);
+ for (size_t i = 0; i < pagesize * 10; i++) {
+ buffer[i] = i / pagesize + 1;
+ }
+ ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+ // Map in only two pages of the data, and after the first page.
+ ASSERT_TRUE(memory_.Init(tf_->path, pagesize, pagesize * 2));
+
+ std::vector<uint8_t> read_buffer(pagesize * 2);
+ // Make sure that reading after mapped data is a failure.
+ ASSERT_FALSE(memory_.Read(pagesize * 2, read_buffer.data(), 1));
+ ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize * 2));
+ for (size_t i = 0; i < pagesize; i++) {
+ ASSERT_EQ(2, read_buffer[i]) << "Failed at byte " << i;
+ }
+ for (size_t i = pagesize; i < pagesize * 2; i++) {
+ ASSERT_EQ(3, read_buffer[i]) << "Failed at byte " << i;
+ }
+}
+
+TEST_F(MemoryFileTest, map_partial_offset_unaligned) {
+ size_t pagesize = getpagesize();
+ ASSERT_TRUE(pagesize > 0x100);
+ std::vector<uint8_t> buffer(pagesize * 10);
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = i / pagesize + 1;
+ }
+ ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+ // Map in only two pages of the data, and after the first page.
+ ASSERT_TRUE(memory_.Init(tf_->path, pagesize + 0x100, pagesize * 2));
+
+ std::vector<uint8_t> read_buffer(pagesize * 2);
+ // Make sure that reading after mapped data is a failure.
+ ASSERT_FALSE(memory_.Read(pagesize * 2, read_buffer.data(), 1));
+ ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize * 2));
+ for (size_t i = 0; i < pagesize - 0x100; i++) {
+ ASSERT_EQ(2, read_buffer[i]) << "Failed at byte " << i;
+ }
+ for (size_t i = pagesize - 0x100; i < 2 * pagesize - 0x100; i++) {
+ ASSERT_EQ(3, read_buffer[i]) << "Failed at byte " << i;
+ }
+ for (size_t i = 2 * pagesize - 0x100; i < pagesize * 2; i++) {
+ ASSERT_EQ(4, read_buffer[i]) << "Failed at byte " << i;
+ }
+}
+
+TEST_F(MemoryFileTest, map_overflow) {
+ size_t pagesize = getpagesize();
+ ASSERT_TRUE(pagesize > 0x100);
+ std::vector<uint8_t> buffer(pagesize * 10);
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = i / pagesize + 1;
+ }
+ ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+ // Map in only two pages of the data, and after the first page.
+ ASSERT_TRUE(memory_.Init(tf_->path, pagesize + 0x100, UINT64_MAX));
+
+ std::vector<uint8_t> read_buffer(pagesize * 10);
+ ASSERT_FALSE(memory_.Read(pagesize * 9 - 0x100 + 1, read_buffer.data(), 1));
+ ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize * 9 - 0x100));
+}
+
+TEST_F(MemoryFileTest, init_reinit) {
+ size_t pagesize = getpagesize();
+ std::vector<uint8_t> buffer(pagesize * 2);
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = i / pagesize + 1;
+ }
+ ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
+
+ ASSERT_TRUE(memory_.Init(tf_->path, 0));
+ std::vector<uint8_t> read_buffer(buffer.size());
+ ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize));
+ for (size_t i = 0; i < pagesize; i++) {
+ ASSERT_EQ(1, read_buffer[i]) << "Failed at byte " << i;
+ }
+
+ // Now reinit.
+ ASSERT_TRUE(memory_.Init(tf_->path, pagesize));
+ ASSERT_TRUE(memory_.Read(0, read_buffer.data(), pagesize));
+ for (size_t i = 0; i < pagesize; i++) {
+ ASSERT_EQ(2, read_buffer[i]) << "Failed at byte " << i;
+ }
+}
diff --git a/libunwindstack/tests/MemoryLocalTest.cpp b/libunwindstack/tests/MemoryLocalTest.cpp
index 49ece9d..0ba5f1c 100644
--- a/libunwindstack/tests/MemoryLocalTest.cpp
+++ b/libunwindstack/tests/MemoryLocalTest.cpp
@@ -23,16 +23,7 @@
#include "Memory.h"
-#include "LogFake.h"
-
-class MemoryLocalTest : public ::testing::Test {
- protected:
- void SetUp() override {
- ResetLogs();
- }
-};
-
-TEST_F(MemoryLocalTest, read) {
+TEST(MemoryLocalTest, read) {
std::vector<uint8_t> src(1024);
memset(src.data(), 0x4c, 1024);
@@ -56,7 +47,7 @@
}
}
-TEST_F(MemoryLocalTest, read_string) {
+TEST(MemoryLocalTest, read_string) {
std::string name("string_in_memory");
MemoryLocal local;
@@ -75,7 +66,7 @@
ASSERT_FALSE(local.ReadString(reinterpret_cast<uint64_t>(&name[7]), &dst_name, 9));
}
-TEST_F(MemoryLocalTest, read_illegal) {
+TEST(MemoryLocalTest, read_illegal) {
MemoryLocal local;
std::vector<uint8_t> dst(100);
diff --git a/libunwindstack/tests/MemoryRangeTest.cpp b/libunwindstack/tests/MemoryRangeTest.cpp
index fcae3a4..d636ec4 100644
--- a/libunwindstack/tests/MemoryRangeTest.cpp
+++ b/libunwindstack/tests/MemoryRangeTest.cpp
@@ -23,13 +23,11 @@
#include "Memory.h"
-#include "LogFake.h"
#include "MemoryFake.h"
class MemoryRangeTest : public ::testing::Test {
protected:
void SetUp() override {
- ResetLogs();
memory_ = new MemoryFake;
}
diff --git a/libunwindstack/tests/MemoryRemoteTest.cpp b/libunwindstack/tests/MemoryRemoteTest.cpp
index 49244a5..7664c3e 100644
--- a/libunwindstack/tests/MemoryRemoteTest.cpp
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -33,14 +33,8 @@
#include "Memory.h"
-#include "LogFake.h"
-
class MemoryRemoteTest : public ::testing::Test {
protected:
- void SetUp() override {
- ResetLogs();
- }
-
static uint64_t NanoTime() {
struct timespec t = { 0, 0 };
clock_gettime(CLOCK_MONOTONIC, &t);
diff --git a/libunwindstack/tests/RegsTest.cpp b/libunwindstack/tests/RegsTest.cpp
index f9e8b0e..0dac278 100644
--- a/libunwindstack/tests/RegsTest.cpp
+++ b/libunwindstack/tests/RegsTest.cpp
@@ -18,50 +18,249 @@
#include <gtest/gtest.h>
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "MapInfo.h"
#include "Regs.h"
-class RegsTest : public ::testing::Test {};
+#include "MemoryFake.h"
-TEST_F(RegsTest, regs32) {
- Regs32 regs32(10, 20, 30);
+class ElfFake : public Elf {
+ public:
+ ElfFake(Memory* memory) : Elf(memory) { valid_ = true; }
+ virtual ~ElfFake() = default;
- ASSERT_EQ(10U, regs32.pc_reg());
- ASSERT_EQ(20U, regs32.sp_reg());
- ASSERT_EQ(30U, regs32.total_regs());
+ void set_elf_interface(ElfInterface* interface) { interface_.reset(interface); }
+};
- uint32_t* raw = reinterpret_cast<uint32_t*>(regs32.raw_data());
- for (size_t i = 0; i < 30; i++) {
- raw[i] = 0xf0000000 + i;
+class ElfInterfaceFake : public ElfInterface {
+ public:
+ ElfInterfaceFake(Memory* memory) : ElfInterface(memory) {}
+ virtual ~ElfInterfaceFake() = default;
+
+ void set_load_bias(uint64_t load_bias) { load_bias_ = load_bias; }
+
+ bool Init() override { return false; }
+ 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; }
+};
+
+template <typename TypeParam>
+class RegsTestTmpl : public RegsTmpl<TypeParam> {
+ public:
+ RegsTestTmpl(uint16_t total_regs, uint16_t regs_sp)
+ : RegsTmpl<TypeParam>(total_regs, regs_sp, Regs::Location(Regs::LOCATION_UNKNOWN, 0)) {}
+ RegsTestTmpl(uint16_t total_regs, uint16_t regs_sp, Regs::Location return_loc)
+ : RegsTmpl<TypeParam>(total_regs, regs_sp, return_loc) {}
+ virtual ~RegsTestTmpl() = default;
+
+ uint64_t GetAdjustedPc(uint64_t, Elf*) { return 0; }
+};
+
+class RegsTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ memory_ = new MemoryFake;
+ elf_.reset(new ElfFake(memory_));
+ elf_interface_ = new ElfInterfaceFake(elf_->memory());
+ elf_->set_elf_interface(elf_interface_);
}
- ASSERT_EQ(0xf000000aU, regs32.pc());
- ASSERT_EQ(0xf0000014U, regs32.sp());
+ template <typename AddressType>
+ void regs_rel_pc();
- ASSERT_EQ(0xf0000001U, regs32[1]);
- regs32[1] = 10;
- ASSERT_EQ(10U, regs32[1]);
+ template <typename AddressType>
+ void regs_return_address_register();
- ASSERT_EQ(0xf000001dU, regs32[29]);
+ ElfInterfaceFake* elf_interface_;
+ MemoryFake* memory_;
+ std::unique_ptr<ElfFake> elf_;
+};
+
+TEST_F(RegsTest, regs32) {
+ RegsTestTmpl<uint32_t> regs32(50, 10);
+ ASSERT_EQ(50U, regs32.total_regs());
+ ASSERT_EQ(10U, regs32.sp_reg());
+
+ uint32_t* raw = reinterpret_cast<uint32_t*>(regs32.RawData());
+ for (size_t i = 0; i < 50; i++) {
+ raw[i] = 0xf0000000 + i;
+ }
+ regs32.set_pc(0xf0120340);
+ regs32.set_sp(0xa0ab0cd0);
+
+ for (size_t i = 0; i < 50; i++) {
+ ASSERT_EQ(0xf0000000U + i, regs32[i]) << "Failed comparing register " << i;
+ }
+
+ ASSERT_EQ(0xf0120340U, regs32.pc());
+ ASSERT_EQ(0xa0ab0cd0U, regs32.sp());
+
+ regs32[32] = 10;
+ ASSERT_EQ(10U, regs32[32]);
}
TEST_F(RegsTest, regs64) {
- Regs64 regs64(10, 20, 30);
-
- ASSERT_EQ(10U, regs64.pc_reg());
- ASSERT_EQ(20U, regs64.sp_reg());
+ RegsTestTmpl<uint64_t> regs64(30, 12);
ASSERT_EQ(30U, regs64.total_regs());
+ ASSERT_EQ(12U, regs64.sp_reg());
- uint64_t* raw = reinterpret_cast<uint64_t*>(regs64.raw_data());
+ uint64_t* raw = reinterpret_cast<uint64_t*>(regs64.RawData());
for (size_t i = 0; i < 30; i++) {
raw[i] = 0xf123456780000000UL + i;
}
+ regs64.set_pc(0xf123456780102030UL);
+ regs64.set_sp(0xa123456780a0b0c0UL);
- ASSERT_EQ(0xf12345678000000aUL, regs64.pc());
- ASSERT_EQ(0xf123456780000014UL, regs64.sp());
+ for (size_t i = 0; i < 30; i++) {
+ ASSERT_EQ(0xf123456780000000U + i, regs64[i]) << "Failed reading register " << i;
+ }
- ASSERT_EQ(0xf123456780000008U, regs64[8]);
+ ASSERT_EQ(0xf123456780102030UL, regs64.pc());
+ ASSERT_EQ(0xa123456780a0b0c0UL, regs64.sp());
+
regs64[8] = 10;
ASSERT_EQ(10U, regs64[8]);
+}
- ASSERT_EQ(0xf12345678000001dU, regs64[29]);
+template <typename AddressType>
+void RegsTest::regs_rel_pc() {
+ RegsTestTmpl<AddressType> regs(30, 12);
+
+ elf_interface_->set_load_bias(0);
+ MapInfo map_info{.start = 0x1000, .end = 0x2000};
+ regs.set_pc(0x1101);
+ ASSERT_EQ(0x101U, regs.GetRelPc(elf_.get(), &map_info));
+ elf_interface_->set_load_bias(0x3000);
+ ASSERT_EQ(0x3101U, regs.GetRelPc(elf_.get(), &map_info));
+}
+
+TEST_F(RegsTest, regs32_rel_pc) {
+ regs_rel_pc<uint32_t>();
+}
+
+TEST_F(RegsTest, regs64_rel_pc) {
+ regs_rel_pc<uint64_t>();
+}
+
+template <typename AddressType>
+void RegsTest::regs_return_address_register() {
+ RegsTestTmpl<AddressType> regs(20, 10, Regs::Location(Regs::LOCATION_REGISTER, 5));
+
+ regs[5] = 0x12345;
+ uint64_t value;
+ ASSERT_TRUE(regs.GetReturnAddressFromDefault(memory_, &value));
+ ASSERT_EQ(0x12345U, value);
+}
+
+TEST_F(RegsTest, regs32_return_address_register) {
+ regs_return_address_register<uint32_t>();
+}
+
+TEST_F(RegsTest, regs64_return_address_register) {
+ regs_return_address_register<uint64_t>();
+}
+
+TEST_F(RegsTest, regs32_return_address_sp_offset) {
+ RegsTestTmpl<uint32_t> regs(20, 10, Regs::Location(Regs::LOCATION_SP_OFFSET, -2));
+
+ regs.set_sp(0x2002);
+ memory_->SetData32(0x2000, 0x12345678);
+ uint64_t value;
+ ASSERT_TRUE(regs.GetReturnAddressFromDefault(memory_, &value));
+ ASSERT_EQ(0x12345678U, value);
+}
+
+TEST_F(RegsTest, regs64_return_address_sp_offset) {
+ RegsTestTmpl<uint64_t> regs(20, 10, Regs::Location(Regs::LOCATION_SP_OFFSET, -8));
+
+ regs.set_sp(0x2008);
+ memory_->SetData64(0x2000, 0x12345678aabbccddULL);
+ uint64_t value;
+ ASSERT_TRUE(regs.GetReturnAddressFromDefault(memory_, &value));
+ ASSERT_EQ(0x12345678aabbccddULL, value);
+}
+
+TEST_F(RegsTest, rel_pc) {
+ RegsArm64 arm64;
+ ASSERT_EQ(0xcU, arm64.GetAdjustedPc(0x10, elf_.get()));
+ ASSERT_EQ(0x0U, arm64.GetAdjustedPc(0x4, elf_.get()));
+ ASSERT_EQ(0x3U, arm64.GetAdjustedPc(0x3, elf_.get()));
+ ASSERT_EQ(0x2U, arm64.GetAdjustedPc(0x2, elf_.get()));
+ ASSERT_EQ(0x1U, arm64.GetAdjustedPc(0x1, elf_.get()));
+ ASSERT_EQ(0x0U, arm64.GetAdjustedPc(0x0, elf_.get()));
+
+ RegsX86 x86;
+ ASSERT_EQ(0xffU, x86.GetAdjustedPc(0x100, elf_.get()));
+ ASSERT_EQ(0x1U, x86.GetAdjustedPc(0x2, elf_.get()));
+ ASSERT_EQ(0x0U, x86.GetAdjustedPc(0x1, elf_.get()));
+ ASSERT_EQ(0x0U, x86.GetAdjustedPc(0x0, elf_.get()));
+
+ RegsX86_64 x86_64;
+ ASSERT_EQ(0xffU, x86_64.GetAdjustedPc(0x100, elf_.get()));
+ ASSERT_EQ(0x1U, x86_64.GetAdjustedPc(0x2, elf_.get()));
+ ASSERT_EQ(0x0U, x86_64.GetAdjustedPc(0x1, elf_.get()));
+ ASSERT_EQ(0x0U, x86_64.GetAdjustedPc(0x0, elf_.get()));
+}
+
+TEST_F(RegsTest, rel_pc_arm) {
+ RegsArm arm;
+
+ // Check fence posts.
+ elf_interface_->set_load_bias(0);
+ ASSERT_EQ(3U, arm.GetAdjustedPc(0x5, elf_.get()));
+ ASSERT_EQ(4U, arm.GetAdjustedPc(0x4, elf_.get()));
+ ASSERT_EQ(3U, arm.GetAdjustedPc(0x3, elf_.get()));
+ ASSERT_EQ(2U, arm.GetAdjustedPc(0x2, elf_.get()));
+ ASSERT_EQ(1U, arm.GetAdjustedPc(0x1, elf_.get()));
+ ASSERT_EQ(0U, arm.GetAdjustedPc(0x0, elf_.get()));
+
+ elf_interface_->set_load_bias(0x100);
+ ASSERT_EQ(0xffU, arm.GetAdjustedPc(0xff, elf_.get()));
+ ASSERT_EQ(0x103U, arm.GetAdjustedPc(0x105, elf_.get()));
+ ASSERT_EQ(0x104U, arm.GetAdjustedPc(0x104, elf_.get()));
+ ASSERT_EQ(0x103U, arm.GetAdjustedPc(0x103, elf_.get()));
+ ASSERT_EQ(0x102U, arm.GetAdjustedPc(0x102, elf_.get()));
+ ASSERT_EQ(0x101U, arm.GetAdjustedPc(0x101, elf_.get()));
+ ASSERT_EQ(0x100U, arm.GetAdjustedPc(0x100, elf_.get()));
+
+ // Check thumb instructions handling.
+ elf_interface_->set_load_bias(0);
+ memory_->SetData32(0x2000, 0);
+ ASSERT_EQ(0x2003U, arm.GetAdjustedPc(0x2005, elf_.get()));
+ memory_->SetData32(0x2000, 0xe000f000);
+ ASSERT_EQ(0x2001U, arm.GetAdjustedPc(0x2005, elf_.get()));
+
+ elf_interface_->set_load_bias(0x400);
+ memory_->SetData32(0x2100, 0);
+ ASSERT_EQ(0x2503U, arm.GetAdjustedPc(0x2505, elf_.get()));
+ memory_->SetData32(0x2100, 0xf111f111);
+ ASSERT_EQ(0x2501U, arm.GetAdjustedPc(0x2505, elf_.get()));
+}
+
+TEST_F(RegsTest, elf_invalid) {
+ Elf invalid_elf(new MemoryFake);
+ RegsArm regs_arm;
+ RegsArm64 regs_arm64;
+ RegsX86 regs_x86;
+ RegsX86_64 regs_x86_64;
+ MapInfo map_info{.start = 0x1000, .end = 0x2000};
+
+ regs_arm.set_pc(0x1500);
+ ASSERT_EQ(0x500U, regs_arm.GetRelPc(&invalid_elf, &map_info));
+ ASSERT_EQ(0x500U, regs_arm.GetAdjustedPc(0x500U, &invalid_elf));
+
+ regs_arm64.set_pc(0x1600);
+ ASSERT_EQ(0x600U, regs_arm64.GetRelPc(&invalid_elf, &map_info));
+ ASSERT_EQ(0x600U, regs_arm64.GetAdjustedPc(0x600U, &invalid_elf));
+
+ regs_x86.set_pc(0x1700);
+ ASSERT_EQ(0x700U, regs_x86.GetRelPc(&invalid_elf, &map_info));
+ ASSERT_EQ(0x700U, regs_x86.GetAdjustedPc(0x700U, &invalid_elf));
+
+ regs_x86_64.set_pc(0x1800);
+ ASSERT_EQ(0x800U, regs_x86_64.GetRelPc(&invalid_elf, &map_info));
+ ASSERT_EQ(0x800U, regs_x86_64.GetAdjustedPc(0x800U, &invalid_elf));
}
diff --git a/libunwindstack/unwind_info.cpp b/libunwindstack/unwind_info.cpp
new file mode 100644
index 0000000..6f158b0
--- /dev/null
+++ b/libunwindstack/unwind_info.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2016 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 <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "ArmExidx.h"
+#include "Elf.h"
+#include "ElfInterface.h"
+#include "ElfInterfaceArm.h"
+#include "Log.h"
+
+void DumpArm(ElfInterfaceArm* interface) {
+ if (interface == nullptr) {
+ printf("No ARM Unwind Information.\n\n");
+ return;
+ }
+
+ printf("ARM Unwind Information:\n");
+ for (const auto& entry : interface->pt_loads()) {
+ uint64_t load_bias = entry.second.table_offset;
+ printf(" PC Range 0x%" PRIx64 " - 0x%" PRIx64 "\n", entry.second.offset + load_bias,
+ entry.second.table_size + load_bias);
+ for (auto addr : *interface) {
+ std::string name;
+ printf(" PC 0x%" PRIx64, addr + load_bias);
+ uint64_t func_offset;
+ if (interface->GetFunctionName(addr + load_bias + 1, &name, &func_offset) && !name.empty()) {
+ printf(" <%s>", name.c_str());
+ }
+ printf("\n");
+ uint64_t entry;
+ if (!interface->FindEntry(addr + load_bias, &entry)) {
+ printf(" Cannot find entry for address.\n");
+ continue;
+ }
+ ArmExidx arm(nullptr, interface->memory(), nullptr);
+ arm.set_log(true);
+ arm.set_log_skip_execution(true);
+ arm.set_log_indent(2);
+ if (!arm.ExtractEntryData(entry)) {
+ if (arm.status() != ARM_STATUS_NO_UNWIND) {
+ printf(" Error trying to extract data.\n");
+ }
+ continue;
+ }
+ if (arm.data()->size() > 0) {
+ if (!arm.Eval() && arm.status() != ARM_STATUS_NO_UNWIND) {
+ printf(" Error trying to evaluate dwarf data.\n");
+ }
+ }
+ }
+ }
+ printf("\n");
+}
+
+int main(int argc, char** argv) {
+ if (argc != 2) {
+ printf("Need to pass the name of an elf file to the program.\n");
+ return 1;
+ }
+
+ struct stat st;
+ if (stat(argv[1], &st) == -1) {
+ printf("Cannot stat %s: %s\n", argv[1], strerror(errno));
+ return 1;
+ }
+ if (!S_ISREG(st.st_mode)) {
+ printf("%s is not a regular file.\n", argv[1]);
+ return 1;
+ }
+ if (S_ISDIR(st.st_mode)) {
+ printf("%s is a directory.\n", argv[1]);
+ return 1;
+ }
+
+ // Send all log messages to stdout.
+ log_to_stdout(true);
+
+ MemoryFileAtOffset* memory = new MemoryFileAtOffset;
+ if (!memory->Init(argv[1], 0)) {
+ // Initializatation failed.
+ printf("Failed to init\n");
+ return 1;
+ }
+
+ Elf elf(memory);
+ if (!elf.Init() || !elf.valid()) {
+ printf("%s is not a valid elf file.\n", argv[1]);
+ return 1;
+ }
+
+ ElfInterface* interface = elf.interface();
+ if (elf.machine_type() == EM_ARM) {
+ DumpArm(reinterpret_cast<ElfInterfaceArm*>(interface));
+ printf("\n");
+ }
+
+ return 0;
+}
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 2a392b9..9c300e0 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -17,9 +17,12 @@
host_supported: true,
export_include_dirs: ["include"],
target: {
+ linux_bionic: {
+ enabled: true,
+ },
windows: {
- enabled: true,
- },
+ enabled: true,
+ },
},
}
@@ -31,7 +34,6 @@
"CallStack.cpp",
"FileMap.cpp",
"JenkinsHash.cpp",
- "LinearTransform.cpp",
"Log.cpp",
"NativeHandle.cpp",
"Printer.cpp",
@@ -42,6 +44,7 @@
"StopWatch.cpp",
"String8.cpp",
"String16.cpp",
+ "StrongPointer.cpp",
"SystemClock.cpp",
"Threads.cpp",
"Timers.cpp",
diff --git a/libutils/LinearTransform.cpp b/libutils/LinearTransform.cpp
deleted file mode 100644
index d2e91a8..0000000
--- a/libutils/LinearTransform.cpp
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * Copyright (C) 2011 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.
- */
-
-#define __STDC_LIMIT_MACROS
-
-#include <utils/LinearTransform.h>
-#include <assert.h>
-
-
-// disable sanitize as these functions may intentionally overflow (see comments below).
-// the ifdef can be removed when host builds use clang.
-#if defined(__clang__)
-#define ATTRIBUTE_NO_SANITIZE_INTEGER __attribute__((no_sanitize("integer")))
-#else
-#define ATTRIBUTE_NO_SANITIZE_INTEGER
-#endif
-
-namespace android {
-
-// sanitize failure with T = int32_t and x = 0x80000000
-template<class T>
-ATTRIBUTE_NO_SANITIZE_INTEGER
-static inline T ABS(T x) { return (x < 0) ? -x : x; }
-
-// Static math methods involving linear transformations
-// remote sanitize failure on overflow case.
-ATTRIBUTE_NO_SANITIZE_INTEGER
-static bool scale_u64_to_u64(
- uint64_t val,
- uint32_t N,
- uint32_t D,
- uint64_t* res,
- bool round_up_not_down) {
- uint64_t tmp1, tmp2;
- uint32_t r;
-
- assert(res);
- assert(D);
-
- // Let U32(X) denote a uint32_t containing the upper 32 bits of a 64 bit
- // integer X.
- // Let L32(X) denote a uint32_t containing the lower 32 bits of a 64 bit
- // integer X.
- // Let X[A, B] with A <= B denote bits A through B of the integer X.
- // Let (A | B) denote the concatination of two 32 bit ints, A and B.
- // IOW X = (A | B) => U32(X) == A && L32(X) == B
- //
- // compute M = val * N (a 96 bit int)
- // ---------------------------------
- // tmp2 = U32(val) * N (a 64 bit int)
- // tmp1 = L32(val) * N (a 64 bit int)
- // which means
- // M = val * N = (tmp2 << 32) + tmp1
- tmp2 = (val >> 32) * N;
- tmp1 = (val & UINT32_MAX) * N;
-
- // compute M[32, 95]
- // tmp2 = tmp2 + U32(tmp1)
- // = (U32(val) * N) + U32(L32(val) * N)
- // = M[32, 95]
- tmp2 += tmp1 >> 32;
-
- // if M[64, 95] >= D, then M/D has bits > 63 set and we have
- // an overflow.
- if ((tmp2 >> 32) >= D) {
- *res = UINT64_MAX;
- return false;
- }
-
- // Divide. Going in we know
- // tmp2 = M[32, 95]
- // U32(tmp2) < D
- r = tmp2 % D;
- tmp2 /= D;
-
- // At this point
- // tmp1 = L32(val) * N
- // tmp2 = M[32, 95] / D
- // = (M / D)[32, 95]
- // r = M[32, 95] % D
- // U32(tmp2) = 0
- //
- // compute tmp1 = (r | M[0, 31])
- tmp1 = (tmp1 & UINT32_MAX) | ((uint64_t)r << 32);
-
- // Divide again. Keep the remainder around in order to round properly.
- r = tmp1 % D;
- tmp1 /= D;
-
- // At this point
- // tmp2 = (M / D)[32, 95]
- // tmp1 = (M / D)[ 0, 31]
- // r = M % D
- // U32(tmp1) = 0
- // U32(tmp2) = 0
-
- // Pack the result and deal with the round-up case (As well as the
- // remote possiblility over overflow in such a case).
- *res = (tmp2 << 32) | tmp1;
- if (r && round_up_not_down) {
- ++(*res);
- if (!(*res)) {
- *res = UINT64_MAX;
- return false;
- }
- }
-
- return true;
-}
-
-// at least one known sanitize failure (see comment below)
-ATTRIBUTE_NO_SANITIZE_INTEGER
-static bool linear_transform_s64_to_s64(
- int64_t val,
- int64_t basis1,
- int32_t N,
- uint32_t D,
- bool invert_frac,
- int64_t basis2,
- int64_t* out) {
- uint64_t scaled, res;
- uint64_t abs_val;
- bool is_neg;
-
- if (!out)
- return false;
-
- // Compute abs(val - basis_64). Keep track of whether or not this delta
- // will be negative after the scale opertaion.
- if (val < basis1) {
- is_neg = true;
- abs_val = basis1 - val;
- } else {
- is_neg = false;
- abs_val = val - basis1;
- }
-
- if (N < 0)
- is_neg = !is_neg;
-
- if (!scale_u64_to_u64(abs_val,
- invert_frac ? D : ABS(N),
- invert_frac ? ABS(N) : D,
- &scaled,
- is_neg))
- return false; // overflow/undeflow
-
- // if scaled is >= 0x8000<etc>, then we are going to overflow or
- // underflow unless ABS(basis2) is large enough to pull us back into the
- // non-overflow/underflow region.
- if (scaled & INT64_MIN) {
- if (is_neg && (basis2 < 0))
- return false; // certain underflow
-
- if (!is_neg && (basis2 >= 0))
- return false; // certain overflow
-
- if (ABS(basis2) <= static_cast<int64_t>(scaled & INT64_MAX))
- return false; // not enough
-
- // Looks like we are OK
- *out = (is_neg ? (-scaled) : scaled) + basis2;
- } else {
- // Scaled fits within signed bounds, so we just need to check for
- // over/underflow for two signed integers. Basically, if both scaled
- // and basis2 have the same sign bit, and the result has a different
- // sign bit, then we have under/overflow. An easy way to compute this
- // is
- // (scaled_signbit XNOR basis_signbit) &&
- // (scaled_signbit XOR res_signbit)
- // ==
- // (scaled_signbit XOR basis_signbit XOR 1) &&
- // (scaled_signbit XOR res_signbit)
-
- if (is_neg)
- scaled = -scaled; // known sanitize failure
- res = scaled + basis2;
-
- if ((scaled ^ basis2 ^ INT64_MIN) & (scaled ^ res) & INT64_MIN)
- return false;
-
- *out = res;
- }
-
- return true;
-}
-
-bool LinearTransform::doForwardTransform(int64_t a_in, int64_t* b_out) const {
- if (0 == a_to_b_denom)
- return false;
-
- return linear_transform_s64_to_s64(a_in,
- a_zero,
- a_to_b_numer,
- a_to_b_denom,
- false,
- b_zero,
- b_out);
-}
-
-bool LinearTransform::doReverseTransform(int64_t b_in, int64_t* a_out) const {
- if (0 == a_to_b_numer)
- return false;
-
- return linear_transform_s64_to_s64(b_in,
- b_zero,
- a_to_b_numer,
- a_to_b_denom,
- true,
- a_zero,
- a_out);
-}
-
-template <class T> void LinearTransform::reduce(T* N, T* D) {
- T a, b;
- if (!N || !D || !(*D)) {
- assert(false);
- return;
- }
-
- a = *N;
- b = *D;
-
- if (a == 0) {
- *D = 1;
- return;
- }
-
- // This implements Euclid's method to find GCD.
- if (a < b) {
- T tmp = a;
- a = b;
- b = tmp;
- }
-
- while (1) {
- // a is now the greater of the two.
- const T remainder = a % b;
- if (remainder == 0) {
- *N /= b;
- *D /= b;
- return;
- }
- // by swapping remainder and b, we are guaranteeing that a is
- // still the greater of the two upon entrance to the loop.
- a = b;
- b = remainder;
- }
-};
-
-template void LinearTransform::reduce<uint64_t>(uint64_t* N, uint64_t* D);
-template void LinearTransform::reduce<uint32_t>(uint32_t* N, uint32_t* D);
-
-// sanitize failure if *N = 0x80000000
-ATTRIBUTE_NO_SANITIZE_INTEGER
-void LinearTransform::reduce(int32_t* N, uint32_t* D) {
- if (N && D && *D) {
- if (*N < 0) {
- *N = -(*N);
- reduce(reinterpret_cast<uint32_t*>(N), D);
- *N = -(*N);
- } else {
- reduce(reinterpret_cast<uint32_t*>(N), D);
- }
- }
-}
-
-} // namespace android
diff --git a/libutils/StrongPointer.cpp b/libutils/StrongPointer.cpp
new file mode 100644
index 0000000..ba52502
--- /dev/null
+++ b/libutils/StrongPointer.cpp
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "sp"
+
+#include <log/log.h>
+
+namespace android {
+
+void sp_report_race() { LOG_ALWAYS_FATAL("sp<> assignment detected data race"); }
+}
diff --git a/libutils/include/utils/LinearTransform.h b/libutils/include/utils/LinearTransform.h
deleted file mode 100644
index 04cb355..0000000
--- a/libutils/include/utils/LinearTransform.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2011 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 _LIBS_UTILS_LINEAR_TRANSFORM_H
-#define _LIBS_UTILS_LINEAR_TRANSFORM_H
-
-#include <stdint.h>
-
-namespace android {
-
-// LinearTransform defines a structure which hold the definition of a
-// transformation from single dimensional coordinate system A into coordinate
-// system B (and back again). Values in A and in B are 64 bit, the linear
-// scale factor is expressed as a rational number using two 32 bit values.
-//
-// Specifically, let
-// f(a) = b
-// F(b) = f^-1(b) = a
-// then
-//
-// f(a) = (((a - a_zero) * a_to_b_numer) / a_to_b_denom) + b_zero;
-//
-// and
-//
-// F(b) = (((b - b_zero) * a_to_b_denom) / a_to_b_numer) + a_zero;
-//
-struct LinearTransform {
- int64_t a_zero;
- int64_t b_zero;
- int32_t a_to_b_numer;
- uint32_t a_to_b_denom;
-
- // Transform from A->B
- // Returns true on success, or false in the case of a singularity or an
- // overflow.
- bool doForwardTransform(int64_t a_in, int64_t* b_out) const;
-
- // Transform from B->A
- // Returns true on success, or false in the case of a singularity or an
- // overflow.
- bool doReverseTransform(int64_t b_in, int64_t* a_out) const;
-
- // Helpers which will reduce the fraction N/D using Euclid's method.
- template <class T> static void reduce(T* N, T* D);
- static void reduce(int32_t* N, uint32_t* D);
-};
-
-
-}
-
-#endif // _LIBS_UTILS_LINEAR_TRANSFORM_H
diff --git a/libutils/include/utils/StrongPointer.h b/libutils/include/utils/StrongPointer.h
index cdfdd8a..0c20607 100644
--- a/libutils/include/utils/StrongPointer.h
+++ b/libutils/include/utils/StrongPointer.h
@@ -102,6 +102,9 @@
T* m_ptr;
};
+// For code size reasons, we do not want this inlined or templated.
+void sp_report_race();
+
#undef COMPARE
// ---------------------------------------------------------------------------
@@ -155,19 +158,21 @@
template<typename T>
sp<T>& sp<T>::operator =(const sp<T>& other) {
+ // Force m_ptr to be read twice, to heuristically check for data races.
+ T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
T* otherPtr(other.m_ptr);
- if (otherPtr)
- otherPtr->incStrong(this);
- if (m_ptr)
- m_ptr->decStrong(this);
+ if (otherPtr) otherPtr->incStrong(this);
+ if (oldPtr) oldPtr->decStrong(this);
+ if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
m_ptr = otherPtr;
return *this;
}
template<typename T>
sp<T>& sp<T>::operator =(sp<T>&& other) {
- if (m_ptr)
- m_ptr->decStrong(this);
+ T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+ if (oldPtr) oldPtr->decStrong(this);
+ if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
return *this;
@@ -175,29 +180,30 @@
template<typename T>
sp<T>& sp<T>::operator =(T* other) {
- if (other)
- other->incStrong(this);
- if (m_ptr)
- m_ptr->decStrong(this);
+ T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+ if (other) other->incStrong(this);
+ if (oldPtr) oldPtr->decStrong(this);
+ if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
m_ptr = other;
return *this;
}
template<typename T> template<typename U>
sp<T>& sp<T>::operator =(const sp<U>& other) {
+ T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
T* otherPtr(other.m_ptr);
- if (otherPtr)
- otherPtr->incStrong(this);
- if (m_ptr)
- m_ptr->decStrong(this);
+ if (otherPtr) otherPtr->incStrong(this);
+ if (oldPtr) oldPtr->decStrong(this);
+ if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
m_ptr = otherPtr;
return *this;
}
template<typename T> template<typename U>
sp<T>& sp<T>::operator =(sp<U>&& other) {
- if (m_ptr)
- m_ptr->decStrong(this);
+ T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+ if (m_ptr) m_ptr->decStrong(this);
+ if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
return *this;
@@ -205,10 +211,10 @@
template<typename T> template<typename U>
sp<T>& sp<T>::operator =(U* other) {
- if (other)
- (static_cast<T*>(other))->incStrong(this);
- if (m_ptr)
- m_ptr->decStrong(this);
+ T* oldPtr(*const_cast<T* volatile*>(&m_ptr));
+ if (other) (static_cast<T*>(other))->incStrong(this);
+ if (oldPtr) oldPtr->decStrong(this);
+ if (oldPtr != *const_cast<T* volatile*>(&m_ptr)) sp_report_race();
m_ptr = other;
return *this;
}
diff --git a/libutils/include/utils/TypeHelpers.h b/libutils/include/utils/TypeHelpers.h
index 2a25227..28fbca5 100644
--- a/libutils/include/utils/TypeHelpers.h
+++ b/libutils/include/utils/TypeHelpers.h
@@ -36,7 +36,7 @@
template <typename T> struct trait_trivial_dtor { enum { value = false }; };
template <typename T> struct trait_trivial_copy { enum { value = false }; };
template <typename T> struct trait_trivial_move { enum { value = false }; };
-template <typename T> struct trait_pointer { enum { value = false }; };
+template <typename T> struct trait_pointer { enum { value = false }; };
template <typename T> struct trait_pointer<T*> { enum { value = true }; };
template <typename TYPE>
@@ -59,13 +59,13 @@
struct aggregate_traits {
enum {
is_pointer = false,
- has_trivial_ctor =
+ has_trivial_ctor =
traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor,
- has_trivial_dtor =
+ has_trivial_dtor =
traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor,
- has_trivial_copy =
+ has_trivial_copy =
traits<T>::has_trivial_copy && traits<U>::has_trivial_copy,
- has_trivial_move =
+ has_trivial_move =
traits<T>::has_trivial_move && traits<U>::has_trivial_move
};
};
diff --git a/libutils/include/utils/Vector.h b/libutils/include/utils/Vector.h
index 9a643f9..3189fd6 100644
--- a/libutils/include/utils/Vector.h
+++ b/libutils/include/utils/Vector.h
@@ -42,11 +42,11 @@
{
public:
typedef TYPE value_type;
-
- /*!
+
+ /*!
* Constructors and destructors
*/
-
+
Vector();
Vector(const Vector<TYPE>& rhs);
explicit Vector(const SortedVector<TYPE>& rhs);
@@ -54,7 +54,7 @@
/*! copy operator */
const Vector<TYPE>& operator = (const Vector<TYPE>& rhs) const;
- Vector<TYPE>& operator = (const Vector<TYPE>& rhs);
+ Vector<TYPE>& operator = (const Vector<TYPE>& rhs);
const Vector<TYPE>& operator = (const SortedVector<TYPE>& rhs) const;
Vector<TYPE>& operator = (const SortedVector<TYPE>& rhs);
@@ -65,7 +65,7 @@
inline void clear() { VectorImpl::clear(); }
- /*!
+ /*!
* vector stats
*/
@@ -87,13 +87,13 @@
/*!
* C-style array access
*/
-
- //! read-only C-style access
+
+ //! read-only C-style access
inline const TYPE* array() const;
//! read-write C-style access
TYPE* editArray();
-
- /*!
+
+ /*!
* accessors
*/
@@ -113,10 +113,10 @@
//! grants right access to the top of the stack (last element)
TYPE& editTop();
- /*!
+ /*!
* append/insert another vector
*/
-
+
//! insert another vector at a given index
ssize_t insertVectorAt(const Vector<TYPE>& vector, size_t index);
@@ -130,10 +130,10 @@
//! append an array at the end of this vector
ssize_t appendArray(const TYPE* array, size_t length);
- /*!
+ /*!
* add/insert/replace items
*/
-
+
//! insert one or several items initialized with their default constructor
inline ssize_t insertAt(size_t index, size_t numItems = 1);
//! insert one or several items initialized from a prototype item
@@ -147,7 +147,7 @@
//! same as push() but returns the index the item was added at (or an error)
inline ssize_t add();
//! same as push() but returns the index the item was added at (or an error)
- ssize_t add(const TYPE& item);
+ ssize_t add(const TYPE& item);
//! replace an item with a new one initialized with its default constructor
inline ssize_t replaceAt(size_t index);
//! replace an item with a new one
@@ -165,10 +165,10 @@
/*!
* sort (stable) the array
*/
-
+
typedef int (*compar_t)(const TYPE* lhs, const TYPE* rhs);
typedef int (*compar_r_t)(const TYPE* lhs, const TYPE* rhs, void* state);
-
+
inline status_t sort(compar_t cmp);
inline status_t sort(compar_r_t cmp, void* state);
@@ -237,7 +237,7 @@
template<class TYPE> inline
Vector<TYPE>& Vector<TYPE>::operator = (const Vector<TYPE>& rhs) {
VectorImpl::operator = (rhs);
- return *this;
+ return *this;
}
template<class TYPE> inline
@@ -255,7 +255,7 @@
template<class TYPE> inline
const Vector<TYPE>& Vector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
VectorImpl::operator = (rhs);
- return *this;
+ return *this;
}
template<class TYPE> inline
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 4da5030..8134936 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -41,6 +41,7 @@
#include <vector>
#include <android-base/file.h>
+#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <cutils/sched_policy.h>
@@ -1195,39 +1196,71 @@
} break;
case 'Q':
-#define KERNEL_OPTION "androidboot.logcat="
+#define LOGCAT_FILTER "androidboot.logcat="
+#define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
#define CONSOLE_OPTION "androidboot.console="
+#define QEMU_PROPERTY "ro.kernel.qemu"
+#define QEMU_CMDLINE "qemu.cmdline"
// This is a *hidden* option used to start a version of logcat
// in an emulated device only. It basically looks for
// androidboot.logcat= on the kernel command line. If
// something is found, it extracts a log filter and uses it to
- // run the program. If nothing is found, the program should
- // quit immediately.
+ // run the program. The logcat output will go to consolepipe if
+ // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
+ // it goes to androidboot.console (e.g. tty)
{
- std::string cmdline;
- android::base::ReadFileToString("/proc/cmdline", &cmdline);
-
- const char* logcat = strstr(cmdline.c_str(), KERNEL_OPTION);
- // if nothing found or invalid filters, exit quietly
- if (!logcat) {
+ // if not in emulator, exit quietly
+ if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
context->retval = EXIT_SUCCESS;
goto exit;
}
- const char* p = logcat + strlen(KERNEL_OPTION);
+ std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
+ if (cmdline.empty()) {
+ android::base::ReadFileToString("/proc/cmdline", &cmdline);
+ }
+
+ const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
+ // if nothing found or invalid filters, exit quietly
+ if (!logcatFilter) {
+ context->retval = EXIT_SUCCESS;
+ goto exit;
+ }
+
+ const char* p = logcatFilter + strlen(LOGCAT_FILTER);
const char* q = strpbrk(p, " \t\n\r");
if (!q) q = p + strlen(p);
forceFilters = std::string(p, q);
- // redirect our output to the emulator console
+ // redirect our output to the emulator console pipe or console
+ const char* consolePipe =
+ strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
const char* console =
strstr(cmdline.c_str(), CONSOLE_OPTION);
- if (!console) break;
- p = console + strlen(CONSOLE_OPTION);
+ if (consolePipe) {
+ p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
+ } else if (console) {
+ p = console + strlen(CONSOLE_OPTION);
+ } else {
+ context->retval = EXIT_FAILURE;
+ goto exit;
+ }
+
q = strpbrk(p, " \t\n\r");
int len = q ? q - p : strlen(p);
std::string devname = "/dev/" + std::string(p, len);
+ std::string pipePurpose("pipe:logcat");
+ if (consolePipe) {
+ // example: "qemu_pipe,pipe:logcat"
+ // upon opening of /dev/qemu_pipe, the "pipe:logcat"
+ // string with trailing '\0' should be written to the fd
+ size_t pos = devname.find(",");
+ if (pos != std::string::npos) {
+ pipePurpose = devname.substr(pos + 1);
+ devname = devname.substr(0, pos);
+ }
+ }
cmdline.erase();
if (context->error) {
@@ -1239,6 +1272,16 @@
devname.erase();
if (!fp) break;
+ if (consolePipe) {
+ // need the trailing '\0'
+ if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
+ pipePurpose.size() + 1)) {
+ fclose(fp);
+ context->retval = EXIT_FAILURE;
+ goto exit;
+ }
+ }
+
// close output and error channels, replace with console
android::close_output(context);
android::close_error(context);
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index dad74ee..0895834 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -208,9 +208,9 @@
if ((*ep != '-') && (*ep != '.')) {
continue;
}
- // Find PID field
+ // Find PID field. Look for ': ' or ':[0-9][0-9][0-9]'
while (((ep = strchr(ep, ':'))) && (*++ep != ' ')) {
- ;
+ if (isdigit(ep[0]) && isdigit(ep[1]) && isdigit(ep[2])) break;
}
if (!ep) {
continue;
diff --git a/logd/FlushCommand.cpp b/logd/FlushCommand.cpp
index 5a5c0d9..c67d2bf 100644
--- a/logd/FlushCommand.cpp
+++ b/logd/FlushCommand.cpp
@@ -27,7 +27,7 @@
#include "LogUtils.h"
FlushCommand::FlushCommand(LogReader& reader, bool nonBlock, unsigned long tail,
- unsigned int logMask, pid_t pid, uint64_t start,
+ unsigned int logMask, pid_t pid, log_time start,
uint64_t timeout)
: mReader(reader),
mNonBlock(nonBlock),
@@ -35,7 +35,7 @@
mLogMask(logMask),
mPid(pid),
mStart(start),
- mTimeout((start > 1) ? timeout : 0) {
+ mTimeout((start != log_time::EPOCH) ? timeout : 0) {
}
// runSocketCommand is called once for every open client on the
@@ -57,8 +57,18 @@
entry = (*it);
if (entry->mClient == client) {
if (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec) {
- LogTimeEntry::unlock();
- return;
+ if (mReader.logbuf().isMonotonic()) {
+ LogTimeEntry::unlock();
+ return;
+ }
+ // If the user changes the time in a gross manner that
+ // invalidates the timeout, fall through and trigger.
+ log_time now(CLOCK_REALTIME);
+ if (((entry->mEnd + entry->mTimeout) > now) &&
+ (now > entry->mEnd)) {
+ LogTimeEntry::unlock();
+ return;
+ }
}
entry->triggerReader_Locked();
if (entry->runningReader_Locked()) {
diff --git a/logd/FlushCommand.h b/logd/FlushCommand.h
index 45cb9c5..7cdd03f 100644
--- a/logd/FlushCommand.h
+++ b/logd/FlushCommand.h
@@ -16,7 +16,7 @@
#ifndef _FLUSH_COMMAND_H
#define _FLUSH_COMMAND_H
-#include <android/log.h>
+#include <private/android_logger.h>
#include <sysutils/SocketClientCommand.h>
class LogBufferElement;
@@ -31,13 +31,13 @@
unsigned long mTail;
unsigned int mLogMask;
pid_t mPid;
- uint64_t mStart;
+ log_time mStart;
uint64_t mTimeout;
public:
explicit FlushCommand(LogReader& mReader, bool nonBlock = false,
unsigned long tail = -1, unsigned int logMask = -1,
- pid_t pid = 0, uint64_t start = 1,
+ pid_t pid = 0, log_time start = log_time::EPOCH,
uint64_t timeout = 0);
virtual void runSocketCommand(SocketClient* client);
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 60d647d..dd78275 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -183,7 +183,7 @@
lenr -= avcr - msgr;
if (lenl != lenr) return DIFFERENT;
// TODO: After b/35468874 is addressed, revisit "lenl > strlen(avc)"
- // condition, it might become superflous.
+ // condition, it might become superfluous.
if (lenl > strlen(avc) &&
fastcmp<memcmp>(avcl + strlen(avc), avcr + strlen(avc),
lenl - strlen(avc))) {
@@ -372,22 +372,22 @@
// assumes mLogElementsLock held, owns elem, will look after garbage collection
void LogBuffer::log(LogBufferElement* elem) {
+ // cap on how far back we will sort in-place, otherwise append
+ static uint32_t too_far_back = 5; // five seconds
// Insert elements in time sorted order if possible
// NB: if end is region locked, place element at end of list
LogBufferElementCollection::iterator it = mLogElements.end();
LogBufferElementCollection::iterator last = it;
- while (last != mLogElements.begin()) {
- --it;
- if ((*it)->getRealTime() <= elem->getRealTime()) {
- break;
- }
- last = it;
- }
-
- if (last == mLogElements.end()) {
+ if (__predict_true(it != mLogElements.begin())) --it;
+ if (__predict_false(it == mLogElements.begin()) ||
+ __predict_true((*it)->getRealTime() <= elem->getRealTime()) ||
+ __predict_false((((*it)->getRealTime().tv_sec - too_far_back) >
+ elem->getRealTime().tv_sec) &&
+ (elem->getLogId() != LOG_ID_KERNEL) &&
+ ((*it)->getLogId() != LOG_ID_KERNEL))) {
mLogElements.push_back(elem);
} else {
- uint64_t end = 1;
+ log_time end = log_time::EPOCH;
bool end_set = false;
bool end_always = false;
@@ -401,6 +401,7 @@
end_always = true;
break;
}
+ // it passing mEnd is blocked by the following checks.
if (!end_set || (end <= entry->mEnd)) {
end = entry->mEnd;
end_set = true;
@@ -409,12 +410,20 @@
times++;
}
- if (end_always || (end_set && (end >= (*last)->getSequence()))) {
+ if (end_always || (end_set && (end > (*it)->getRealTime()))) {
mLogElements.push_back(elem);
} else {
+ // should be short as timestamps are localized near end()
+ do {
+ last = it;
+ if (__predict_false(it == mLogElements.begin())) {
+ break;
+ }
+ --it;
+ } while (((*it)->getRealTime() > elem->getRealTime()) &&
+ (!end_set || (end <= (*it)->getRealTime())));
mLogElements.insert(last, elem);
}
-
LogTimeEntry::unlock();
}
@@ -589,12 +598,12 @@
}
void clear(LogBufferElement* element) {
- uint64_t current =
- element->getRealTime().nsec() - (EXPIRE_RATELIMIT * NS_PER_SEC);
+ log_time current =
+ element->getRealTime() - log_time(EXPIRE_RATELIMIT, 0);
for (LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
LogBufferElement* mapElement = it->second;
if ((mapElement->getDropped() >= EXPIRE_THRESHOLD) &&
- (current > mapElement->getRealTime().nsec())) {
+ (current > mapElement->getRealTime())) {
it = map.erase(it);
} else {
++it;
@@ -690,7 +699,7 @@
mLastSet[id] = true;
}
- if (oldest && (oldest->mStart <= element->getSequence())) {
+ if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
busy = true;
if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
oldest->triggerReader_Locked();
@@ -782,7 +791,7 @@
while (it != mLogElements.end()) {
LogBufferElement* element = *it;
- if (oldest && (oldest->mStart <= element->getSequence())) {
+ if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
busy = true;
if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
oldest->triggerReader_Locked();
@@ -936,7 +945,7 @@
mLastSet[id] = true;
}
- if (oldest && (oldest->mStart <= element->getSequence())) {
+ if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
busy = true;
if (whitelist) {
break;
@@ -980,7 +989,7 @@
mLastSet[id] = true;
}
- if (oldest && (oldest->mStart <= element->getSequence())) {
+ if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
busy = true;
if (stats.sizes(id) > (2 * log_buffer_size(id))) {
// kick a misbehaving log reader client off the island
@@ -1073,32 +1082,37 @@
return retval;
}
-uint64_t LogBuffer::flushTo(
- SocketClient* reader, const uint64_t start, bool privileged, bool security,
+log_time LogBuffer::flushTo(
+ SocketClient* reader, const log_time& start, bool privileged, bool security,
int (*filter)(const LogBufferElement* element, void* arg), void* arg) {
LogBufferElementCollection::iterator it;
- uint64_t max = start;
uid_t uid = reader->getUid();
pthread_mutex_lock(&mLogElementsLock);
- if (start <= 1) {
+ if (start == log_time::EPOCH) {
// client wants to start from the beginning
it = mLogElements.begin();
} else {
+ LogBufferElementCollection::iterator last = mLogElements.begin();
+ // 30 second limit to continue search for out-of-order entries.
+ log_time min = start - log_time(30, 0);
// Client wants to start from some specified time. Chances are
// we are better off starting from the end of the time sorted list.
for (it = mLogElements.end(); it != mLogElements.begin();
/* do nothing */) {
--it;
LogBufferElement* element = *it;
- if (element->getSequence() <= start) {
- it++;
+ if (element->getRealTime() > start) {
+ last = it;
+ } else if (element->getRealTime() < min) {
break;
}
}
+ it = last;
}
+ log_time max = start;
// Help detect if the valid message before is from the same source so
// we can differentiate chatty filter types.
pid_t lastTid[LOG_ID_MAX] = { 0 };
@@ -1114,7 +1128,7 @@
continue;
}
- if (element->getSequence() <= start) {
+ if (element->getRealTime() <= start) {
continue;
}
diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h
index 92b0297..fcf6b9a 100644
--- a/logd/LogBuffer.h
+++ b/logd/LogBuffer.h
@@ -115,7 +115,7 @@
int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
const char* msg, unsigned short len);
- uint64_t flushTo(SocketClient* writer, const uint64_t start,
+ log_time flushTo(SocketClient* writer, const log_time& start,
bool privileged, bool security,
int (*filter)(const LogBufferElement* element,
void* arg) = NULL,
diff --git a/logd/LogBufferElement.cpp b/logd/LogBufferElement.cpp
index 5ba3a15..81356fe 100644
--- a/logd/LogBufferElement.cpp
+++ b/logd/LogBufferElement.cpp
@@ -30,7 +30,7 @@
#include "LogReader.h"
#include "LogUtils.h"
-const uint64_t LogBufferElement::FLUSH_ERROR(0);
+const log_time LogBufferElement::FLUSH_ERROR((uint32_t)-1, (uint32_t)-1);
atomic_int_fast64_t LogBufferElement::sequence(1);
LogBufferElement::LogBufferElement(log_id_t log_id, log_time realtime,
@@ -39,7 +39,6 @@
: mUid(uid),
mPid(pid),
mTid(tid),
- mSequence(sequence.fetch_add(1, memory_order_relaxed)),
mRealTime(realtime),
mMsgLen(len),
mLogId(log_id) {
@@ -55,7 +54,6 @@
mUid(elem.mUid),
mPid(elem.mPid),
mTid(elem.mTid),
- mSequence(elem.mSequence),
mRealTime(elem.mRealTime),
mMsgLen(elem.mMsgLen),
mLogId(elem.mLogId) {
@@ -206,7 +204,7 @@
return retval;
}
-uint64_t LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent,
+log_time LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent,
bool privileged, bool lastSame) {
struct logger_entry_v4 entry;
@@ -229,7 +227,7 @@
if (!mMsg) {
entry.len = populateDroppedMessage(buffer, parent, lastSame);
- if (!entry.len) return mSequence;
+ if (!entry.len) return mRealTime;
iovec[1].iov_base = buffer;
} else {
entry.len = mMsgLen;
@@ -237,7 +235,7 @@
}
iovec[1].iov_len = entry.len;
- uint64_t retval = reader->sendDatav(iovec, 2) ? FLUSH_ERROR : mSequence;
+ log_time retval = reader->sendDatav(iovec, 2) ? FLUSH_ERROR : mRealTime;
if (buffer) free(buffer);
diff --git a/logd/LogBufferElement.h b/logd/LogBufferElement.h
index 43990e8..814ec87 100644
--- a/logd/LogBufferElement.h
+++ b/logd/LogBufferElement.h
@@ -40,7 +40,6 @@
const uint32_t mUid;
const uint32_t mPid;
const uint32_t mTid;
- const uint64_t mSequence;
log_time mRealTime;
char* mMsg;
union {
@@ -96,18 +95,12 @@
const char* getMsg() const {
return mMsg;
}
- uint64_t getSequence(void) const {
- return mSequence;
- }
- static uint64_t getCurrentSequence(void) {
- return sequence.load(memory_order_relaxed);
- }
log_time getRealTime(void) const {
return mRealTime;
}
- static const uint64_t FLUSH_ERROR;
- uint64_t flushTo(SocketClient* writer, LogBuffer* parent, bool privileged,
+ static const log_time FLUSH_ERROR;
+ log_time flushTo(SocketClient* writer, LogBuffer* parent, bool privileged,
bool lastSame);
};
diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp
index 9ae95f9..9dfa14e 100644
--- a/logd/LogKlog.cpp
+++ b/logd/LogKlog.cpp
@@ -754,7 +754,7 @@
// eg: [143:healthd]healthd -> [143:healthd]
taglen = etag - tag;
// Mediatek-special printk induced stutter
- const char* mp = strnrchr(tag, ']', taglen);
+ const char* mp = strnrchr(tag, taglen, ']');
if (mp && (++mp < etag)) {
size_t s = etag - mp;
if (((s + s) < taglen) && !fastcmp<memcmp>(mp, mp - 1 - s, s)) {
diff --git a/logd/LogReader.cpp b/logd/LogReader.cpp
index 76f5798..620d4d0 100644
--- a/logd/LogReader.cpp
+++ b/logd/LogReader.cpp
@@ -116,57 +116,70 @@
nonBlock = true;
}
- uint64_t sequence = 1;
- // Convert realtime to sequence number
- if (start != log_time::EPOCH) {
- class LogFindStart {
+ log_time sequence = start;
+ //
+ // This somewhat expensive data validation operation is required
+ // for non-blocking, with timeout. The incoming timestamp must be
+ // in range of the list, if not, return immediately. This is
+ // used to prevent us from from getting stuck in timeout processing
+ // with an invalid time.
+ //
+ // Find if time is really present in the logs, monotonic or real, implicit
+ // conversion from monotonic or real as necessary to perform the check.
+ // Exit in the check loop ASAP as you find a transition from older to
+ // newer, but use the last entry found to ensure overlap.
+ //
+ if (nonBlock && (sequence != log_time::EPOCH) && timeout) {
+ class LogFindStart { // A lambda by another name
+ private:
const pid_t mPid;
const unsigned mLogMask;
- bool startTimeSet;
- log_time& start;
- uint64_t& sequence;
- uint64_t last;
- bool isMonotonic;
+ bool mStartTimeSet;
+ log_time mStart;
+ log_time& mSequence;
+ log_time mLast;
+ bool mIsMonotonic;
public:
- LogFindStart(unsigned logMask, pid_t pid, log_time& start,
- uint64_t& sequence, bool isMonotonic)
+ LogFindStart(pid_t pid, unsigned logMask, log_time& sequence,
+ bool isMonotonic)
: mPid(pid),
mLogMask(logMask),
- startTimeSet(false),
- start(start),
- sequence(sequence),
- last(sequence),
- isMonotonic(isMonotonic) {
+ mStartTimeSet(false),
+ mStart(sequence),
+ mSequence(sequence),
+ mLast(sequence),
+ mIsMonotonic(isMonotonic) {
}
static int callback(const LogBufferElement* element, void* obj) {
LogFindStart* me = reinterpret_cast<LogFindStart*>(obj);
if ((!me->mPid || (me->mPid == element->getPid())) &&
(me->mLogMask & (1 << element->getLogId()))) {
- if (me->start == element->getRealTime()) {
- me->sequence = element->getSequence();
- me->startTimeSet = true;
+ log_time real = element->getRealTime();
+ if (me->mStart == real) {
+ me->mSequence = real;
+ me->mStartTimeSet = true;
return -1;
- } else if (!me->isMonotonic ||
- android::isMonotonic(element->getRealTime())) {
- if (me->start < element->getRealTime()) {
- me->sequence = me->last;
- me->startTimeSet = true;
+ } else if (!me->mIsMonotonic || android::isMonotonic(real)) {
+ if (me->mStart < real) {
+ me->mSequence = me->mLast;
+ me->mStartTimeSet = true;
return -1;
}
- me->last = element->getSequence();
+ me->mLast = real;
} else {
- me->last = element->getSequence();
+ me->mLast = real;
}
}
return false;
}
bool found() {
- return startTimeSet;
+ return mStartTimeSet;
}
- } logFindStart(logMask, pid, start, sequence,
+
+ } logFindStart(pid, logMask, sequence,
logbuf().isMonotonic() && android::isMonotonic(start));
logbuf().flushTo(cli, sequence, FlushCommand::hasReadLogs(cli),
@@ -174,11 +187,8 @@
logFindStart.callback, &logFindStart);
if (!logFindStart.found()) {
- if (nonBlock) {
- doSocketDelete(cli);
- return false;
- }
- sequence = LogBufferElement::getCurrentSequence();
+ doSocketDelete(cli);
+ return false;
}
}
diff --git a/logd/LogTimes.cpp b/logd/LogTimes.cpp
index bdaeb75..04e531f 100644
--- a/logd/LogTimes.cpp
+++ b/logd/LogTimes.cpp
@@ -17,6 +17,8 @@
#include <errno.h>
#include <sys/prctl.h>
+#include <private/android_logger.h>
+
#include "FlushCommand.h"
#include "LogBuffer.h"
#include "LogReader.h"
@@ -26,7 +28,7 @@
LogTimeEntry::LogTimeEntry(LogReader& reader, SocketClient* client,
bool nonBlock, unsigned long tail,
- unsigned int logMask, pid_t pid, uint64_t start,
+ unsigned int logMask, pid_t pid, log_time start,
uint64_t timeout)
: mRefCount(1),
mRelease(false),
@@ -42,7 +44,7 @@
mClient(client),
mStart(start),
mNonBlock(nonBlock),
- mEnd(LogBufferElement::getCurrentSequence()) {
+ mEnd(log_time(android_log_clockid())) {
mTimeout.tv_sec = timeout / NS_PER_SEC;
mTimeout.tv_nsec = timeout % NS_PER_SEC;
pthread_cond_init(&threadTriggeredCondition, NULL);
@@ -132,7 +134,7 @@
lock();
- uint64_t start = me->mStart;
+ log_time start = me->mStart;
while (me->threadRunning && !me->isError_Locked()) {
if (me->mTimeout.tv_sec || me->mTimeout.tv_nsec) {
@@ -163,7 +165,7 @@
break;
}
- me->mStart = start + 1;
+ me->mStart = start + log_time(0, 1);
if (me->mNonBlock || !me->threadRunning || me->isError_Locked()) {
break;
@@ -198,7 +200,7 @@
}
if (me->mCount == 0) {
- me->mStart = element->getSequence();
+ me->mStart = element->getRealTime();
}
if ((!me->mPid || (me->mPid == element->getPid())) &&
@@ -217,7 +219,7 @@
LogTimeEntry::lock();
- me->mStart = element->getSequence();
+ me->mStart = element->getRealTime();
if (me->skipAhead[element->getLogId()]) {
me->skipAhead[element->getLogId()]--;
diff --git a/logd/LogTimes.h b/logd/LogTimes.h
index 23fdf4e..9a3ddab 100644
--- a/logd/LogTimes.h
+++ b/logd/LogTimes.h
@@ -51,13 +51,13 @@
public:
LogTimeEntry(LogReader& reader, SocketClient* client, bool nonBlock,
unsigned long tail, unsigned int logMask, pid_t pid,
- uint64_t start, uint64_t timeout);
+ log_time start, uint64_t timeout);
SocketClient* mClient;
- uint64_t mStart;
+ log_time mStart;
struct timespec mTimeout;
const bool mNonBlock;
- const uint64_t mEnd; // only relevant if mNonBlock
+ const log_time mEnd; // only relevant if mNonBlock
// Protect List manipulations
static void lock(void) {
diff --git a/rootdir/init-debug.rc b/rootdir/init-debug.rc
index 44d34d8..435d4cb 100644
--- a/rootdir/init-debug.rc
+++ b/rootdir/init-debug.rc
@@ -6,6 +6,3 @@
on property:persist.mmc.cache_size=*
write /sys/block/mmcblk0/cache_size ${persist.mmc.cache_size}
-
-on early-init
- mount debugfs debugfs /sys/kernel/debug
diff --git a/sdcard/sdcard.cpp b/sdcard/sdcard.cpp
index df3ce85..c342cf8 100644
--- a/sdcard/sdcard.cpp
+++ b/sdcard/sdcard.cpp
@@ -420,7 +420,7 @@
}
// Fall back to device opinion about state
- if (property_get_bool(PROP_SDCARDFS_DEVICE, false)) {
+ if (property_get_bool(PROP_SDCARDFS_DEVICE, true)) {
LOG(WARNING) << "Device explicitly enabled sdcardfs";
return supports_sdcardfs();
} else {
diff --git a/storaged/Android.mk b/storaged/Android.mk
index 2adb14d..5e6a3c0 100644
--- a/storaged/Android.mk
+++ b/storaged/Android.mk
@@ -16,6 +16,7 @@
LOCAL_SRC_FILES := \
storaged.cpp \
+ storaged_info.cpp \
storaged_service.cpp \
storaged_utils.cpp \
storaged_uid_monitor.cpp \
diff --git a/storaged/include/storaged.h b/storaged/include/storaged.h
index c291bd9..bd1391c 100644
--- a/storaged/include/storaged.h
+++ b/storaged/include/storaged.h
@@ -28,6 +28,7 @@
#include <batteryservice/IBatteryPropertiesListener.h>
+#include "storaged_info.h"
#include "storaged_uid_monitor.h"
using namespace android;
@@ -44,6 +45,8 @@
#define debuginfo(...)
#endif
+#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
+
#define SECTOR_SIZE ( 512 )
#define SEC_TO_MSEC ( 1000 )
#define MSEC_TO_USEC ( 1000 )
@@ -83,15 +86,7 @@
double io_avg; // average io_in_flight for accumulate calculations
};
-#define MMC_VER_STR_LEN ( 9 ) // maximum length of the MMC version string, including NULL terminator
-// minimum size of a ext_csd file
-#define EXT_CSD_FILE_MIN_SIZE ( 1024 )
-struct emmc_info {
- int eol; // pre-eol (end of life) information
- int lifetime_a; // device life time estimation (type A)
- int lifetime_b; // device life time estimation (type B)
- char mmc_ver[MMC_VER_STR_LEN]; // device version string
-};
+
struct disk_perf {
uint32_t read_perf; // read speed (kbytes/s)
@@ -232,26 +227,6 @@
void update(void);
};
-class emmc_info_t {
-private:
- struct emmc_info mInfo;
- bool mValid;
- int mFdEmmc;
-public:
- emmc_info_t(void) :
- mValid(false),
- mFdEmmc(-1) {
- memset(&mInfo, 0, sizeof(struct emmc_info));
- }
- ~emmc_info_t(void) {}
-
- void publish(void);
- void update(void);
- void set_emmc_fd(int fd) {
- mFdEmmc = fd;
- }
-};
-
// Periodic chores intervals in seconds
#define DEFAULT_PERIODIC_CHORES_INTERVAL_UNIT ( 60 )
#define DEFAULT_PERIODIC_CHORES_INTERVAL_DISK_STATS_PUBLISH ( 3600 )
@@ -268,7 +243,6 @@
int periodic_chores_interval_emmc_info_publish;
int periodic_chores_interval_uid_io;
bool proc_uid_io_available; // whether uid_io is accessible
- bool emmc_available; // whether eMMC est_csd file is readable
bool diskstats_available; // whether diskstats is accessible
int event_time_check_usec; // check how much cputime spent in event loop
};
@@ -279,7 +253,7 @@
storaged_config mConfig;
disk_stats_publisher mDiskStats;
disk_stats_monitor mDsm;
- emmc_info_t mEmmcInfo;
+ storage_info_t *info = nullptr;
uid_monitor mUidm;
time_t mStarttime;
public:
@@ -290,8 +264,8 @@
void pause(void) {
sleep(mConfig.periodic_chores_interval_unit);
}
- void set_privileged_fds(int fd_emmc) {
- mEmmcInfo.set_emmc_fd(fd_emmc);
+ void set_storage_info(storage_info_t *storage_info) {
+ info = storage_info;
}
time_t get_starttime(void) {
diff --git a/storaged/include/storaged_info.h b/storaged/include/storaged_info.h
new file mode 100644
index 0000000..cb5b8a8
--- /dev/null
+++ b/storaged/include/storaged_info.h
@@ -0,0 +1,66 @@
+/*
+ * 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 _STORAGED_INFO_H_
+#define _STORAGED_INFO_H_
+
+#include <string.h>
+
+#define FRIEND_TEST(test_case_name, test_name) \
+friend class test_case_name##_##test_name##_Test
+
+using namespace std;
+
+// two characters in string for each byte
+struct str_hex {
+ char str[2];
+};
+
+class storage_info_t {
+protected:
+ FRIEND_TEST(storaged_test, storage_info_t);
+ uint8_t eol; // pre-eol (end of life) information
+ uint8_t lifetime_a; // device life time estimation (type A)
+ uint8_t lifetime_b; // device life time estimation (type B)
+ string version; // version string
+public:
+ void publish();
+ virtual ~storage_info_t() {}
+ virtual bool init() = 0;
+ virtual bool update() = 0;
+};
+
+class emmc_info_t : public storage_info_t {
+private:
+ // minimum size of a ext_csd file
+ const int EXT_CSD_FILE_MIN_SIZE = 1024;
+ // List of interesting offsets
+ const size_t EXT_CSD_REV_IDX = 192 * sizeof(str_hex);
+ const size_t EXT_PRE_EOL_INFO_IDX = 267 * sizeof(str_hex);
+ const size_t EXT_DEVICE_LIFE_TIME_EST_A_IDX = 268 * sizeof(str_hex);
+ const size_t EXT_DEVICE_LIFE_TIME_EST_B_IDX = 269 * sizeof(str_hex);
+
+ const char* ext_csd_file = "/d/mmc0/mmc0:0001/ext_csd";
+ const char* emmc_ver_str[8] = {
+ "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
+ };
+public:
+ virtual ~emmc_info_t() {}
+ bool init();
+ bool update();
+};
+
+#endif /* _STORAGED_INFO_H_ */
diff --git a/storaged/main.cpp b/storaged/main.cpp
index 672f453..e25298b 100644
--- a/storaged/main.cpp
+++ b/storaged/main.cpp
@@ -43,6 +43,7 @@
#include <storaged_utils.h>
storaged_t storaged;
+emmc_info_t emmc_info;
// Function of storaged's main thread
void* storaged_main(void* s) {
@@ -69,7 +70,6 @@
int main(int argc, char** argv) {
int flag_main_service = 0;
int flag_dump_uid = 0;
- int fd_emmc = -1;
int opt;
for (;;) {
@@ -114,12 +114,9 @@
}
if (flag_main_service) { // start main thread
- static const char mmc0_ext_csd[] = "/d/mmc0/mmc0:0001/ext_csd";
- fd_emmc = android_get_control_file(mmc0_ext_csd);
- if (fd_emmc < 0)
- fd_emmc = TEMP_FAILURE_RETRY(open(mmc0_ext_csd, O_RDONLY));
-
- storaged.set_privileged_fds(fd_emmc);
+ if (emmc_info.init()) {
+ storaged.set_storage_info(&emmc_info);
+ }
// Start the main thread of storaged
pthread_t storaged_main_thread;
@@ -134,8 +131,6 @@
IPCThreadState::self()->joinThreadPool();
pthread_join(storaged_main_thread, NULL);
- close(fd_emmc);
-
return 0;
}
diff --git a/storaged/storaged.cpp b/storaged/storaged.cpp
index 2f02074..88fbb7a 100644
--- a/storaged/storaged.cpp
+++ b/storaged/storaged.cpp
@@ -147,19 +147,6 @@
}
}
-/* emmc_info_t */
-void emmc_info_t::publish(void) {
- if (mValid) {
- log_event_emmc_info(&mInfo);
- }
-}
-
-void emmc_info_t::update(void) {
- if (mFdEmmc >= 0) {
- mValid = parse_emmc_ecsd(mFdEmmc, &mInfo);
- }
-}
-
static sp<IBatteryPropertiesRegistrar> get_battery_properties_service() {
sp<IServiceManager> sm = defaultServiceManager();
if (sm == NULL) return NULL;
@@ -199,8 +186,6 @@
/* storaged_t */
storaged_t::storaged_t(void) {
- mConfig.emmc_available = (access(EMMC_ECSD_PATH, R_OK) >= 0);
-
if (access(MMC_DISK_STATS_PATH, R_OK) < 0 && access(SDA_DISK_STATS_PATH, R_OK) < 0) {
mConfig.diskstats_available = false;
} else {
@@ -236,10 +221,10 @@
}
}
- if (mConfig.emmc_available && mTimer &&
- (mTimer % mConfig.periodic_chores_interval_emmc_info_publish) == 0) {
- mEmmcInfo.update();
- mEmmcInfo.publish();
+ if (info && mTimer &&
+ (mTimer % mConfig.periodic_chores_interval_emmc_info_publish) == 0) {
+ info->update();
+ info->publish();
}
if (mConfig.proc_uid_io_available && mTimer &&
diff --git a/storaged/storaged_info.cpp b/storaged/storaged_info.cpp
new file mode 100644
index 0000000..73d611c
--- /dev/null
+++ b/storaged/storaged_info.cpp
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#define LOG_TAG "storaged"
+
+#include <string.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <log/log_event_list.h>
+
+#include "storaged.h"
+
+using namespace std;
+using namespace android;
+using namespace android::base;
+
+void storage_info_t::publish()
+{
+ if (eol == 0 && lifetime_a == 0 && lifetime_b == 0) {
+ return;
+ }
+
+ android_log_event_list(EVENTLOGTAG_EMMCINFO)
+ << version << eol << lifetime_a << lifetime_b
+ << LOG_ID_EVENTS;
+}
+
+bool emmc_info_t::init()
+{
+ string buffer;
+ if (!ReadFileToString(ext_csd_file, &buffer) ||
+ buffer.length() < (size_t)EXT_CSD_FILE_MIN_SIZE) {
+ return false;
+ }
+
+ string ver_str = buffer.substr(EXT_CSD_REV_IDX, sizeof(str_hex));
+ uint8_t ext_csd_rev;
+ if (!ParseUint(ver_str, &ext_csd_rev)) {
+ LOG_TO(SYSTEM, ERROR) << "Failure on parsing EXT_CSD_REV.";
+ return false;
+ }
+
+ version = "emmc ";
+ version += (ext_csd_rev < ARRAY_SIZE(emmc_ver_str)) ?
+ emmc_ver_str[ext_csd_rev] : "Unknown";
+
+ if (ext_csd_rev < 7) {
+ return false;
+ }
+
+ return update();
+}
+
+bool emmc_info_t::update()
+{
+ string buffer;
+ if (!ReadFileToString(ext_csd_file, &buffer) ||
+ buffer.length() < (size_t)EXT_CSD_FILE_MIN_SIZE) {
+ return false;
+ }
+
+ string str = buffer.substr(EXT_PRE_EOL_INFO_IDX, sizeof(str_hex));
+ if (!ParseUint(str, &eol)) {
+ LOG_TO(SYSTEM, ERROR) << "Failure on parsing EXT_PRE_EOL_INFO.";
+ return false;
+ }
+
+ str = buffer.substr(EXT_DEVICE_LIFE_TIME_EST_A_IDX, sizeof(str_hex));
+ if (!ParseUint(str, &lifetime_a)) {
+ LOG_TO(SYSTEM, ERROR)
+ << "Failure on parsing EXT_DEVICE_LIFE_TIME_EST_TYP_A.";
+ return false;
+ }
+
+ str = buffer.substr(EXT_DEVICE_LIFE_TIME_EST_B_IDX, sizeof(str_hex));
+ if (!ParseUint(str, &lifetime_b)) {
+ LOG_TO(SYSTEM, ERROR)
+ << "Failure on parsing EXT_DEVICE_LIFE_TIME_EST_TYP_B.";
+ return false;
+ }
+
+ return true;
+}
diff --git a/storaged/storaged_utils.cpp b/storaged/storaged_utils.cpp
index 9fcf1fa..74b7436 100644
--- a/storaged/storaged_utils.cpp
+++ b/storaged/storaged_utils.cpp
@@ -158,93 +158,6 @@
}
}
-bool parse_emmc_ecsd(int ext_csd_fd, struct emmc_info* info) {
- CHECK(ext_csd_fd >= 0);
- struct hex {
- char str[2];
- };
- // List of interesting offsets
- static const size_t EXT_CSD_REV_IDX = 192 * sizeof(hex);
- static const size_t EXT_PRE_EOL_INFO_IDX = 267 * sizeof(hex);
- static const size_t EXT_DEVICE_LIFE_TIME_EST_A_IDX = 268 * sizeof(hex);
- static const size_t EXT_DEVICE_LIFE_TIME_EST_B_IDX = 269 * sizeof(hex);
-
- // Read file
- CHECK(lseek(ext_csd_fd, 0, SEEK_SET) == 0);
- std::string buffer;
- if (!android::base::ReadFdToString(ext_csd_fd, &buffer)) {
- PLOG_TO(SYSTEM, ERROR) << "ReadFdToString failed.";
- return false;
- }
-
- if (buffer.length() < EXT_CSD_FILE_MIN_SIZE) {
- LOG_TO(SYSTEM, ERROR) << "EMMC ext csd file has truncated content. "
- << "File length: " << buffer.length();
- return false;
- }
-
- std::string sub;
- std::stringstream ss;
- // Parse EXT_CSD_REV
- int ext_csd_rev = -1;
- sub = buffer.substr(EXT_CSD_REV_IDX, sizeof(hex));
- ss << sub;
- ss >> std::hex >> ext_csd_rev;
- if (ext_csd_rev < 0) {
- LOG_TO(SYSTEM, ERROR) << "Failure on parsing EXT_CSD_REV.";
- return false;
- }
- ss.clear();
-
- static const char* ver_str[] = {
- "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
- };
-
- strlcpy(info->mmc_ver,
- (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
- ver_str[ext_csd_rev] :
- "Unknown",
- MMC_VER_STR_LEN);
-
- if (ext_csd_rev < 7) {
- return 0;
- }
-
- // Parse EXT_PRE_EOL_INFO
- info->eol = -1;
- sub = buffer.substr(EXT_PRE_EOL_INFO_IDX, sizeof(hex));
- ss << sub;
- ss >> std::hex >> info->eol;
- if (info->eol < 0) {
- LOG_TO(SYSTEM, ERROR) << "Failure on parsing EXT_PRE_EOL_INFO.";
- return false;
- }
- ss.clear();
-
- // Parse DEVICE_LIFE_TIME_EST
- info->lifetime_a = -1;
- sub = buffer.substr(EXT_DEVICE_LIFE_TIME_EST_A_IDX, sizeof(hex));
- ss << sub;
- ss >> std::hex >> info->lifetime_a;
- if (info->lifetime_a < 0) {
- LOG_TO(SYSTEM, ERROR) << "Failure on parsing EXT_DEVICE_LIFE_TIME_EST_TYP_A.";
- return false;
- }
- ss.clear();
-
- info->lifetime_b = -1;
- sub = buffer.substr(EXT_DEVICE_LIFE_TIME_EST_B_IDX, sizeof(hex));
- ss << sub;
- ss >> std::hex >> info->lifetime_b;
- if (info->lifetime_b < 0) {
- LOG_TO(SYSTEM, ERROR) << "Failure on parsing EXT_DEVICE_LIFE_TIME_EST_TYP_B.";
- return false;
- }
- ss.clear();
-
- return true;
-}
-
static bool cmp_uid_info(struct uid_info l, struct uid_info r) {
// Compare background I/O first.
for (int i = UID_STATS - 1; i >= 0; i--) {
@@ -317,14 +230,3 @@
<< LOG_ID_EVENTS;
}
-void log_event_emmc_info(struct emmc_info* info) {
- // skip if the input structure are all zeros
- if (info == NULL) return;
- struct emmc_info zero_cmp;
- memset(&zero_cmp, 0, sizeof(zero_cmp));
- if (memcmp(&zero_cmp, info, sizeof(struct emmc_info)) == 0) return;
-
- android_log_event_list(EVENTLOGTAG_EMMCINFO)
- << info->mmc_ver << info->eol << info->lifetime_a << info->lifetime_b
- << LOG_ID_EVENTS;
-}
diff --git a/storaged/tests/storaged_test.cpp b/storaged/tests/storaged_test.cpp
index 9e03c50..e335cad 100644
--- a/storaged/tests/storaged_test.cpp
+++ b/storaged/tests/storaged_test.cpp
@@ -58,13 +58,11 @@
const char* DISK_STATS_PATH;
TEST(storaged_test, retvals) {
struct disk_stats stats;
- struct emmc_info info;
+ emmc_info_t info;
memset(&stats, 0, sizeof(struct disk_stats));
- memset(&info, 0, sizeof(struct emmc_info));
- int emmc_fd = open(EMMC_EXT_CSD_PATH, O_RDONLY);
- if (emmc_fd >= 0) {
- EXPECT_TRUE(parse_emmc_ecsd(emmc_fd, &info));
+ if (info.init()) {
+ EXPECT_TRUE(info.update());
}
if (access(MMC_DISK_STATS_PATH, R_OK) >= 0) {
@@ -129,17 +127,17 @@
}
}
-TEST(storaged_test, emmc_info) {
- struct emmc_info info, void_info;
- memset(&info, 0, sizeof(struct emmc_info));
- memset(&void_info, 0, sizeof(struct emmc_info));
+TEST(storaged_test, storage_info_t) {
+ emmc_info_t info;
if (access(EMMC_EXT_CSD_PATH, R_OK) >= 0) {
- int emmc_fd = open(EMMC_EXT_CSD_PATH, O_RDONLY);
- ASSERT_GE(emmc_fd, 0);
- ASSERT_TRUE(parse_emmc_ecsd(emmc_fd, &info));
- // parse_emmc_ecsd() should put something in info.
- EXPECT_NE(0, memcmp(&void_info, &info, sizeof(struct emmc_info)));
+ int ret = info.init();
+ if (ret) {
+ EXPECT_TRUE(info.version.empty());
+ ASSERT_TRUE(info.update());
+ // update should put something in info.
+ EXPECT_TRUE(info.eol || info.lifetime_a || info.lifetime_b);
+ }
}
}
diff --git a/tzdatacheck/tzdatacheck.cpp b/tzdatacheck/tzdatacheck.cpp
index 769f0f5..381df5a 100644
--- a/tzdatacheck/tzdatacheck.cpp
+++ b/tzdatacheck/tzdatacheck.cpp
@@ -31,7 +31,7 @@
#include "android-base/logging.h"
// The name of the file containing the distro version information.
-// See also libcore.tzdata.update2.TimeZoneDistro / libcore.tzdata.update2.DistroVersion.
+// See also libcore.tzdata.shared2.TimeZoneDistro / libcore.tzdata.shared2.DistroVersion.
static const char* DISTRO_VERSION_FILENAME = "/distro_version";
// distro_version is an ASCII file consisting of 17 bytes in the form: AAA.BBB|CCCCC|DDD
@@ -42,14 +42,14 @@
static const int DISTRO_VERSION_LENGTH = 13;
// The major version of the distro format supported by this code as a null-terminated char[].
-// See also libcore.tzdata.update2.TimeZoneDistro / libcore.tzdata.update2.DistroVersion.
+// See also libcore.tzdata.shared2.TimeZoneDistro / libcore.tzdata.shared2.DistroVersion.
static const char SUPPORTED_DISTRO_MAJOR_VERSION[] = "001";
// The length of the distro format major version excluding the \0
static const size_t SUPPORTED_DISTRO_MAJOR_VERSION_LEN = sizeof(SUPPORTED_DISTRO_MAJOR_VERSION) - 1;
// The minor version of the distro format supported by this code as a null-terminated char[].
-// See also libcore.tzdata.update2.TimeZoneDistro / libcore.tzdata.update2.DistroVersion.
+// See also libcore.tzdata.shared2.TimeZoneDistro / libcore.tzdata.shared2.DistroVersion.
static const char SUPPORTED_DISTRO_MINOR_VERSION[] = "001";
// The length of the distro format minor version excluding the \0
@@ -65,7 +65,7 @@
// Distro version bytes are: AAA.BBB|CCCCC - the rules version is CCCCC
static const size_t DISTRO_VERSION_RULES_IDX = 8;
-// See also libcore.tzdata.update2.TimeZoneDistro.
+// See also libcore.tzdata.shared2.TimeZoneDistro.
static const char* TZDATA_FILENAME = "/tzdata";
// tzdata file header (as much as we need for the version):