Merge "Stop attempting to read /d/sync"
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index d276696..443f885 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -62,7 +62,7 @@
using std::string;
-#define MAX_SYS_FILES 10
+#define MAX_SYS_FILES 11
const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
@@ -132,7 +132,11 @@
{ OPT, "events/sched/sched_blocked_reason/enable" },
{ OPT, "events/sched/sched_cpu_hotplug/enable" },
{ OPT, "events/sched/sched_pi_setprio/enable" },
+ { OPT, "events/sched/sched_process_exit/enable" },
{ OPT, "events/cgroup/enable" },
+ { OPT, "events/oom/oom_score_adj_update/enable" },
+ { OPT, "events/task/task_rename/enable" },
+ { OPT, "events/task/task_newtask/enable" },
} },
{ "irq", "IRQ Events", 0, {
{ REQ, "events/irq/enable" },
@@ -230,10 +234,6 @@
{ OPT, "events/kmem/rss_stat/enable" },
{ OPT, "events/kmem/ion_heap_grow/enable" },
{ OPT, "events/kmem/ion_heap_shrink/enable" },
- { OPT, "events/oom/oom_score_adj_update/enable" },
- { OPT, "events/sched/sched_process_exit/enable" },
- { OPT, "events/task/task_rename/enable" },
- { OPT, "events/task/task_newtask/enable" },
} },
};
diff --git a/cmds/atrace/atrace.rc b/cmds/atrace/atrace.rc
index 66c9cc6..f1426b6 100644
--- a/cmds/atrace/atrace.rc
+++ b/cmds/atrace/atrace.rc
@@ -33,6 +33,10 @@
chmod 0666 /sys/kernel/tracing/events/sched/sched_cpu_hotplug/enable
chmod 0666 /sys/kernel/debug/tracing/events/sched/sched_pi_setprio/enable
chmod 0666 /sys/kernel/tracing/events/sched/sched_pi_setprio/enable
+ chmod 0666 /sys/kernel/debug/tracing/events/sched/sched_process_exit/enable
+ chmod 0666 /sys/kernel/tracing/events/sched/sched_process_exit/enable
+ chmod 0666 /sys/kernel/debug/tracing/events/sched/sched_waking/enable
+ chmod 0666 /sys/kernel/tracing/events/sched/sched_waking/enable
chmod 0666 /sys/kernel/debug/tracing/events/cgroup/enable
chmod 0666 /sys/kernel/tracing/events/cgroup/enable
chmod 0666 /sys/kernel/debug/tracing/events/power/cpu_frequency/enable
@@ -43,6 +47,8 @@
chmod 0666 /sys/kernel/tracing/events/power/clock_set_rate/enable
chmod 0666 /sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable
chmod 0666 /sys/kernel/tracing/events/power/cpu_frequency_limits/enable
+ chmod 0666 /sys/kernel/debug/tracing/events/power/gpu_frequency/enable
+ chmod 0666 /sys/kernel/tracing/events/power/gpu_frequency/enable
chmod 0666 /sys/kernel/debug/tracing/events/cpufreq_interactive/enable
chmod 0666 /sys/kernel/tracing/events/cpufreq_interactive/enable
chmod 0666 /sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable
diff --git a/cmds/bugreport/bugreport.cpp b/cmds/bugreport/bugreport.cpp
index 917c813..840ae47 100644
--- a/cmds/bugreport/bugreport.cpp
+++ b/cmds/bugreport/bugreport.cpp
@@ -37,7 +37,7 @@
property_set("ctl.start", "dumpstate");
// Socket will not be available until service starts.
- int s;
+ int s = -1;
for (int i = 0; i < 20; i++) {
s = socket_local_client("dumpstate", ANDROID_SOCKET_NAMESPACE_RESERVED,
SOCK_STREAM);
diff --git a/cmds/bugreportz/main.cpp b/cmds/bugreportz/main.cpp
index a3ae1ff..945eae5 100644
--- a/cmds/bugreportz/main.cpp
+++ b/cmds/bugreportz/main.cpp
@@ -72,7 +72,7 @@
property_set("ctl.start", "dumpstatez");
// Socket will not be available until service starts.
- int s;
+ int s = -1;
for (int i = 0; i < 20; i++) {
s = socket_local_client("dumpstate", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
if (s >= 0) break;
diff --git a/cmds/dumpstate/Android.bp b/cmds/dumpstate/Android.bp
index ee32cb4..8d383f5 100644
--- a/cmds/dumpstate/Android.bp
+++ b/cmds/dumpstate/Android.bp
@@ -86,6 +86,7 @@
"libdumpstateaidl",
"libdumpstateutil",
"libdumputils",
+ "libhardware_legacy",
"libhidlbase",
"libhidltransport",
"liblog",
@@ -94,7 +95,6 @@
srcs: [
"DumpstateSectionReporter.cpp",
"DumpstateService.cpp",
- "utils.cpp",
],
static_libs: [
"libincidentcompanion",
@@ -123,7 +123,6 @@
"lsmod",
"lsof",
"netstat",
- "parse_radio_log",
"printenv",
"procrank",
"screencap",
@@ -146,6 +145,12 @@
"tests/dumpstate_test.cpp",
],
static_libs: ["libgmock"],
+ test_config: "dumpstate_test.xml",
+ data: [
+ ":dumpstate_test_fixture",
+ "tests/testdata/**/*",
+ ],
+ test_suites: ["device-tests"],
}
cc_test {
diff --git a/cmds/dumpstate/DumpstateInternal.cpp b/cmds/dumpstate/DumpstateInternal.cpp
index 33e35f7..bbc724c 100644
--- a/cmds/dumpstate/DumpstateInternal.cpp
+++ b/cmds/dumpstate/DumpstateInternal.cpp
@@ -68,7 +68,8 @@
}
static const std::vector<std::string> group_names{
- "log", "sdcard_r", "sdcard_rw", "mount", "inet", "net_bw_stats", "readproc", "bluetooth"};
+ "log", "sdcard_r", "sdcard_rw", "mount", "inet", "net_bw_stats",
+ "readproc", "bluetooth", "wakelock"};
std::vector<gid_t> groups(group_names.size(), 0);
for (size_t i = 0; i < group_names.size(); ++i) {
grp = getgrnam(group_names[i].c_str());
@@ -116,6 +117,11 @@
capdata[cap_syslog_index].effective |= cap_syslog_mask;
}
+ const uint32_t cap_block_suspend_mask = CAP_TO_MASK(CAP_BLOCK_SUSPEND);
+ const uint32_t cap_block_suspend_index = CAP_TO_INDEX(CAP_BLOCK_SUSPEND);
+ capdata[cap_block_suspend_index].permitted |= cap_block_suspend_mask;
+ capdata[cap_block_suspend_index].effective |= cap_block_suspend_mask;
+
if (capset(&capheader, &capdata[0]) != 0) {
MYLOGE("capset({%#x, %#x}) failed: %s\n", capdata[0].effective,
capdata[1].effective, strerror(errno));
diff --git a/cmds/dumpstate/DumpstateUtil.cpp b/cmds/dumpstate/DumpstateUtil.cpp
index 97c8ae2..4b69607 100644
--- a/cmds/dumpstate/DumpstateUtil.cpp
+++ b/cmds/dumpstate/DumpstateUtil.cpp
@@ -378,34 +378,6 @@
return status;
}
-int GetPidByName(const std::string& ps_name) {
- DIR* proc_dir;
- struct dirent* ps;
- unsigned int pid;
- std::string cmdline;
-
- if (!(proc_dir = opendir("/proc"))) {
- MYLOGE("Can't open /proc\n");
- return -1;
- }
-
- while ((ps = readdir(proc_dir))) {
- if (!(pid = atoi(ps->d_name))) {
- continue;
- }
- android::base::ReadFileToString("/proc/" + std::string(ps->d_name) + "/cmdline", &cmdline);
- if (cmdline.find(ps_name) == std::string::npos) {
- continue;
- } else {
- closedir(proc_dir);
- return pid;
- }
- }
- MYLOGE("can't find the pid\n");
- closedir(proc_dir);
- return -1;
-}
-
} // namespace dumpstate
} // namespace os
} // namespace android
diff --git a/cmds/dumpstate/DumpstateUtil.h b/cmds/dumpstate/DumpstateUtil.h
index d75b08c..b7ac25c 100644
--- a/cmds/dumpstate/DumpstateUtil.h
+++ b/cmds/dumpstate/DumpstateUtil.h
@@ -205,12 +205,6 @@
*/
int DumpFileToFd(int fd, const std::string& title, const std::string& path);
-/*
- * Finds the process id by process name.
- * |ps_name| the process name we want to search for
- */
-int GetPidByName(const std::string& ps_name);
-
} // namespace dumpstate
} // namespace os
} // namespace android
diff --git a/cmds/dumpstate/TEST_MAPPING b/cmds/dumpstate/TEST_MAPPING
new file mode 100644
index 0000000..083944f
--- /dev/null
+++ b/cmds/dumpstate/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "dumpstate_test"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index 4c778da..45a143b 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -21,6 +21,8 @@
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
+#include <math.h>
+#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
@@ -31,6 +33,13 @@
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <string.h>
+#include <sys/capability.h>
+#include <sys/inotify.h>
+#include <sys/klog.h>
+#include <time.h>
#include <unistd.h>
#include <chrono>
@@ -55,10 +64,13 @@
#include <android/os/IIncidentCompanion.h>
#include <cutils/native_handle.h>
#include <cutils/properties.h>
+#include <cutils/sockets.h>
#include <debuggerd/client.h>
#include <dumpsys.h>
#include <dumputils/dump_utils.h>
+#include <hardware_legacy/power.h>
#include <hidl/ServiceManagement.h>
+#include <log/log.h>
#include <openssl/sha.h>
#include <private/android_filesystem_config.h>
#include <private/android_logger.h>
@@ -91,9 +103,28 @@
using android::os::dumpstate::CommandOptions;
using android::os::dumpstate::DumpFileToFd;
using android::os::dumpstate::DumpstateSectionReporter;
-using android::os::dumpstate::GetPidByName;
using android::os::dumpstate::PropertiesHelper;
+// Keep in sync with
+// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
+static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
+
+/* Most simple commands have 10 as timeout, so 5 is a good estimate */
+static const int32_t WEIGHT_FILE = 5;
+
+// TODO: temporary variables and functions used during C++ refactoring
+static Dumpstate& ds = Dumpstate::GetInstance();
+static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
+ const CommandOptions& options = CommandOptions::DEFAULT) {
+ return ds.RunCommand(title, full_command, options);
+}
+
+// Reasonable value for max stats.
+static const int STATS_MAX_N_RUNS = 1000;
+static const long STATS_MAX_AVERAGE = 100000;
+
+CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
+
typedef Dumpstate::ConsentCallback::ConsentResult UserConsentResult;
/* read before root is shed */
@@ -130,7 +161,6 @@
static const std::string ANR_FILE_PREFIX = "anr_";
// TODO: temporary variables and functions used during C++ refactoring
-static Dumpstate& ds = Dumpstate::GetInstance();
#define RETURN_IF_USER_DENIED_CONSENT() \
if (ds.IsUserConsentDenied()) { \
@@ -145,6 +175,8 @@
func_ptr(__VA_ARGS__); \
RETURN_IF_USER_DENIED_CONSENT();
+static const char* WAKE_LOCK_NAME = "dumpstate_wakelock";
+
namespace android {
namespace os {
namespace {
@@ -208,10 +240,6 @@
} // namespace os
} // namespace android
-static int RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
- const CommandOptions& options = CommandOptions::DEFAULT) {
- return ds.RunCommand(title, fullCommand, options);
-}
static void RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
const CommandOptions& options = Dumpstate::DEFAULT_DUMPSYS,
long dumpsysTimeoutMs = 0) {
@@ -394,108 +422,6 @@
closedir(d);
}
-
-
-// dump anrd's trace and add to the zip file.
-// 1. check if anrd is running on this device.
-// 2. send a SIGUSR1 to its pid which will dump anrd's trace.
-// 3. wait until the trace generation completes and add to the zip file.
-static bool dump_anrd_trace() {
- unsigned int pid;
- char buf[50], path[PATH_MAX];
- struct dirent *trace;
- struct stat st;
- DIR *trace_dir;
- int retry = 5;
- long max_ctime = 0, old_mtime;
- long long cur_size = 0;
- const char *trace_path = "/data/misc/anrd/";
-
- if (!ds.IsZipping()) {
- MYLOGE("Not dumping anrd trace because it's not a zipped bugreport\n");
- return false;
- }
-
- // find anrd's pid if it is running.
- pid = GetPidByName("/system/bin/anrd");
-
- if (pid > 0) {
- if (stat(trace_path, &st) == 0) {
- old_mtime = st.st_mtime;
- } else {
- MYLOGE("Failed to find: %s\n", trace_path);
- return false;
- }
-
- // send SIGUSR1 to the anrd to generate a trace.
- sprintf(buf, "%u", pid);
- if (RunCommand("ANRD_DUMP", {"kill", "-SIGUSR1", buf},
- CommandOptions::WithTimeout(1).Build())) {
- MYLOGE("anrd signal timed out. Please manually collect trace\n");
- return false;
- }
-
- while (retry-- > 0 && old_mtime == st.st_mtime) {
- sleep(1);
- stat(trace_path, &st);
- }
-
- if (retry < 0 && old_mtime == st.st_mtime) {
- MYLOGE("Failed to stat %s or trace creation timeout\n", trace_path);
- return false;
- }
-
- // identify the trace file by its creation time.
- if (!(trace_dir = opendir(trace_path))) {
- MYLOGE("Can't open trace file under %s\n", trace_path);
- }
- while ((trace = readdir(trace_dir))) {
- if (strcmp(trace->d_name, ".") == 0
- || strcmp(trace->d_name, "..") == 0) {
- continue;
- }
- sprintf(path, "%s%s", trace_path, trace->d_name);
- if (stat(path, &st) == 0) {
- if (st.st_ctime > max_ctime) {
- max_ctime = st.st_ctime;
- sprintf(buf, "%s", trace->d_name);
- }
- }
- }
- closedir(trace_dir);
-
- // Wait until the dump completes by checking the size of the trace.
- if (max_ctime > 0) {
- sprintf(path, "%s%s", trace_path, buf);
- while(true) {
- sleep(1);
- if (stat(path, &st) == 0) {
- if (st.st_size == cur_size) {
- break;
- } else if (st.st_size > cur_size) {
- cur_size = st.st_size;
- } else {
- return false;
- }
- } else {
- MYLOGE("Cant stat() %s anymore\n", path);
- return false;
- }
- }
- // Add to the zip file.
- if (!ds.AddZipEntry("anrd_trace.txt", path)) {
- MYLOGE("Unable to add anrd_trace file %s to zip file\n", path);
- } else {
- android::os::UnlinkAndLogOnError(path);
- return true;
- }
- } else {
- MYLOGE("Can't stats any trace file under %s\n", trace_path);
- }
- }
- return false;
-}
-
static bool skip_not_stat(const char *path) {
static const char stat[] = "/stat";
size_t len = strlen(path);
@@ -1232,7 +1158,7 @@
}
DurationReporter duration_reporter("DUMP HALS");
RunCommand("HARDWARE HALS", {"lshal", "-lVSietrpc", "--types=b,c,l,z"},
- CommandOptions::WithTimeout(2).AsRootIfAvailable().Build());
+ CommandOptions::WithTimeout(10).AsRootIfAvailable().Build());
using android::hidl::manager::V1_0::IServiceManager;
using android::hardware::defaultServiceManager;
@@ -1348,7 +1274,7 @@
/* Dump Bluetooth HCI logs */
ds.AddDir("/data/misc/bluetooth/logs", true);
- if (!ds.do_early_screenshot_) {
+ if (ds.options_->do_fb && !ds.do_early_screenshot_) {
MYLOGI("taking late screenshot\n");
ds.TakeScreenshot();
}
@@ -1387,8 +1313,6 @@
RunCommand("FILESYSTEMS & FREE SPACE", {"df"});
- RunCommand("LAST RADIO LOG", {"parse_radio_log", "/proc/last_radio_log"});
-
/* Binder state is expensive to look at as it uses a lot of memory. */
DumpFile("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log");
DumpFile("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log");
@@ -1500,9 +1424,6 @@
* with the caller.
*/
static Dumpstate::RunStatus DumpstateDefault() {
- // Try to dump anrd trace if the daemon is running.
- dump_anrd_trace();
-
// Invoking the following dumpsys calls before DumpTraces() to try and
// keep the system stats as close to its initial state as possible.
RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunDumpsysCritical);
@@ -1864,22 +1785,21 @@
static void ShowUsage() {
fprintf(stderr,
- "usage: dumpstate [-h] [-b soundfile] [-e soundfile] [-o file] [-d] [-p] "
+ "usage: dumpstate [-h] [-b soundfile] [-e soundfile] [-d] [-p] "
"[-z]] [-s] [-S] [-q] [-B] [-P] [-R] [-V version]\n"
" -h: display this help message\n"
" -b: play sound file instead of vibrate, at beginning of job\n"
" -e: play sound file instead of vibrate, at end of job\n"
- " -o: write to file (instead of stdout)\n"
- " -d: append date to filename (requires -o)\n"
- " -p: capture screenshot to filename.png (requires -o)\n"
- " -z: generate zipped file (requires -o)\n"
+ " -d: append date to filename\n"
+ " -p: capture screenshot to filename.png\n"
+ " -z: generate zipped file\n"
" -s: write output to control socket (for init)\n"
- " -S: write file location to control socket (for init; requires -o and -z)\n"
+ " -S: write file location to control socket (for init; requires -z)\n"
" -q: disable vibrate\n"
- " -B: send broadcast when finished (requires -o)\n"
+ " -B: send broadcast when finished\n"
" -P: send broadcast when started and update system properties on "
- "progress (requires -o and -B)\n"
- " -R: take bugreport in remote mode (requires -o, -z, -d and -B, "
+ "progress (requires -B)\n"
+ " -R: take bugreport in remote mode (requires -z, -d and -B, "
"shouldn't be used with -P)\n"
" -w: start binder service and make it wait for a call to startBugreport\n"
" -v: prints the dumpstate header and exit\n");
@@ -2363,7 +2283,6 @@
}
}
- // TODO: use helper function to convert argv into a string
for (int i = 0; i < argc; i++) {
args += argv[i];
if (i < argc - 1) {
@@ -2514,6 +2433,13 @@
MYLOGI("begin\n");
+ if (acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME) < 0) {
+ MYLOGE("Failed to acquire wake lock: %s\n", strerror(errno));
+ } else {
+ // Wake lock will be released automatically on process death
+ MYLOGD("Wake lock acquired.\n");
+ }
+
register_sig_handler();
// TODO(b/111441001): maybe skip if already started?
@@ -2587,13 +2513,8 @@
}
if (options_->do_fb && do_early_screenshot_) {
- if (screenshot_path_.empty()) {
- // should not have happened
- MYLOGE("INTERNAL ERROR: skipping early screenshot because path was not set\n");
- } else {
- MYLOGI("taking early screenshot\n");
- TakeScreenshot();
- }
+ MYLOGI("taking early screenshot\n");
+ TakeScreenshot();
}
if (options_->do_zip_file && zip_file != nullptr) {
@@ -2649,7 +2570,7 @@
// Dump state for the default case. This also drops root.
RunStatus s = DumpstateDefault();
if (s != RunStatus::OK) {
- if (s == RunStatus::USER_CONSENT_TIMED_OUT) {
+ if (s == RunStatus::USER_CONSENT_DENIED) {
HandleUserConsentDenied();
}
return s;
@@ -2845,3 +2766,947 @@
exit(2);
}
}
+
+// TODO(111441001): Default DumpOptions to sensible values.
+Dumpstate::Dumpstate(const std::string& version)
+ : pid_(getpid()),
+ options_(new Dumpstate::DumpOptions()),
+ version_(version),
+ now_(time(nullptr)) {
+}
+
+Dumpstate& Dumpstate::GetInstance() {
+ static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
+ return singleton_;
+}
+
+DurationReporter::DurationReporter(const std::string& title, bool logcat_only)
+ : title_(title), logcat_only_(logcat_only) {
+ if (!title_.empty()) {
+ started_ = Nanotime();
+ }
+}
+
+DurationReporter::~DurationReporter() {
+ if (!title_.empty()) {
+ float elapsed = (float)(Nanotime() - started_) / NANOS_PER_SEC;
+ if (elapsed < .5f) {
+ return;
+ }
+ MYLOGD("Duration of '%s': %.2fs\n", title_.c_str(), elapsed);
+ if (logcat_only_) {
+ return;
+ }
+ // Use "Yoda grammar" to make it easier to grep|sort sections.
+ printf("------ %.3fs was the duration of '%s' ------\n", elapsed, title_.c_str());
+ }
+}
+
+const int32_t Progress::kDefaultMax = 5000;
+
+Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
+}
+
+Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
+ : Progress(initial_max, growth_factor, "") {
+ progress_ = progress;
+}
+
+Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
+ : initial_max_(initial_max),
+ progress_(0),
+ max_(initial_max),
+ growth_factor_(growth_factor),
+ n_runs_(0),
+ average_max_(0),
+ path_(path) {
+ if (!path_.empty()) {
+ Load();
+ }
+}
+
+void Progress::Load() {
+ MYLOGD("Loading stats from %s\n", path_.c_str());
+ std::string content;
+ if (!android::base::ReadFileToString(path_, &content)) {
+ MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
+ return;
+ }
+ if (content.empty()) {
+ MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
+ return;
+ }
+ std::vector<std::string> lines = android::base::Split(content, "\n");
+
+ if (lines.size() < 1) {
+ MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
+ (int)lines.size(), max_);
+ return;
+ }
+ char* ptr;
+ n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
+ average_max_ = strtol(ptr, nullptr, 10);
+ if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
+ average_max_ > STATS_MAX_AVERAGE) {
+ MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
+ initial_max_ = Progress::kDefaultMax;
+ } else {
+ initial_max_ = average_max_;
+ }
+ max_ = initial_max_;
+
+ MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
+}
+
+void Progress::Save() {
+ int32_t total = n_runs_ * average_max_ + progress_;
+ int32_t runs = n_runs_ + 1;
+ int32_t average = floor(((float)total) / runs);
+ MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
+ path_.c_str());
+ if (path_.empty()) {
+ return;
+ }
+
+ std::string content = android::base::StringPrintf("%d %d\n", runs, average);
+ if (!android::base::WriteStringToFile(content, path_)) {
+ MYLOGE("Could not save stats on %s\n", path_.c_str());
+ }
+}
+
+int32_t Progress::Get() const {
+ return progress_;
+}
+
+bool Progress::Inc(int32_t delta_sec) {
+ bool changed = false;
+ if (delta_sec >= 0) {
+ progress_ += delta_sec;
+ if (progress_ > max_) {
+ int32_t old_max = max_;
+ max_ = floor((float)progress_ * growth_factor_);
+ MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+int32_t Progress::GetMax() const {
+ return max_;
+}
+
+int32_t Progress::GetInitialMax() const {
+ return initial_max_;
+}
+
+void Progress::Dump(int fd, const std::string& prefix) const {
+ const char* pr = prefix.c_str();
+ dprintf(fd, "%sprogress: %d\n", pr, progress_);
+ dprintf(fd, "%smax: %d\n", pr, max_);
+ dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
+ dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
+ dprintf(fd, "%spath: %s\n", pr, path_.c_str());
+ dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
+ dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
+}
+
+bool Dumpstate::IsZipping() const {
+ return zip_writer_ != nullptr;
+}
+
+std::string Dumpstate::GetPath(const std::string& suffix) const {
+ return GetPath(bugreport_internal_dir_, suffix);
+}
+
+std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
+ return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
+ name_.c_str(), suffix.c_str());
+}
+
+void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
+ progress_ = std::move(progress);
+}
+
+void for_each_userid(void (*func)(int), const char *header) {
+ std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
+ "for_each_userid(%s)", header);
+ DurationReporter duration_reporter(title);
+ if (PropertiesHelper::IsDryRun()) return;
+
+ DIR *d;
+ struct dirent *de;
+
+ if (header) printf("\n------ %s ------\n", header);
+ func(0);
+
+ if (!(d = opendir("/data/system/users"))) {
+ printf("Failed to open /data/system/users (%s)\n", strerror(errno));
+ return;
+ }
+
+ while ((de = readdir(d))) {
+ int userid;
+ if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
+ continue;
+ }
+ func(userid);
+ }
+
+ closedir(d);
+}
+
+static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
+ DIR *d;
+ struct dirent *de;
+
+ if (!(d = opendir("/proc"))) {
+ printf("Failed to open /proc (%s)\n", strerror(errno));
+ return;
+ }
+
+ if (header) printf("\n------ %s ------\n", header);
+ while ((de = readdir(d))) {
+ if (ds.IsUserConsentDenied()) {
+ MYLOGE(
+ "Returning early because user denied consent to share bugreport with calling app.");
+ closedir(d);
+ return;
+ }
+ int pid;
+ int fd;
+ char cmdpath[255];
+ char cmdline[255];
+
+ if (!(pid = atoi(de->d_name))) {
+ continue;
+ }
+
+ memset(cmdline, 0, sizeof(cmdline));
+
+ snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
+ if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
+ TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
+ close(fd);
+ if (cmdline[0]) {
+ helper(pid, cmdline, arg);
+ continue;
+ }
+ }
+
+ // if no cmdline, a kernel thread has comm
+ snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
+ if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
+ TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
+ close(fd);
+ if (cmdline[1]) {
+ cmdline[0] = '[';
+ size_t len = strcspn(cmdline, "\f\b\r\n");
+ cmdline[len] = ']';
+ cmdline[len+1] = '\0';
+ }
+ }
+ if (!cmdline[0]) {
+ strcpy(cmdline, "N/A");
+ }
+ helper(pid, cmdline, arg);
+ }
+
+ closedir(d);
+}
+
+static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
+ for_each_pid_func *func = (for_each_pid_func*) arg;
+ func(pid, cmdline);
+}
+
+void for_each_pid(for_each_pid_func func, const char *header) {
+ std::string title = header == nullptr ? "for_each_pid"
+ : android::base::StringPrintf("for_each_pid(%s)", header);
+ DurationReporter duration_reporter(title);
+ if (PropertiesHelper::IsDryRun()) return;
+
+ __for_each_pid(for_each_pid_helper, header, (void *) func);
+}
+
+static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
+ DIR *d;
+ struct dirent *de;
+ char taskpath[255];
+ for_each_tid_func *func = (for_each_tid_func *) arg;
+
+ snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
+
+ if (!(d = opendir(taskpath))) {
+ printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
+ return;
+ }
+
+ func(pid, pid, cmdline);
+
+ while ((de = readdir(d))) {
+ if (ds.IsUserConsentDenied()) {
+ MYLOGE(
+ "Returning early because user denied consent to share bugreport with calling app.");
+ closedir(d);
+ return;
+ }
+ int tid;
+ int fd;
+ char commpath[255];
+ char comm[255];
+
+ if (!(tid = atoi(de->d_name))) {
+ continue;
+ }
+
+ if (tid == pid)
+ continue;
+
+ snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
+ memset(comm, 0, sizeof(comm));
+ if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
+ strcpy(comm, "N/A");
+ } else {
+ char *c;
+ TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
+ close(fd);
+
+ c = strrchr(comm, '\n');
+ if (c) {
+ *c = '\0';
+ }
+ }
+ func(pid, tid, comm);
+ }
+
+ closedir(d);
+}
+
+void for_each_tid(for_each_tid_func func, const char *header) {
+ std::string title = header == nullptr ? "for_each_tid"
+ : android::base::StringPrintf("for_each_tid(%s)", header);
+ DurationReporter duration_reporter(title);
+
+ if (PropertiesHelper::IsDryRun()) return;
+
+ __for_each_pid(for_each_tid_helper, header, (void *) func);
+}
+
+void show_wchan(int pid, int tid, const char *name) {
+ if (PropertiesHelper::IsDryRun()) return;
+
+ char path[255];
+ char buffer[255];
+ int fd, ret, save_errno;
+ char name_buffer[255];
+
+ memset(buffer, 0, sizeof(buffer));
+
+ snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
+ if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
+ printf("Failed to open '%s' (%s)\n", path, strerror(errno));
+ return;
+ }
+
+ ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
+ save_errno = errno;
+ close(fd);
+
+ if (ret < 0) {
+ printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
+ return;
+ }
+
+ snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
+ pid == tid ? 0 : 3, "", name);
+
+ printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
+
+ return;
+}
+
+// print time in centiseconds
+static void snprcent(char *buffer, size_t len, size_t spc,
+ unsigned long long time) {
+ static long hz; // cache discovered hz
+
+ if (hz <= 0) {
+ hz = sysconf(_SC_CLK_TCK);
+ if (hz <= 0) {
+ hz = 1000;
+ }
+ }
+
+ // convert to centiseconds
+ time = (time * 100 + (hz / 2)) / hz;
+
+ char str[16];
+
+ snprintf(str, sizeof(str), " %llu.%02u",
+ time / 100, (unsigned)(time % 100));
+ size_t offset = strlen(buffer);
+ snprintf(buffer + offset, (len > offset) ? len - offset : 0,
+ "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
+}
+
+// print permille as a percent
+static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
+ char str[16];
+
+ snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
+ size_t offset = strlen(buffer);
+ snprintf(buffer + offset, (len > offset) ? len - offset : 0,
+ "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
+}
+
+void show_showtime(int pid, const char *name) {
+ if (PropertiesHelper::IsDryRun()) return;
+
+ char path[255];
+ char buffer[1023];
+ int fd, ret, save_errno;
+
+ memset(buffer, 0, sizeof(buffer));
+
+ snprintf(path, sizeof(path), "/proc/%d/stat", pid);
+ if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
+ printf("Failed to open '%s' (%s)\n", path, strerror(errno));
+ return;
+ }
+
+ ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
+ save_errno = errno;
+ close(fd);
+
+ if (ret < 0) {
+ printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
+ return;
+ }
+
+ // field 14 is utime
+ // field 15 is stime
+ // field 42 is iotime
+ unsigned long long utime = 0, stime = 0, iotime = 0;
+ if (sscanf(buffer,
+ "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
+ "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
+ "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
+ "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
+ &utime, &stime, &iotime) != 3) {
+ return;
+ }
+
+ unsigned long long total = utime + stime;
+ if (!total) {
+ return;
+ }
+
+ unsigned permille = (iotime * 1000 + (total / 2)) / total;
+ if (permille > 1000) {
+ permille = 1000;
+ }
+
+ // try to beautify and stabilize columns at <80 characters
+ snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
+ if ((name[0] != '[') || utime) {
+ snprcent(buffer, sizeof(buffer), 57, utime);
+ }
+ snprcent(buffer, sizeof(buffer), 65, stime);
+ if ((name[0] != '[') || iotime) {
+ snprcent(buffer, sizeof(buffer), 73, iotime);
+ }
+ if (iotime) {
+ snprdec(buffer, sizeof(buffer), 79, permille);
+ }
+ puts(buffer); // adds a trailing newline
+
+ return;
+}
+
+void do_dmesg() {
+ const char *title = "KERNEL LOG (dmesg)";
+ DurationReporter duration_reporter(title);
+ printf("------ %s ------\n", title);
+
+ if (PropertiesHelper::IsDryRun()) return;
+
+ /* Get size of kernel buffer */
+ int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
+ if (size <= 0) {
+ printf("Unexpected klogctl return value: %d\n\n", size);
+ return;
+ }
+ char *buf = (char *) malloc(size + 1);
+ if (buf == nullptr) {
+ printf("memory allocation failed\n\n");
+ return;
+ }
+ int retval = klogctl(KLOG_READ_ALL, buf, size);
+ if (retval < 0) {
+ printf("klogctl failure\n\n");
+ free(buf);
+ return;
+ }
+ buf[retval] = '\0';
+ printf("%s\n\n", buf);
+ free(buf);
+ return;
+}
+
+void do_showmap(int pid, const char *name) {
+ char title[255];
+ char arg[255];
+
+ snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
+ snprintf(arg, sizeof(arg), "%d", pid);
+ RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
+}
+
+int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
+ DurationReporter duration_reporter(title);
+
+ int status = DumpFileToFd(STDOUT_FILENO, title, path);
+
+ UpdateProgress(WEIGHT_FILE);
+
+ return status;
+}
+
+int read_file_as_long(const char *path, long int *output) {
+ int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
+ if (fd < 0) {
+ int err = errno;
+ MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
+ return -1;
+ }
+ char buffer[50];
+ ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
+ if (bytes_read == -1) {
+ MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
+ return -2;
+ }
+ if (bytes_read == 0) {
+ MYLOGE("File %s is empty\n", path);
+ return -3;
+ }
+ *output = atoi(buffer);
+ return 0;
+}
+
+/* calls skip to gate calling dump_from_fd recursively
+ * in the specified directory. dump_from_fd defaults to
+ * dump_file_from_fd above when set to NULL. skip defaults
+ * to false when set to NULL. dump_from_fd will always be
+ * called with title NULL.
+ */
+int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
+ int (*dump_from_fd)(const char* title, const char* path, int fd)) {
+ DurationReporter duration_reporter(title);
+ DIR *dirp;
+ struct dirent *d;
+ char *newpath = nullptr;
+ const char *slash = "/";
+ int retval = 0;
+
+ if (!title.empty()) {
+ printf("------ %s (%s) ------\n", title.c_str(), dir);
+ }
+ if (PropertiesHelper::IsDryRun()) return 0;
+
+ if (dir[strlen(dir) - 1] == '/') {
+ ++slash;
+ }
+ dirp = opendir(dir);
+ if (dirp == nullptr) {
+ retval = -errno;
+ MYLOGE("%s: %s\n", dir, strerror(errno));
+ return retval;
+ }
+
+ if (!dump_from_fd) {
+ dump_from_fd = dump_file_from_fd;
+ }
+ for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
+ if ((d->d_name[0] == '.')
+ && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
+ || (d->d_name[1] == '\0'))) {
+ continue;
+ }
+ asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
+ (d->d_type == DT_DIR) ? "/" : "");
+ if (!newpath) {
+ retval = -errno;
+ continue;
+ }
+ if (skip && (*skip)(newpath)) {
+ continue;
+ }
+ if (d->d_type == DT_DIR) {
+ int ret = dump_files("", newpath, skip, dump_from_fd);
+ if (ret < 0) {
+ retval = ret;
+ }
+ continue;
+ }
+ android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
+ if (fd.get() < 0) {
+ retval = -1;
+ printf("*** %s: %s\n", newpath, strerror(errno));
+ continue;
+ }
+ (*dump_from_fd)(nullptr, newpath, fd.get());
+ }
+ closedir(dirp);
+ if (!title.empty()) {
+ printf("\n");
+ }
+ return retval;
+}
+
+/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
+ * it's possible to avoid issues where opening the file itself can get
+ * stuck.
+ */
+int dump_file_from_fd(const char *title, const char *path, int fd) {
+ if (PropertiesHelper::IsDryRun()) return 0;
+
+ int flags = fcntl(fd, F_GETFL);
+ if (flags == -1) {
+ printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
+ return -1;
+ } else if (!(flags & O_NONBLOCK)) {
+ printf("*** %s: fd must have O_NONBLOCK set.\n", path);
+ return -1;
+ }
+ return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
+}
+
+int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
+ const CommandOptions& options) {
+ DurationReporter duration_reporter(title);
+
+ int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
+
+ /* TODO: for now we're simplifying the progress calculation by using the
+ * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
+ * where its weight should be much higher proportionally to its timeout.
+ * Ideally, it should use a options.EstimatedDuration() instead...*/
+ UpdateProgress(options.Timeout());
+
+ return status;
+}
+
+void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
+ const CommandOptions& options, long dumpsysTimeoutMs) {
+ long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
+ std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
+ dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
+ RunCommand(title, dumpsys, options);
+}
+
+int open_socket(const char *service) {
+ int s = android_get_control_socket(service);
+ if (s < 0) {
+ MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
+ return -1;
+ }
+ fcntl(s, F_SETFD, FD_CLOEXEC);
+
+ // Set backlog to 0 to make sure that queue size will be minimum.
+ // In Linux, because the minimum queue will be 1, connect() will be blocked
+ // if the other clients already called connect() and the connection request was not accepted.
+ if (listen(s, 0) < 0) {
+ MYLOGE("listen(control socket): %s\n", strerror(errno));
+ return -1;
+ }
+
+ struct sockaddr addr;
+ socklen_t alen = sizeof(addr);
+ int fd = accept(s, &addr, &alen);
+
+ // Close socket just after accept(), to make sure that connect() by client will get error
+ // when the socket is used by the other services.
+ // There is still a race condition possibility between accept and close, but there is no way
+ // to close-on-accept atomically.
+ // See detail; b/123306389#comment25
+ close(s);
+
+ if (fd < 0) {
+ MYLOGE("accept(control socket): %s\n", strerror(errno));
+ return -1;
+ }
+
+ return fd;
+}
+
+/* redirect output to a service control socket */
+bool redirect_to_socket(FILE* redirect, const char* service) {
+ int fd = open_socket(service);
+ if (fd == -1) {
+ return false;
+ }
+ fflush(redirect);
+ // TODO: handle dup2 failure
+ TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
+ close(fd);
+ return true;
+}
+
+// TODO: should call is_valid_output_file and/or be merged into it.
+void create_parent_dirs(const char *path) {
+ char *chp = const_cast<char *> (path);
+
+ /* skip initial slash */
+ if (chp[0] == '/')
+ chp++;
+
+ /* create leading directories, if necessary */
+ struct stat dir_stat;
+ while (chp && chp[0]) {
+ chp = strchr(chp, '/');
+ if (chp) {
+ *chp = 0;
+ if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
+ MYLOGI("Creating directory %s\n", path);
+ if (mkdir(path, 0770)) { /* drwxrwx--- */
+ MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
+ } else if (chown(path, AID_SHELL, AID_SHELL)) {
+ MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
+ }
+ }
+ *chp++ = '/';
+ }
+ }
+}
+
+bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
+ create_parent_dirs(path);
+
+ int fd = TEMP_FAILURE_RETRY(open(path,
+ O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
+ if (fd < 0) {
+ MYLOGE("%s: %s\n", path, strerror(errno));
+ return false;
+ }
+
+ TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
+ close(fd);
+ return true;
+}
+
+bool redirect_to_file(FILE* redirect, char* path) {
+ return _redirect_to_file(redirect, path, O_TRUNC);
+}
+
+bool redirect_to_existing_file(FILE* redirect, char* path) {
+ return _redirect_to_file(redirect, path, O_APPEND);
+}
+
+void dump_route_tables() {
+ DurationReporter duration_reporter("DUMP ROUTE TABLES");
+ if (PropertiesHelper::IsDryRun()) return;
+ const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
+ ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
+ FILE* fp = fopen(RT_TABLES_PATH, "re");
+ if (!fp) {
+ printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
+ return;
+ }
+ char table[16];
+ // Each line has an integer (the table number), a space, and a string (the table name). We only
+ // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
+ // Add a fixed max limit so this doesn't go awry.
+ for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
+ RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
+ RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
+ }
+ fclose(fp);
+}
+
+// TODO: make this function thread safe if sections are generated in parallel.
+void Dumpstate::UpdateProgress(int32_t delta_sec) {
+ if (progress_ == nullptr) {
+ MYLOGE("UpdateProgress: progress_ not set\n");
+ return;
+ }
+
+ // Always update progess so stats can be tuned...
+ bool max_changed = progress_->Inc(delta_sec);
+
+ // ...but only notifiy listeners when necessary.
+ if (!options_->do_progress_updates) return;
+
+ int progress = progress_->Get();
+ int max = progress_->GetMax();
+
+ // adjusts max on the fly
+ if (max_changed && listener_ != nullptr) {
+ listener_->onMaxProgressUpdated(max);
+ }
+
+ int32_t last_update_delta = progress - last_updated_progress_;
+ if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
+ return;
+ }
+ last_updated_progress_ = progress;
+
+ if (control_socket_fd_ >= 0) {
+ dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
+ fsync(control_socket_fd_);
+ }
+
+ int percent = 100 * progress / max;
+ if (listener_ != nullptr) {
+ if (percent % 5 == 0) {
+ // We don't want to spam logcat, so only log multiples of 5.
+ MYLOGD("Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(), progress, max,
+ percent);
+ } else {
+ // stderr is ignored on normal invocations, but useful when calling
+ // /system/bin/dumpstate directly for debuggging.
+ fprintf(stderr, "Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(),
+ progress, max, percent);
+ }
+ // TODO(b/111441001): Remove in favor of onProgress
+ listener_->onProgressUpdated(progress);
+
+ listener_->onProgress(percent);
+ }
+}
+
+void Dumpstate::TakeScreenshot(const std::string& path) {
+ const std::string& real_path = path.empty() ? screenshot_path_ : path;
+ int status =
+ RunCommand("", {"/system/bin/screencap", "-p", real_path},
+ CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
+ if (status == 0) {
+ MYLOGD("Screenshot saved on %s\n", real_path.c_str());
+ } else {
+ MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
+ }
+}
+
+bool is_dir(const char* pathname) {
+ struct stat info;
+ if (stat(pathname, &info) == -1) {
+ return false;
+ }
+ return S_ISDIR(info.st_mode);
+}
+
+time_t get_mtime(int fd, time_t default_mtime) {
+ struct stat info;
+ if (fstat(fd, &info) == -1) {
+ return default_mtime;
+ }
+ return info.st_mtime;
+}
+
+void dump_emmc_ecsd(const char *ext_csd_path) {
+ // List of interesting offsets
+ struct hex {
+ char str[2];
+ };
+ static const size_t EXT_CSD_REV = 192 * sizeof(hex);
+ static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
+ static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
+ static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
+
+ std::string buffer;
+ if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
+ return;
+ }
+
+ printf("------ %s Extended CSD ------\n", ext_csd_path);
+
+ if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
+ printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
+ return;
+ }
+
+ int ext_csd_rev = 0;
+ std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
+ if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
+ printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
+ return;
+ }
+
+ static const char *ver_str[] = {
+ "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
+ };
+ printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
+ (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
+ : "Unknown");
+ if (ext_csd_rev < 7) {
+ printf("\n");
+ return;
+ }
+
+ if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
+ printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
+ return;
+ }
+
+ int ext_pre_eol_info = 0;
+ sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
+ if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
+ printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
+ return;
+ }
+
+ static const char *eol_str[] = {
+ "Undefined",
+ "Normal",
+ "Warning (consumed 80% of reserve)",
+ "Urgent (consumed 90% of reserve)"
+ };
+ printf(
+ "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
+ eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
+ : 0]);
+
+ for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
+ lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
+ lifetime += sizeof(hex)) {
+ int ext_device_life_time_est;
+ static const char *est_str[] = {
+ "Undefined",
+ "0-10% of device lifetime used",
+ "10-20% of device lifetime used",
+ "20-30% of device lifetime used",
+ "30-40% of device lifetime used",
+ "40-50% of device lifetime used",
+ "50-60% of device lifetime used",
+ "60-70% of device lifetime used",
+ "70-80% of device lifetime used",
+ "80-90% of device lifetime used",
+ "90-100% of device lifetime used",
+ "Exceeded the maximum estimated device lifetime",
+ };
+
+ if (buffer.length() < (lifetime + sizeof(hex))) {
+ printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
+ break;
+ }
+
+ ext_device_life_time_est = 0;
+ sub = buffer.substr(lifetime, sizeof(hex));
+ if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
+ printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
+ (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
+ sub.c_str());
+ continue;
+ }
+ printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
+ (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
+ ext_device_life_time_est,
+ est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
+ ? ext_device_life_time_est
+ : 0]);
+ }
+
+ printf("\n");
+}
+
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index d02ec75..ae6a721 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -441,8 +441,7 @@
// Full path of the bugreport file, be it zip or text, inside bugreport_internal_dir_.
std::string path_;
- // TODO: If temporary this should be removed at the end.
- // Full path of the temporary file containing the screenshot (when requested).
+ // Full path of the file containing the screenshot (when requested).
std::string screenshot_path_;
// Pointer to the zipped file.
diff --git a/cmds/dumpstate/dumpstate_test.xml b/cmds/dumpstate/dumpstate_test.xml
new file mode 100644
index 0000000..e4e4a30
--- /dev/null
+++ b/cmds/dumpstate/dumpstate_test.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<configuration description="Config for dumpstate_test">
+ <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+ <option name="cleanup" value="true" />
+ <option name="push" value="dumpstate_test->/data/local/tmp/dumpstate_test" />
+ </target_preparer>
+ <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"/>
+ <option name="test-suite-tag" value="apct" />
+ <test class="com.android.tradefed.testtype.GTest" >
+ <option name="native-test-device-path" value="/data/local/tmp" />
+ <option name="file-exclusion-filter-regex" value=".*/dumpstate_test_fixture" />
+ <option name="file-exclusion-filter-regex" value=".*/tests/.*" />
+ <option name="module-name" value="dumpstate_test" />
+ </test>
+</configuration>
diff --git a/cmds/dumpstate/tests/dumpstate_smoke_test.cpp b/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
index fc3642c..f7acaf1 100644
--- a/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
+++ b/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
@@ -14,20 +14,21 @@
* limitations under the License.
*/
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include <fcntl.h>
-#include <libgen.h>
-
#include <android-base/file.h>
#include <android/os/BnDumpstate.h>
#include <android/os/BnDumpstateListener.h>
#include <binder/IServiceManager.h>
#include <binder/ProcessState.h>
#include <cutils/properties.h>
+#include <fcntl.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <libgen.h>
#include <ziparchive/zip_archive.h>
+#include <fstream>
+#include <regex>
+
#include "dumpstate.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
@@ -44,6 +45,11 @@
namespace {
+struct SectionInfo {
+ std::string name;
+ int32_t size_bytes;
+};
+
sp<IDumpstate> GetDumpstateService() {
return android::interface_cast<IDumpstate>(
android::defaultServiceManager()->getService(String16("dumpstate")));
@@ -55,14 +61,79 @@
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
}
-} // namespace
+void GetEntry(const ZipArchiveHandle archive, const std::string_view entry_name, ZipEntry* data) {
+ int32_t e = FindEntry(archive, entry_name, data);
+ EXPECT_EQ(e, 0) << ErrorCodeString(e) << " entry name: " << entry_name;
+}
-struct SectionInfo {
- std::string name;
- status_t status;
- int32_t size_bytes;
- int32_t duration_ms;
-};
+// Extracts the main bugreport txt from the given archive and writes into output_fd.
+void ExtractBugreport(const ZipArchiveHandle* handle, int output_fd) {
+ // Read contents of main_entry.txt which is a single line indicating the name of the zip entry
+ // that contains the main bugreport txt.
+ ZipEntry main_entry;
+ GetEntry(*handle, "main_entry.txt", &main_entry);
+ std::string bugreport_txt_name;
+ bugreport_txt_name.resize(main_entry.uncompressed_length);
+ ExtractToMemory(*handle, &main_entry, reinterpret_cast<uint8_t*>(bugreport_txt_name.data()),
+ main_entry.uncompressed_length);
+
+ // Read the main bugreport txt and extract to output_fd.
+ ZipEntry entry;
+ GetEntry(*handle, bugreport_txt_name, &entry);
+ ExtractEntryToFile(*handle, &entry, output_fd);
+}
+
+bool IsSectionStart(const std::string& line, std::string* section_name) {
+ static const std::regex kSectionStart = std::regex{"DUMP OF SERVICE (.*):"};
+ std::smatch match;
+ if (std::regex_match(line, match, kSectionStart)) {
+ *section_name = match.str(1);
+ return true;
+ }
+ return false;
+}
+
+bool IsSectionEnd(const std::string& line) {
+ // Not all lines that contain "was the duration of" is a section end, but all section ends do
+ // contain "was the duration of". The disambiguation can be done by the caller.
+ return (line.find("was the duration of") != std::string::npos);
+}
+
+// Extracts the zipped bugreport and identifies the sections.
+void ParseSections(const std::string& zip_path, std::vector<SectionInfo>* sections) {
+ // Open the archive
+ ZipArchiveHandle handle;
+ ASSERT_EQ(OpenArchive(zip_path.c_str(), &handle), 0);
+
+ // Extract the main entry to a temp file
+ TemporaryFile tmp_binary;
+ ASSERT_NE(-1, tmp_binary.fd);
+ ExtractBugreport(&handle, tmp_binary.fd);
+
+ // Read line by line and identify sections
+ std::ifstream ifs(tmp_binary.path, std::ifstream::in);
+ std::string line;
+ int section_bytes = 0;
+ std::string current_section_name;
+ while (std::getline(ifs, line)) {
+ std::string section_name;
+ if (IsSectionStart(line, §ion_name)) {
+ section_bytes = 0;
+ current_section_name = section_name;
+ } else if (IsSectionEnd(line)) {
+ if (!current_section_name.empty()) {
+ sections->push_back({current_section_name, section_bytes});
+ }
+ current_section_name = "";
+ } else if (!current_section_name.empty()) {
+ section_bytes += line.length();
+ }
+ }
+
+ CloseArchive(handle);
+}
+
+} // namespace
/**
* Listens to bugreport progress and updates the user by writing the progress to STDOUT. All the
@@ -107,11 +178,11 @@
return binder::Status::ok();
}
- binder::Status onSectionComplete(const ::std::string& name, int32_t status, int32_t size_bytes,
- int32_t duration_ms) override {
+ binder::Status onSectionComplete(const ::std::string& name, int32_t, int32_t size_bytes,
+ int32_t) override {
std::lock_guard<std::mutex> lock(lock_);
if (sections_.get() != nullptr) {
- sections_->push_back({name, status, size_bytes, duration_ms});
+ sections_->push_back({name, size_bytes});
}
return binder::Status::ok();
}
@@ -208,29 +279,30 @@
void FileExists(const char* filename, uint32_t minsize, uint32_t maxsize) {
ZipEntry entry;
- EXPECT_EQ(FindEntry(handle, ZipString(filename), &entry), 0);
+ GetEntry(handle, filename, &entry);
EXPECT_GT(entry.uncompressed_length, minsize);
EXPECT_LT(entry.uncompressed_length, maxsize);
}
};
TEST_F(ZippedBugReportContentsTest, ContainsMainEntry) {
- ZipEntry mainEntryLoc;
+ ZipEntry main_entry;
// contains main entry name file
- EXPECT_EQ(FindEntry(handle, ZipString("main_entry.txt"), &mainEntryLoc), 0);
+ GetEntry(handle, "main_entry.txt", &main_entry);
- char* buf = new char[mainEntryLoc.uncompressed_length];
- ExtractToMemory(handle, &mainEntryLoc, (uint8_t*)buf, mainEntryLoc.uncompressed_length);
- delete[] buf;
+ std::string bugreport_txt_name;
+ bugreport_txt_name.resize(main_entry.uncompressed_length);
+ ExtractToMemory(handle, &main_entry, reinterpret_cast<uint8_t*>(bugreport_txt_name.data()),
+ main_entry.uncompressed_length);
// contains main entry file
- FileExists(buf, 1000000U, 50000000U);
+ FileExists(bugreport_txt_name.c_str(), 1000000U, 50000000U);
}
TEST_F(ZippedBugReportContentsTest, ContainsVersion) {
ZipEntry entry;
// contains main entry name file
- EXPECT_EQ(FindEntry(handle, ZipString("version.txt"), &entry), 0);
+ GetEntry(handle, "version.txt", &entry);
char* buf = new char[entry.uncompressed_length + 1];
ExtractToMemory(handle, &entry, (uint8_t*)buf, entry.uncompressed_length);
@@ -244,6 +316,10 @@
FileExists("dumpstate_board.txt", 100000U, 1000000U);
}
+TEST_F(ZippedBugReportContentsTest, ContainsProtoFile) {
+ FileExists("proto/activity.proto", 100000U, 1000000U);
+}
+
// Spot check on some files pulled from the file system
TEST_F(ZippedBugReportContentsTest, ContainsSomeFileSystemFiles) {
// FS/proc/*/mountinfo size > 0
@@ -258,6 +334,11 @@
*/
class BugreportSectionTest : public Test {
public:
+ static void SetUpTestCase() {
+ ParseSections(ZippedBugreportGenerationTest::getZipFilePath(),
+ ZippedBugreportGenerationTest::sections.get());
+ }
+
int numMatches(const std::string& substring) {
int matches = 0;
for (auto const& section : *ZippedBugreportGenerationTest::sections) {
@@ -267,10 +348,11 @@
}
return matches;
}
+
void SectionExists(const std::string& sectionName, int minsize) {
for (auto const& section : *ZippedBugreportGenerationTest::sections) {
if (sectionName == section.name) {
- EXPECT_GE(section.size_bytes, minsize);
+ EXPECT_GE(section.size_bytes, minsize) << " for section:" << sectionName;
return;
}
}
@@ -278,71 +360,59 @@
}
};
-// Test all sections are generated without timeouts or errors
-TEST_F(BugreportSectionTest, GeneratedWithoutErrors) {
- for (auto const& section : *ZippedBugreportGenerationTest::sections) {
- EXPECT_EQ(section.status, 0) << section.name << " failed with status " << section.status;
- }
-}
-
TEST_F(BugreportSectionTest, Atleast3CriticalDumpsysSectionsGenerated) {
- int numSections = numMatches("DUMPSYS CRITICAL");
+ int numSections = numMatches("CRITICAL");
EXPECT_GE(numSections, 3);
}
TEST_F(BugreportSectionTest, Atleast2HighDumpsysSectionsGenerated) {
- int numSections = numMatches("DUMPSYS HIGH");
+ int numSections = numMatches("HIGH");
EXPECT_GE(numSections, 2);
}
TEST_F(BugreportSectionTest, Atleast50NormalDumpsysSectionsGenerated) {
- int allSections = numMatches("DUMPSYS");
- int criticalSections = numMatches("DUMPSYS CRITICAL");
- int highSections = numMatches("DUMPSYS HIGH");
+ int allSections = ZippedBugreportGenerationTest::sections->size();
+ int criticalSections = numMatches("CRITICAL");
+ int highSections = numMatches("HIGH");
int normalSections = allSections - criticalSections - highSections;
EXPECT_GE(normalSections, 50) << "Total sections less than 50 (Critical:" << criticalSections
<< "High:" << highSections << "Normal:" << normalSections << ")";
}
-TEST_F(BugreportSectionTest, Atleast1ProtoDumpsysSectionGenerated) {
- int numSections = numMatches("proto/");
- EXPECT_GE(numSections, 1);
-}
-
// Test if some critical sections are being generated.
TEST_F(BugreportSectionTest, CriticalSurfaceFlingerSectionGenerated) {
- SectionExists("DUMPSYS CRITICAL - SurfaceFlinger", /* bytes= */ 10000);
+ SectionExists("CRITICAL SurfaceFlinger", /* bytes= */ 10000);
}
TEST_F(BugreportSectionTest, ActivitySectionsGenerated) {
- SectionExists("DUMPSYS CRITICAL - activity", /* bytes= */ 5000);
- SectionExists("DUMPSYS - activity", /* bytes= */ 10000);
+ SectionExists("CRITICAL activity", /* bytes= */ 5000);
+ SectionExists("activity", /* bytes= */ 10000);
}
TEST_F(BugreportSectionTest, CpuinfoSectionGenerated) {
- SectionExists("DUMPSYS CRITICAL - cpuinfo", /* bytes= */ 1000);
+ SectionExists("CRITICAL cpuinfo", /* bytes= */ 1000);
}
TEST_F(BugreportSectionTest, WindowSectionGenerated) {
- SectionExists("DUMPSYS CRITICAL - window", /* bytes= */ 20000);
+ SectionExists("CRITICAL window", /* bytes= */ 20000);
}
TEST_F(BugreportSectionTest, ConnectivitySectionsGenerated) {
- SectionExists("DUMPSYS HIGH - connectivity", /* bytes= */ 5000);
- SectionExists("DUMPSYS - connectivity", /* bytes= */ 5000);
+ SectionExists("HIGH connectivity", /* bytes= */ 3000);
+ SectionExists("connectivity", /* bytes= */ 5000);
}
TEST_F(BugreportSectionTest, MeminfoSectionGenerated) {
- SectionExists("DUMPSYS HIGH - meminfo", /* bytes= */ 100000);
+ SectionExists("HIGH meminfo", /* bytes= */ 100000);
}
TEST_F(BugreportSectionTest, BatteryStatsSectionGenerated) {
- SectionExists("DUMPSYS - batterystats", /* bytes= */ 1000);
+ SectionExists("batterystats", /* bytes= */ 1000);
}
TEST_F(BugreportSectionTest, WifiSectionGenerated) {
- SectionExists("DUMPSYS - wifi", /* bytes= */ 100000);
+ SectionExists("wifi", /* bytes= */ 100000);
}
class DumpstateBinderTest : public Test {
diff --git a/cmds/dumpstate/tests/dumpstate_test.cpp b/cmds/dumpstate/tests/dumpstate_test.cpp
index 71d15f4..4e6b084 100644
--- a/cmds/dumpstate/tests/dumpstate_test.cpp
+++ b/cmds/dumpstate/tests/dumpstate_test.cpp
@@ -105,9 +105,8 @@
protected:
const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
- const std::string kFixturesPath = kTestPath + "/../dumpstate_test_fixture/";
- const std::string kTestDataPath = kFixturesPath + "tests/testdata/";
- const std::string kSimpleCommand = kFixturesPath + "dumpstate_test_fixture";
+ const std::string kTestDataPath = kTestPath + "/tests/testdata/";
+ const std::string kSimpleCommand = kTestPath + "/dumpstate_test_fixture";
const std::string kEchoCommand = "/system/bin/echo";
/*
@@ -664,7 +663,8 @@
TEST_F(DumpstateTest, RunCommandWithTitle) {
EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
EXPECT_THAT(err, StrEq("stderr\n"));
- // We don't know the exact duration, so we check the prefix and suffix
+ // The duration may not get output, depending on how long it takes,
+ // so we just check the prefix.
EXPECT_THAT(out,
StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
}
@@ -699,7 +699,8 @@
TEST_F(DumpstateTest, RunCommandDryRun) {
SetDryRun(true);
EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
- // We don't know the exact duration, so we check the prefix and suffix
+ // The duration may not get output, depending on how long it takes,
+ // so we just check the prefix.
EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
") ------\n\t(skipped on dry run)\n"));
EXPECT_THAT(err, IsEmpty());
@@ -1037,7 +1038,8 @@
TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
EXPECT_THAT(err, IsEmpty());
- // We don't know the exact duration, so we check the prefix and suffix
+ // The duration may not get output, depending on how long it takes,
+ // so we just check the prefix.
EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
"such file or directory\n"));
}
@@ -1404,14 +1406,6 @@
return status;
}
- // Find out the pid of the process_name
- int FindPidOfProcess(const std::string& process_name) {
- CaptureStderr();
- int status = GetPidByName(process_name);
- err = GetCapturedStderr();
- return status;
- }
-
int fd;
// 'fd` output and `stderr` from the last command ran.
@@ -1761,18 +1755,6 @@
EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
}
-TEST_F(DumpstateUtilTest, FindingPidWithExistingProcess) {
- // init process always has pid 1.
- EXPECT_EQ(1, FindPidOfProcess("init"));
- EXPECT_THAT(err, IsEmpty());
-}
-
-TEST_F(DumpstateUtilTest, FindingPidWithNotExistingProcess) {
- // find the process with abnormal name.
- EXPECT_EQ(-1, FindPidOfProcess("abcdef12345-543"));
- EXPECT_THAT(err, StrEq("can't find the pid\n"));
-}
-
} // namespace dumpstate
} // namespace os
} // namespace android
diff --git a/cmds/dumpstate/utils.cpp b/cmds/dumpstate/utils.cpp
deleted file mode 100644
index 0bb80dc..0000000
--- a/cmds/dumpstate/utils.cpp
+++ /dev/null
@@ -1,1012 +0,0 @@
-/*
- * Copyright (C) 2008 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 "dumpstate"
-
-#include "dumpstate.h"
-
-#include <dirent.h>
-#include <fcntl.h>
-#include <libgen.h>
-#include <math.h>
-#include <poll.h>
-#include <signal.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/capability.h>
-#include <sys/inotify.h>
-#include <sys/klog.h>
-#include <sys/prctl.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/wait.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <memory>
-#include <set>
-#include <string>
-#include <vector>
-
-#include <android-base/file.h>
-#include <android-base/properties.h>
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <android-base/unique_fd.h>
-#include <cutils/properties.h>
-#include <cutils/sockets.h>
-#include <log/log.h>
-#include <private/android_filesystem_config.h>
-
-#include "DumpstateInternal.h"
-
-// TODO: remove once moved to namespace
-using android::os::dumpstate::CommandOptions;
-using android::os::dumpstate::DumpFileToFd;
-using android::os::dumpstate::PropertiesHelper;
-
-// Keep in sync with
-// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
-static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
-
-/* Most simple commands have 10 as timeout, so 5 is a good estimate */
-static const int32_t WEIGHT_FILE = 5;
-
-// TODO: temporary variables and functions used during C++ refactoring
-static Dumpstate& ds = Dumpstate::GetInstance();
-static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
- const CommandOptions& options = CommandOptions::DEFAULT) {
- return ds.RunCommand(title, full_command, options);
-}
-
-// Reasonable value for max stats.
-static const int STATS_MAX_N_RUNS = 1000;
-static const long STATS_MAX_AVERAGE = 100000;
-
-CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
-
-// TODO(111441001): Default DumpOptions to sensible values.
-Dumpstate::Dumpstate(const std::string& version)
- : pid_(getpid()),
- options_(new Dumpstate::DumpOptions()),
- version_(version),
- now_(time(nullptr)) {
-}
-
-Dumpstate& Dumpstate::GetInstance() {
- static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
- return singleton_;
-}
-
-DurationReporter::DurationReporter(const std::string& title, bool logcat_only)
- : title_(title), logcat_only_(logcat_only) {
- if (!title_.empty()) {
- started_ = Nanotime();
- }
-}
-
-DurationReporter::~DurationReporter() {
- if (!title_.empty()) {
- float elapsed = (float)(Nanotime() - started_) / NANOS_PER_SEC;
- if (elapsed < .5f) {
- return;
- }
- MYLOGD("Duration of '%s': %.2fs\n", title_.c_str(), elapsed);
- if (logcat_only_) {
- return;
- }
- // Use "Yoda grammar" to make it easier to grep|sort sections.
- printf("------ %.3fs was the duration of '%s' ------\n", elapsed, title_.c_str());
- }
-}
-
-const int32_t Progress::kDefaultMax = 5000;
-
-Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
-}
-
-Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
- : Progress(initial_max, growth_factor, "") {
- progress_ = progress;
-}
-
-Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
- : initial_max_(initial_max),
- progress_(0),
- max_(initial_max),
- growth_factor_(growth_factor),
- n_runs_(0),
- average_max_(0),
- path_(path) {
- if (!path_.empty()) {
- Load();
- }
-}
-
-void Progress::Load() {
- MYLOGD("Loading stats from %s\n", path_.c_str());
- std::string content;
- if (!android::base::ReadFileToString(path_, &content)) {
- MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
- return;
- }
- if (content.empty()) {
- MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
- return;
- }
- std::vector<std::string> lines = android::base::Split(content, "\n");
-
- if (lines.size() < 1) {
- MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
- (int)lines.size(), max_);
- return;
- }
- char* ptr;
- n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
- average_max_ = strtol(ptr, nullptr, 10);
- if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
- average_max_ > STATS_MAX_AVERAGE) {
- MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
- initial_max_ = Progress::kDefaultMax;
- } else {
- initial_max_ = average_max_;
- }
- max_ = initial_max_;
-
- MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
-}
-
-void Progress::Save() {
- int32_t total = n_runs_ * average_max_ + progress_;
- int32_t runs = n_runs_ + 1;
- int32_t average = floor(((float)total) / runs);
- MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
- path_.c_str());
- if (path_.empty()) {
- return;
- }
-
- std::string content = android::base::StringPrintf("%d %d\n", runs, average);
- if (!android::base::WriteStringToFile(content, path_)) {
- MYLOGE("Could not save stats on %s\n", path_.c_str());
- }
-}
-
-int32_t Progress::Get() const {
- return progress_;
-}
-
-bool Progress::Inc(int32_t delta_sec) {
- bool changed = false;
- if (delta_sec >= 0) {
- progress_ += delta_sec;
- if (progress_ > max_) {
- int32_t old_max = max_;
- max_ = floor((float)progress_ * growth_factor_);
- MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
- changed = true;
- }
- }
- return changed;
-}
-
-int32_t Progress::GetMax() const {
- return max_;
-}
-
-int32_t Progress::GetInitialMax() const {
- return initial_max_;
-}
-
-void Progress::Dump(int fd, const std::string& prefix) const {
- const char* pr = prefix.c_str();
- dprintf(fd, "%sprogress: %d\n", pr, progress_);
- dprintf(fd, "%smax: %d\n", pr, max_);
- dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
- dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
- dprintf(fd, "%spath: %s\n", pr, path_.c_str());
- dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
- dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
-}
-
-bool Dumpstate::IsZipping() const {
- return zip_writer_ != nullptr;
-}
-
-std::string Dumpstate::GetPath(const std::string& suffix) const {
- return GetPath(bugreport_internal_dir_, suffix);
-}
-
-std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
- return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
- name_.c_str(), suffix.c_str());
-}
-
-void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
- progress_ = std::move(progress);
-}
-
-void for_each_userid(void (*func)(int), const char *header) {
- std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
- "for_each_userid(%s)", header);
- DurationReporter duration_reporter(title);
- if (PropertiesHelper::IsDryRun()) return;
-
- DIR *d;
- struct dirent *de;
-
- if (header) printf("\n------ %s ------\n", header);
- func(0);
-
- if (!(d = opendir("/data/system/users"))) {
- printf("Failed to open /data/system/users (%s)\n", strerror(errno));
- return;
- }
-
- while ((de = readdir(d))) {
- int userid;
- if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
- continue;
- }
- func(userid);
- }
-
- closedir(d);
-}
-
-static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
- DIR *d;
- struct dirent *de;
-
- if (!(d = opendir("/proc"))) {
- printf("Failed to open /proc (%s)\n", strerror(errno));
- return;
- }
-
- if (header) printf("\n------ %s ------\n", header);
- while ((de = readdir(d))) {
- if (ds.IsUserConsentDenied()) {
- MYLOGE(
- "Returning early because user denied consent to share bugreport with calling app.");
- closedir(d);
- return;
- }
- int pid;
- int fd;
- char cmdpath[255];
- char cmdline[255];
-
- if (!(pid = atoi(de->d_name))) {
- continue;
- }
-
- memset(cmdline, 0, sizeof(cmdline));
-
- snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
- if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
- TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
- close(fd);
- if (cmdline[0]) {
- helper(pid, cmdline, arg);
- continue;
- }
- }
-
- // if no cmdline, a kernel thread has comm
- snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
- if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
- TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
- close(fd);
- if (cmdline[1]) {
- cmdline[0] = '[';
- size_t len = strcspn(cmdline, "\f\b\r\n");
- cmdline[len] = ']';
- cmdline[len+1] = '\0';
- }
- }
- if (!cmdline[0]) {
- strcpy(cmdline, "N/A");
- }
- helper(pid, cmdline, arg);
- }
-
- closedir(d);
-}
-
-static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
- for_each_pid_func *func = (for_each_pid_func*) arg;
- func(pid, cmdline);
-}
-
-void for_each_pid(for_each_pid_func func, const char *header) {
- std::string title = header == nullptr ? "for_each_pid"
- : android::base::StringPrintf("for_each_pid(%s)", header);
- DurationReporter duration_reporter(title);
- if (PropertiesHelper::IsDryRun()) return;
-
- __for_each_pid(for_each_pid_helper, header, (void *) func);
-}
-
-static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
- DIR *d;
- struct dirent *de;
- char taskpath[255];
- for_each_tid_func *func = (for_each_tid_func *) arg;
-
- snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
-
- if (!(d = opendir(taskpath))) {
- printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
- return;
- }
-
- func(pid, pid, cmdline);
-
- while ((de = readdir(d))) {
- if (ds.IsUserConsentDenied()) {
- MYLOGE(
- "Returning early because user denied consent to share bugreport with calling app.");
- closedir(d);
- return;
- }
- int tid;
- int fd;
- char commpath[255];
- char comm[255];
-
- if (!(tid = atoi(de->d_name))) {
- continue;
- }
-
- if (tid == pid)
- continue;
-
- snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
- memset(comm, 0, sizeof(comm));
- if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
- strcpy(comm, "N/A");
- } else {
- char *c;
- TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
- close(fd);
-
- c = strrchr(comm, '\n');
- if (c) {
- *c = '\0';
- }
- }
- func(pid, tid, comm);
- }
-
- closedir(d);
-}
-
-void for_each_tid(for_each_tid_func func, const char *header) {
- std::string title = header == nullptr ? "for_each_tid"
- : android::base::StringPrintf("for_each_tid(%s)", header);
- DurationReporter duration_reporter(title);
-
- if (PropertiesHelper::IsDryRun()) return;
-
- __for_each_pid(for_each_tid_helper, header, (void *) func);
-}
-
-void show_wchan(int pid, int tid, const char *name) {
- if (PropertiesHelper::IsDryRun()) return;
-
- char path[255];
- char buffer[255];
- int fd, ret, save_errno;
- char name_buffer[255];
-
- memset(buffer, 0, sizeof(buffer));
-
- snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
- if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
- printf("Failed to open '%s' (%s)\n", path, strerror(errno));
- return;
- }
-
- ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
- save_errno = errno;
- close(fd);
-
- if (ret < 0) {
- printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
- return;
- }
-
- snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
- pid == tid ? 0 : 3, "", name);
-
- printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
-
- return;
-}
-
-// print time in centiseconds
-static void snprcent(char *buffer, size_t len, size_t spc,
- unsigned long long time) {
- static long hz; // cache discovered hz
-
- if (hz <= 0) {
- hz = sysconf(_SC_CLK_TCK);
- if (hz <= 0) {
- hz = 1000;
- }
- }
-
- // convert to centiseconds
- time = (time * 100 + (hz / 2)) / hz;
-
- char str[16];
-
- snprintf(str, sizeof(str), " %llu.%02u",
- time / 100, (unsigned)(time % 100));
- size_t offset = strlen(buffer);
- snprintf(buffer + offset, (len > offset) ? len - offset : 0,
- "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
-}
-
-// print permille as a percent
-static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
- char str[16];
-
- snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
- size_t offset = strlen(buffer);
- snprintf(buffer + offset, (len > offset) ? len - offset : 0,
- "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
-}
-
-void show_showtime(int pid, const char *name) {
- if (PropertiesHelper::IsDryRun()) return;
-
- char path[255];
- char buffer[1023];
- int fd, ret, save_errno;
-
- memset(buffer, 0, sizeof(buffer));
-
- snprintf(path, sizeof(path), "/proc/%d/stat", pid);
- if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
- printf("Failed to open '%s' (%s)\n", path, strerror(errno));
- return;
- }
-
- ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
- save_errno = errno;
- close(fd);
-
- if (ret < 0) {
- printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
- return;
- }
-
- // field 14 is utime
- // field 15 is stime
- // field 42 is iotime
- unsigned long long utime = 0, stime = 0, iotime = 0;
- if (sscanf(buffer,
- "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
- "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
- "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
- "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
- &utime, &stime, &iotime) != 3) {
- return;
- }
-
- unsigned long long total = utime + stime;
- if (!total) {
- return;
- }
-
- unsigned permille = (iotime * 1000 + (total / 2)) / total;
- if (permille > 1000) {
- permille = 1000;
- }
-
- // try to beautify and stabilize columns at <80 characters
- snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
- if ((name[0] != '[') || utime) {
- snprcent(buffer, sizeof(buffer), 57, utime);
- }
- snprcent(buffer, sizeof(buffer), 65, stime);
- if ((name[0] != '[') || iotime) {
- snprcent(buffer, sizeof(buffer), 73, iotime);
- }
- if (iotime) {
- snprdec(buffer, sizeof(buffer), 79, permille);
- }
- puts(buffer); // adds a trailing newline
-
- return;
-}
-
-void do_dmesg() {
- const char *title = "KERNEL LOG (dmesg)";
- DurationReporter duration_reporter(title);
- printf("------ %s ------\n", title);
-
- if (PropertiesHelper::IsDryRun()) return;
-
- /* Get size of kernel buffer */
- int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
- if (size <= 0) {
- printf("Unexpected klogctl return value: %d\n\n", size);
- return;
- }
- char *buf = (char *) malloc(size + 1);
- if (buf == nullptr) {
- printf("memory allocation failed\n\n");
- return;
- }
- int retval = klogctl(KLOG_READ_ALL, buf, size);
- if (retval < 0) {
- printf("klogctl failure\n\n");
- free(buf);
- return;
- }
- buf[retval] = '\0';
- printf("%s\n\n", buf);
- free(buf);
- return;
-}
-
-void do_showmap(int pid, const char *name) {
- char title[255];
- char arg[255];
-
- snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
- snprintf(arg, sizeof(arg), "%d", pid);
- RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
-}
-
-int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
- DurationReporter duration_reporter(title);
-
- int status = DumpFileToFd(STDOUT_FILENO, title, path);
-
- UpdateProgress(WEIGHT_FILE);
-
- return status;
-}
-
-int read_file_as_long(const char *path, long int *output) {
- int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
- if (fd < 0) {
- int err = errno;
- MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
- return -1;
- }
- char buffer[50];
- ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
- if (bytes_read == -1) {
- MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
- return -2;
- }
- if (bytes_read == 0) {
- MYLOGE("File %s is empty\n", path);
- return -3;
- }
- *output = atoi(buffer);
- return 0;
-}
-
-/* calls skip to gate calling dump_from_fd recursively
- * in the specified directory. dump_from_fd defaults to
- * dump_file_from_fd above when set to NULL. skip defaults
- * to false when set to NULL. dump_from_fd will always be
- * called with title NULL.
- */
-int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
- int (*dump_from_fd)(const char* title, const char* path, int fd)) {
- DurationReporter duration_reporter(title);
- DIR *dirp;
- struct dirent *d;
- char *newpath = nullptr;
- const char *slash = "/";
- int retval = 0;
-
- if (!title.empty()) {
- printf("------ %s (%s) ------\n", title.c_str(), dir);
- }
- if (PropertiesHelper::IsDryRun()) return 0;
-
- if (dir[strlen(dir) - 1] == '/') {
- ++slash;
- }
- dirp = opendir(dir);
- if (dirp == nullptr) {
- retval = -errno;
- MYLOGE("%s: %s\n", dir, strerror(errno));
- return retval;
- }
-
- if (!dump_from_fd) {
- dump_from_fd = dump_file_from_fd;
- }
- for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
- if ((d->d_name[0] == '.')
- && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
- || (d->d_name[1] == '\0'))) {
- continue;
- }
- asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
- (d->d_type == DT_DIR) ? "/" : "");
- if (!newpath) {
- retval = -errno;
- continue;
- }
- if (skip && (*skip)(newpath)) {
- continue;
- }
- if (d->d_type == DT_DIR) {
- int ret = dump_files("", newpath, skip, dump_from_fd);
- if (ret < 0) {
- retval = ret;
- }
- continue;
- }
- android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
- if (fd.get() < 0) {
- retval = -1;
- printf("*** %s: %s\n", newpath, strerror(errno));
- continue;
- }
- (*dump_from_fd)(nullptr, newpath, fd.get());
- }
- closedir(dirp);
- if (!title.empty()) {
- printf("\n");
- }
- return retval;
-}
-
-/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
- * it's possible to avoid issues where opening the file itself can get
- * stuck.
- */
-int dump_file_from_fd(const char *title, const char *path, int fd) {
- if (PropertiesHelper::IsDryRun()) return 0;
-
- int flags = fcntl(fd, F_GETFL);
- if (flags == -1) {
- printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
- return -1;
- } else if (!(flags & O_NONBLOCK)) {
- printf("*** %s: fd must have O_NONBLOCK set.\n", path);
- return -1;
- }
- return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
-}
-
-int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
- const CommandOptions& options) {
- DurationReporter duration_reporter(title);
-
- int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
-
- /* TODO: for now we're simplifying the progress calculation by using the
- * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
- * where its weight should be much higher proportionally to its timeout.
- * Ideally, it should use a options.EstimatedDuration() instead...*/
- UpdateProgress(options.Timeout());
-
- return status;
-}
-
-void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
- const CommandOptions& options, long dumpsysTimeoutMs) {
- long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
- std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
- dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
- RunCommand(title, dumpsys, options);
-}
-
-int open_socket(const char *service) {
- int s = android_get_control_socket(service);
- if (s < 0) {
- MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
- return -1;
- }
- fcntl(s, F_SETFD, FD_CLOEXEC);
- if (listen(s, 4) < 0) {
- MYLOGE("listen(control socket): %s\n", strerror(errno));
- return -1;
- }
-
- struct sockaddr addr;
- socklen_t alen = sizeof(addr);
- int fd = accept(s, &addr, &alen);
- if (fd < 0) {
- MYLOGE("accept(control socket): %s\n", strerror(errno));
- return -1;
- }
-
- return fd;
-}
-
-/* redirect output to a service control socket */
-bool redirect_to_socket(FILE* redirect, const char* service) {
- int fd = open_socket(service);
- if (fd == -1) {
- return false;
- }
- fflush(redirect);
- // TODO: handle dup2 failure
- TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
- close(fd);
- return true;
-}
-
-// TODO: should call is_valid_output_file and/or be merged into it.
-void create_parent_dirs(const char *path) {
- char *chp = const_cast<char *> (path);
-
- /* skip initial slash */
- if (chp[0] == '/')
- chp++;
-
- /* create leading directories, if necessary */
- struct stat dir_stat;
- while (chp && chp[0]) {
- chp = strchr(chp, '/');
- if (chp) {
- *chp = 0;
- if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
- MYLOGI("Creating directory %s\n", path);
- if (mkdir(path, 0770)) { /* drwxrwx--- */
- MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
- } else if (chown(path, AID_SHELL, AID_SHELL)) {
- MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
- }
- }
- *chp++ = '/';
- }
- }
-}
-
-bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
- create_parent_dirs(path);
-
- int fd = TEMP_FAILURE_RETRY(open(path,
- O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
- if (fd < 0) {
- MYLOGE("%s: %s\n", path, strerror(errno));
- return false;
- }
-
- TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
- close(fd);
- return true;
-}
-
-bool redirect_to_file(FILE* redirect, char* path) {
- return _redirect_to_file(redirect, path, O_TRUNC);
-}
-
-bool redirect_to_existing_file(FILE* redirect, char* path) {
- return _redirect_to_file(redirect, path, O_APPEND);
-}
-
-void dump_route_tables() {
- DurationReporter duration_reporter("DUMP ROUTE TABLES");
- if (PropertiesHelper::IsDryRun()) return;
- const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
- ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
- FILE* fp = fopen(RT_TABLES_PATH, "re");
- if (!fp) {
- printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
- return;
- }
- char table[16];
- // Each line has an integer (the table number), a space, and a string (the table name). We only
- // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
- // Add a fixed max limit so this doesn't go awry.
- for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
- RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
- RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
- }
- fclose(fp);
-}
-
-// TODO: make this function thread safe if sections are generated in parallel.
-void Dumpstate::UpdateProgress(int32_t delta_sec) {
- if (progress_ == nullptr) {
- MYLOGE("UpdateProgress: progress_ not set\n");
- return;
- }
-
- // Always update progess so stats can be tuned...
- bool max_changed = progress_->Inc(delta_sec);
-
- // ...but only notifiy listeners when necessary.
- if (!options_->do_progress_updates) return;
-
- int progress = progress_->Get();
- int max = progress_->GetMax();
-
- // adjusts max on the fly
- if (max_changed && listener_ != nullptr) {
- listener_->onMaxProgressUpdated(max);
- }
-
- int32_t last_update_delta = progress - last_updated_progress_;
- if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
- return;
- }
- last_updated_progress_ = progress;
-
- if (control_socket_fd_ >= 0) {
- dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
- fsync(control_socket_fd_);
- }
-
- int percent = 100 * progress / max;
- if (listener_ != nullptr) {
- if (percent % 5 == 0) {
- // We don't want to spam logcat, so only log multiples of 5.
- MYLOGD("Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(), progress, max,
- percent);
- } else {
- // stderr is ignored on normal invocations, but useful when calling
- // /system/bin/dumpstate directly for debuggging.
- fprintf(stderr, "Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(),
- progress, max, percent);
- }
- // TODO(b/111441001): Remove in favor of onProgress
- listener_->onProgressUpdated(progress);
-
- listener_->onProgress(percent);
- }
-}
-
-void Dumpstate::TakeScreenshot(const std::string& path) {
- const std::string& real_path = path.empty() ? screenshot_path_ : path;
- int status =
- RunCommand("", {"/system/bin/screencap", "-p", real_path},
- CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
- if (status == 0) {
- MYLOGD("Screenshot saved on %s\n", real_path.c_str());
- } else {
- MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
- }
-}
-
-bool is_dir(const char* pathname) {
- struct stat info;
- if (stat(pathname, &info) == -1) {
- return false;
- }
- return S_ISDIR(info.st_mode);
-}
-
-time_t get_mtime(int fd, time_t default_mtime) {
- struct stat info;
- if (fstat(fd, &info) == -1) {
- return default_mtime;
- }
- return info.st_mtime;
-}
-
-void dump_emmc_ecsd(const char *ext_csd_path) {
- // List of interesting offsets
- struct hex {
- char str[2];
- };
- static const size_t EXT_CSD_REV = 192 * sizeof(hex);
- static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
- static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
- static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
-
- std::string buffer;
- if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
- return;
- }
-
- printf("------ %s Extended CSD ------\n", ext_csd_path);
-
- if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
- printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
- return;
- }
-
- int ext_csd_rev = 0;
- std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
- if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
- printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
- return;
- }
-
- static const char *ver_str[] = {
- "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
- };
- printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
- (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
- : "Unknown");
- if (ext_csd_rev < 7) {
- printf("\n");
- return;
- }
-
- if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
- printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
- return;
- }
-
- int ext_pre_eol_info = 0;
- sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
- if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
- printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
- return;
- }
-
- static const char *eol_str[] = {
- "Undefined",
- "Normal",
- "Warning (consumed 80% of reserve)",
- "Urgent (consumed 90% of reserve)"
- };
- printf(
- "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
- eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
- : 0]);
-
- for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
- lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
- lifetime += sizeof(hex)) {
- int ext_device_life_time_est;
- static const char *est_str[] = {
- "Undefined",
- "0-10% of device lifetime used",
- "10-20% of device lifetime used",
- "20-30% of device lifetime used",
- "30-40% of device lifetime used",
- "40-50% of device lifetime used",
- "50-60% of device lifetime used",
- "60-70% of device lifetime used",
- "70-80% of device lifetime used",
- "80-90% of device lifetime used",
- "90-100% of device lifetime used",
- "Exceeded the maximum estimated device lifetime",
- };
-
- if (buffer.length() < (lifetime + sizeof(hex))) {
- printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
- break;
- }
-
- ext_device_life_time_est = 0;
- sub = buffer.substr(lifetime, sizeof(hex));
- if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
- printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
- (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
- sub.c_str());
- continue;
- }
- printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
- (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
- ext_device_life_time_est,
- est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
- ? ext_device_life_time_est
- : 0]);
- }
-
- printf("\n");
-}
diff --git a/cmds/installd/Android.bp b/cmds/installd/Android.bp
index 4619427..1016832 100644
--- a/cmds/installd/Android.bp
+++ b/cmds/installd/Android.bp
@@ -133,6 +133,7 @@
cc_binary {
name: "otapreopt_chroot",
+ defaults: ["libapexd-deps"],
cflags: [
"-Wall",
"-Werror",
@@ -145,20 +146,11 @@
],
shared_libs: [
"libbase",
- "libbinder",
"liblog",
- "libprotobuf-cpp-full",
- "libselinux",
"libutils",
- "libziparchive",
],
static_libs: [
- "libapex",
"libapexd",
- "lib_apex_manifest_proto",
- "libavb",
- "libdm",
- "libvold_binder",
],
}
@@ -167,6 +159,7 @@
srcs: [
"binder/android/os/IInstalld.aidl",
],
+ path: "binder",
}
//
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index ae4ea78..47fdcc4 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -2055,10 +2055,15 @@
CHECK_ARGUMENT_PATH(dexMetadataPath);
std::lock_guard<std::recursive_mutex> lock(mLock);
+ const char* oat_dir = getCStr(outputPath);
+ const char* instruction_set = instructionSet.c_str();
+ if (oat_dir != nullptr && !createOatDir(oat_dir, instruction_set).isOk()) {
+ // Can't create oat dir - let dexopt use cache dir.
+ oat_dir = nullptr;
+ }
+
const char* apk_path = apkPath.c_str();
const char* pkgname = getCStr(packageName, "*");
- const char* instruction_set = instructionSet.c_str();
- const char* oat_dir = getCStr(outputPath);
const char* compiler_filter = compilerFilter.c_str();
const char* volume_uuid = getCStr(uuid);
const char* class_loader_context = getCStr(classLoaderContext);
diff --git a/cmds/installd/OWNERS b/cmds/installd/OWNERS
index 5673918..9a21104 100644
--- a/cmds/installd/OWNERS
+++ b/cmds/installd/OWNERS
@@ -4,7 +4,9 @@
calin@google.com
jsharkey@android.com
maco@google.com
+mast@google.com
mathieuc@google.com
narayan@google.com
ngeoffray@google.com
+rpl@google.com
toddke@google.com
diff --git a/cmds/installd/art_helper/Android.bp b/cmds/installd/art_helper/Android.bp
deleted file mode 100644
index c47dd72..0000000
--- a/cmds/installd/art_helper/Android.bp
+++ /dev/null
@@ -1,12 +0,0 @@
-// Inherit image values.
-art_global_defaults {
- name: "libartimagevalues_defaults",
-}
-
-cc_library_static {
- name: "libartimagevalues",
- defaults: ["libartimagevalues_defaults"],
- srcs: ["art_image_values.cpp"],
- export_include_dirs: ["."],
- cflags: ["-Wconversion"],
-}
diff --git a/cmds/installd/art_helper/art_image_values.cpp b/cmds/installd/art_helper/art_image_values.cpp
deleted file mode 100644
index a139049..0000000
--- a/cmds/installd/art_helper/art_image_values.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2018 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 "art_image_values.h"
-
-namespace android {
-namespace installd {
-namespace art {
-
-uint32_t GetImageBaseAddress() {
- return ART_BASE_ADDRESS;
-}
-int32_t GetImageMinBaseAddressDelta() {
- return ART_BASE_ADDRESS_MIN_DELTA;
-}
-int32_t GetImageMaxBaseAddressDelta() {
- return ART_BASE_ADDRESS_MAX_DELTA;
-}
-
-static_assert(ART_BASE_ADDRESS_MIN_DELTA < ART_BASE_ADDRESS_MAX_DELTA, "Inconsistent setup");
-
-} // namespace art
-} // namespace installd
-} // namespace android
diff --git a/cmds/installd/art_helper/art_image_values.h b/cmds/installd/art_helper/art_image_values.h
deleted file mode 100644
index 20c44c9..0000000
--- a/cmds/installd/art_helper/art_image_values.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2018 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 FRAMEWORKS_NATIVE_CMDS_INSTALLD_ART_HELPER_ART_IMAGE_VALUES_H
-#define FRAMEWORKS_NATIVE_CMDS_INSTALLD_ART_HELPER_ART_IMAGE_VALUES_H
-
-#include <cstdint>
-
-namespace android {
-namespace installd {
-namespace art {
-
-uint32_t GetImageBaseAddress();
-int32_t GetImageMinBaseAddressDelta();
-int32_t GetImageMaxBaseAddressDelta();
-
-} // namespace art
-} // namespace installd
-} // namespace android
-
-#endif // FRAMEWORKS_NATIVE_CMDS_INSTALLD_ART_HELPER_ART_IMAGE_VALUES_H
diff --git a/cmds/installd/otapreopt.cpp b/cmds/installd/otapreopt.cpp
index de7b249..db36ce3 100644
--- a/cmds/installd/otapreopt.cpp
+++ b/cmds/installd/otapreopt.cpp
@@ -445,9 +445,11 @@
}
cmd.push_back(StringPrintf("--oat-file=%s", oat_path.c_str()));
- int32_t base_offset = ChooseRelocationOffsetDelta(art::GetImageMinBaseAddressDelta(),
- art::GetImageMaxBaseAddressDelta());
- cmd.push_back(StringPrintf("--base=0x%x", art::GetImageBaseAddress() + base_offset));
+ int32_t base_offset = ChooseRelocationOffsetDelta(
+ art::imagevalues::GetImageMinBaseAddressDelta(),
+ art::imagevalues::GetImageMaxBaseAddressDelta());
+ cmd.push_back(StringPrintf("--base=0x%x",
+ art::imagevalues::GetImageBaseAddress() + base_offset));
cmd.push_back(StringPrintf("--instruction-set=%s", isa));
@@ -464,7 +466,7 @@
"--compiler-filter=",
false,
cmd);
- cmd.push_back("--image-classes=/system/etc/preloaded-classes");
+ cmd.push_back("--profile-file=/system/etc/boot-image.prof");
// TODO: Compiled-classes.
const std::string* extra_opts =
system_properties_.GetProperty("dalvik.vm.image-dex2oat-flags");
diff --git a/cmds/installd/otapreopt_chroot.cpp b/cmds/installd/otapreopt_chroot.cpp
index 2e2cc18..b4bcd53 100644
--- a/cmds/installd/otapreopt_chroot.cpp
+++ b/cmds/installd/otapreopt_chroot.cpp
@@ -64,16 +64,18 @@
// system/apex/apexd/apexd_main.cpp.
//
// Only scan the APEX directory under /system (within the chroot dir).
- apex::scanPackagesDirAndActivate(apex::kApexPackageSystemDir);
+ // Cast call to void to suppress warn_unused_result.
+ static_cast<void>(apex::scanPackagesDirAndActivate(apex::kApexPackageSystemDir));
return apex::getActivePackages();
}
static void DeactivateApexPackages(const std::vector<apex::ApexFile>& active_packages) {
for (const apex::ApexFile& apex_file : active_packages) {
const std::string& package_path = apex_file.GetPath();
- apex::Status status = apex::deactivatePackage(package_path);
- if (!status.Ok()) {
- LOG(ERROR) << "Failed to deactivate " << package_path << ": " << status.ErrorMessage();
+ base::Result<void> status = apex::deactivatePackage(package_path);
+ if (!status) {
+ LOG(ERROR) << "Failed to deactivate " << package_path << ": "
+ << status.error();
}
}
}
@@ -234,6 +236,18 @@
// the Android Runtime APEX, as it is required by otapreopt to run dex2oat.
std::vector<apex::ApexFile> active_packages = ActivateApexPackages();
+ // Check that an Android Runtime APEX has been activated; clean up and exit
+ // early otherwise.
+ if (std::none_of(active_packages.begin(),
+ active_packages.end(),
+ [](const apex::ApexFile& package){
+ return package.GetManifest().name() == "com.android.runtime";
+ })) {
+ LOG(FATAL_WITHOUT_ABORT) << "No activated com.android.runtime APEX package.";
+ DeactivateApexPackages(active_packages);
+ exit(217);
+ }
+
// Now go on and run otapreopt.
// Incoming: cmd + status-fd + target-slot + cmd... | Incoming | = argc
diff --git a/cmds/installd/tests/installd_dexopt_test.cpp b/cmds/installd/tests/installd_dexopt_test.cpp
index 13fd067..73780ec 100644
--- a/cmds/installd/tests/installd_dexopt_test.cpp
+++ b/cmds/installd/tests/installd_dexopt_test.cpp
@@ -241,18 +241,14 @@
}
::testing::AssertionResult create_mock_app() {
- // Create the oat dir.
- app_oat_dir_ = app_apk_dir_ + "/oat";
// For debug mode, the directory might already exist. Avoid erroring out.
if (mkdir(app_apk_dir_, kSystemUid, kSystemGid, 0755) != 0 && !kDebug) {
return ::testing::AssertionFailure() << "Could not create app dir " << app_apk_dir_
<< " : " << strerror(errno);
}
- binder::Status status = service_->createOatDir(app_oat_dir_, kRuntimeIsa);
- if (!status.isOk()) {
- return ::testing::AssertionFailure() << "Could not create oat dir: "
- << status.toString8().c_str();
- }
+
+ // Initialize the oat dir path.
+ app_oat_dir_ = app_apk_dir_ + "/oat";
// Copy the primary apk.
apk_path_ = app_apk_dir_ + "/base.jar";
@@ -283,7 +279,7 @@
}
// Create the app user data.
- status = service_->createAppData(
+ binder::Status status = service_->createAppData(
volume_uuid_,
package_name_,
kTestUserId,
@@ -647,6 +643,16 @@
DEX2OAT_FROM_SCRATCH);
}
+TEST_F(DexoptTest, DexoptPrimaryPublicCreateOatDir) {
+ LOG(INFO) << "DexoptPrimaryPublic";
+ ASSERT_BINDER_SUCCESS(service_->createOatDir(app_oat_dir_, kRuntimeIsa));
+ CompilePrimaryDexOk("verify",
+ DEXOPT_BOOTCOMPLETE | DEXOPT_PUBLIC,
+ app_oat_dir_.c_str(),
+ kTestAppGid,
+ DEX2OAT_FROM_SCRATCH);
+}
+
TEST_F(DexoptTest, DexoptPrimaryFailedInvalidFilter) {
LOG(INFO) << "DexoptPrimaryFailedInvalidFilter";
binder::Status status;
diff --git a/cmds/lshal/Android.bp b/cmds/lshal/Android.bp
index 93d878b..f8b8c68 100644
--- a/cmds/lshal/Android.bp
+++ b/cmds/lshal/Android.bp
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-cc_library_shared {
+cc_library_static {
name: "liblshal",
shared_libs: [
"libbase",
@@ -36,6 +36,7 @@
"TableEntry.cpp",
"TextTable.cpp",
"utils.cpp",
+ "WaitCommand.cpp",
],
cflags: [
"-Wall",
@@ -47,13 +48,16 @@
name: "lshal_defaults",
shared_libs: [
"libbase",
- "libhidlbase",
- "libhidl-gen-utils",
- "libhidltransport",
- "liblshal",
+ "libcutils",
"libutils",
+ "libhidlbase",
+ "libhidltransport",
+ "libhidl-gen-hash",
+ "libhidl-gen-utils",
+ "libvintf",
],
static_libs: [
+ "liblshal",
"libprocpartition",
],
cflags: ["-Wall", "-Werror"],
@@ -69,14 +73,18 @@
cc_test {
name: "lshal_test",
+ test_suites: ["device-tests"],
defaults: ["lshal_defaults"],
gtest: true,
static_libs: [
- "libgmock"
+ "android.hardware.tests.baz@1.0",
+ "libgmock",
],
shared_libs: [
+ "libhwbinder",
+ "libhidlbase",
+ "libhidltransport",
"libvintf",
- "android.hardware.tests.baz@1.0"
],
srcs: [
"test.cpp"
diff --git a/cmds/lshal/Command.h b/cmds/lshal/Command.h
index e19e3f7..84809d9 100644
--- a/cmds/lshal/Command.h
+++ b/cmds/lshal/Command.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_COMMAND_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_COMMAND_H_
+#pragma once
#include "utils.h"
@@ -48,5 +47,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_LIST_COMMAND_H_
diff --git a/cmds/lshal/DebugCommand.cpp b/cmds/lshal/DebugCommand.cpp
index 0952db6..af22ac9 100644
--- a/cmds/lshal/DebugCommand.cpp
+++ b/cmds/lshal/DebugCommand.cpp
@@ -79,7 +79,7 @@
" lshal debug [-E] <interface> [options [options [...]]] \n"
" Print debug information of a specified interface.\n"
" -E: excludes debug output if HAL is actually a subclass.\n"
- " <inteface>: Format is `android.hardware.foo@1.0::IFoo/default`.\n"
+ " <interface>: Format is `android.hardware.foo@1.0::IFoo/default`.\n"
" If instance name is missing `default` is used.\n"
" options: space separated options to IBase::debug.\n";
@@ -88,4 +88,3 @@
} // namespace lshal
} // namespace android
-
diff --git a/cmds/lshal/DebugCommand.h b/cmds/lshal/DebugCommand.h
index 3c3f56f..cd57e31 100644
--- a/cmds/lshal/DebugCommand.h
+++ b/cmds/lshal/DebugCommand.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_DEBUG_COMMAND_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_DEBUG_COMMAND_H_
+#pragma once
#include <string>
@@ -53,5 +52,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_DEBUG_COMMAND_H_
diff --git a/cmds/lshal/HelpCommand.h b/cmds/lshal/HelpCommand.h
index da0cba6..bfa8500 100644
--- a/cmds/lshal/HelpCommand.h
+++ b/cmds/lshal/HelpCommand.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_HELP_COMMAND_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_HELP_COMMAND_H_
+#pragma once
#include <string>
@@ -44,5 +43,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_HELP_COMMAND_H_
diff --git a/cmds/lshal/ListCommand.cpp b/cmds/lshal/ListCommand.cpp
index c706d91..ad7e4c4 100644
--- a/cmds/lshal/ListCommand.cpp
+++ b/cmds/lshal/ListCommand.cpp
@@ -975,7 +975,8 @@
" - DM: if the HAL is in the device manifest\n"
" - DC: if the HAL is in the device compatibility matrix\n"
" - FM: if the HAL is in the framework manifest\n"
- " - FC: if the HAL is in the framework compatibility matrix"});
+ " - FC: if the HAL is in the framework compatibility matrix\n"
+ " - X: if the HAL is in none of the above lists"});
mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
return OK;
diff --git a/cmds/lshal/ListCommand.h b/cmds/lshal/ListCommand.h
index 85195fc..b3ed23d 100644
--- a/cmds/lshal/ListCommand.h
+++ b/cmds/lshal/ListCommand.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_LIST_COMMAND_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_LIST_COMMAND_H_
+#pragma once
#include <getopt.h>
#include <stdint.h>
@@ -206,5 +205,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_LIST_COMMAND_H_
diff --git a/cmds/lshal/Lshal.cpp b/cmds/lshal/Lshal.cpp
index 8c83457..132b31e 100644
--- a/cmds/lshal/Lshal.cpp
+++ b/cmds/lshal/Lshal.cpp
@@ -26,7 +26,9 @@
#include <hidl/HidlTransportUtils.h>
#include "DebugCommand.h"
+#include "HelpCommand.h"
#include "ListCommand.h"
+#include "WaitCommand.h"
#include "PipeRelay.h"
namespace android {
@@ -49,6 +51,7 @@
mRegisteredCommands.push_back({std::make_unique<ListCommand>(*this)});
mRegisteredCommands.push_back({std::make_unique<DebugCommand>(*this)});
mRegisteredCommands.push_back({std::make_unique<HelpCommand>(*this)});
+ mRegisteredCommands.push_back({std::make_unique<WaitCommand>(*this)});
}
void Lshal::forEachCommand(const std::function<void(const Command* c)>& f) const {
diff --git a/cmds/lshal/Lshal.h b/cmds/lshal/Lshal.h
index 9457f1e..830bd87 100644
--- a/cmds/lshal/Lshal.h
+++ b/cmds/lshal/Lshal.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_LSHAL_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_LSHAL_H_
+#pragma once
#include <iostream>
#include <string>
@@ -25,7 +24,6 @@
#include <utils/StrongPointer.h>
#include "Command.h"
-#include "HelpCommand.h"
#include "NullableOStream.h"
#include "utils.h"
@@ -76,5 +74,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_LSHAL_H_
diff --git a/cmds/lshal/NullableOStream.h b/cmds/lshal/NullableOStream.h
index 737d3a2..7cffcf8 100644
--- a/cmds/lshal/NullableOStream.h
+++ b/cmds/lshal/NullableOStream.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
+#pragma once
#include <iostream>
@@ -69,5 +68,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
diff --git a/cmds/lshal/PipeRelay.h b/cmds/lshal/PipeRelay.h
index 8dc3093..835016041 100644
--- a/cmds/lshal/PipeRelay.h
+++ b/cmds/lshal/PipeRelay.h
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORKS_NATIVE_CMDS_LSHAL_PIPE_RELAY_H_
-
-#define FRAMEWORKS_NATIVE_CMDS_LSHAL_PIPE_RELAY_H_
+#pragma once
#include <android-base/macros.h>
#include <ostream>
@@ -53,6 +51,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORKS_NATIVE_CMDS_LSHAL_PIPE_RELAY_H_
-
diff --git a/cmds/lshal/TEST_MAPPING b/cmds/lshal/TEST_MAPPING
new file mode 100644
index 0000000..0320624
--- /dev/null
+++ b/cmds/lshal/TEST_MAPPING
@@ -0,0 +1,8 @@
+{
+ "presubmit": [
+ {
+ "name": "lshal_test"
+ }
+ ]
+}
+
diff --git a/cmds/lshal/TableEntry.h b/cmds/lshal/TableEntry.h
index 601b7e2..0ff0c96 100644
--- a/cmds/lshal/TableEntry.h
+++ b/cmds/lshal/TableEntry.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_TABLE_ENTRY_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_TABLE_ENTRY_H_
+#pragma once
#include <stdint.h>
@@ -157,5 +156,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_TABLE_ENTRY_H_
diff --git a/cmds/lshal/TextTable.h b/cmds/lshal/TextTable.h
index 301b4bd..be41a08 100644
--- a/cmds/lshal/TextTable.h
+++ b/cmds/lshal/TextTable.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_TEXT_TABLE_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_TEXT_TABLE_H_
+#pragma once
#include <iostream>
#include <string>
@@ -80,5 +79,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_TEXT_TABLE_H_
diff --git a/cmds/lshal/Timeout.h b/cmds/lshal/Timeout.h
index 46d8177..e8d22d9 100644
--- a/cmds/lshal/Timeout.h
+++ b/cmds/lshal/Timeout.h
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#pragma once
+
#include <condition_variable>
#include <chrono>
#include <functional>
diff --git a/cmds/lshal/WaitCommand.cpp b/cmds/lshal/WaitCommand.cpp
new file mode 100644
index 0000000..65b41b9
--- /dev/null
+++ b/cmds/lshal/WaitCommand.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2019 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 "WaitCommand.h"
+
+#include "Lshal.h"
+
+#include <hidl/ServiceManagement.h>
+#include <hidl-util/FQName.h>
+
+namespace android {
+namespace lshal {
+
+std::string WaitCommand::getName() const {
+ return "wait";
+}
+
+std::string WaitCommand::getSimpleDescription() const {
+ return "Wait for HAL to start if it is not already started.";
+}
+
+Status WaitCommand::parseArgs(const Arg &arg) {
+ if (optind + 1 != arg.argc) {
+ return USAGE;
+ }
+
+ mInterfaceName = arg.argv[optind];
+ ++optind;
+ return OK;
+}
+
+Status WaitCommand::main(const Arg &arg) {
+ Status status = parseArgs(arg);
+ if (status != OK) {
+ return status;
+ }
+
+ auto [interface, instance] = splitFirst(mInterfaceName, '/');
+ instance = instance.empty() ? "default" : instance;
+
+ FQName fqName;
+ if (!FQName::parse(interface, &fqName) || fqName.isIdentifier() || !fqName.isFullyQualified()) {
+ mLshal.err() << "Invalid fully-qualified name '" << interface << "'\n\n";
+ return USAGE;
+ }
+
+ using android::hidl::manager::V1_0::IServiceManager;
+
+ using android::hardware::details::getRawServiceInternal;
+ auto service = getRawServiceInternal(interface, instance, true /*retry*/, false /*getStub*/);
+
+ if (service == nullptr) {
+ mLshal.err() << "Service not found (missing permissions or not in VINTF manifest?).\n";
+ return NO_INTERFACE;
+ }
+
+ return OK;
+}
+
+void WaitCommand::usage() const {
+ static const std::string debug =
+ "wait:\n"
+ " lshal wait <interface/instance> \n"
+ " For a HAL that is on the device, wait for the HAL to start.\n"
+ " This will not start a HAL unless it is configured as a lazy HAL.\n"
+ " <interface>: Format is `android.hardware.foo@1.0::IFoo/default`.\n"
+ " If instance name is missing `default` is used.\n";
+
+ mLshal.err() << debug;
+}
+
+} // namespace lshal
+} // namespace android
+
diff --git a/cmds/lshal/WaitCommand.h b/cmds/lshal/WaitCommand.h
new file mode 100644
index 0000000..c9f67c2
--- /dev/null
+++ b/cmds/lshal/WaitCommand.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#pragma once
+
+#include <string>
+
+#include <android-base/macros.h>
+
+#include "Command.h"
+#include "utils.h"
+
+namespace android {
+namespace lshal {
+
+class Lshal;
+
+class WaitCommand : public Command {
+public:
+ explicit WaitCommand(Lshal &lshal) : Command(lshal) {}
+ ~WaitCommand() = default;
+ Status main(const Arg &arg) override;
+ void usage() const override;
+ std::string getSimpleDescription() const override;
+ std::string getName() const override;
+private:
+ Status parseArgs(const Arg &arg);
+
+ std::string mInterfaceName;
+
+ DISALLOW_COPY_AND_ASSIGN(WaitCommand);
+};
+
+
+} // namespace lshal
+} // namespace android
diff --git a/cmds/lshal/libprocpartition/include/procpartition/procpartition.h b/cmds/lshal/libprocpartition/include/procpartition/procpartition.h
index 7e86432..ca1e690 100644
--- a/cmds/lshal/libprocpartition/include/procpartition/procpartition.h
+++ b/cmds/lshal/libprocpartition/include/procpartition/procpartition.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_PROCPARTITION_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_PROCPARTITION_H_
+#pragma once
#include <sys/types.h>
@@ -44,5 +43,3 @@
} // namespace procpartition
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_PROCPARTITION_H_
diff --git a/cmds/lshal/test.cpp b/cmds/lshal/test.cpp
index fc8d58b..76f7c7f 100644
--- a/cmds/lshal/test.cpp
+++ b/cmds/lshal/test.cpp
@@ -493,19 +493,19 @@
TEST_F(ListTest, DumpDefault) {
const std::string expected =
"[fake description 0]\n"
- "R Interface Thread Use Server Clients\n"
- "N a.h.foo1@1.0::IFoo/1 11/21 1 2 4\n"
- "Y a.h.foo2@2.0::IFoo/2 12/22 2 3 5\n"
+ "VINTF R Interface Thread Use Server Clients\n"
+ "X N a.h.foo1@1.0::IFoo/1 11/21 1 2 4\n"
+ "X Y a.h.foo2@2.0::IFoo/2 12/22 2 3 5\n"
"\n"
"[fake description 1]\n"
- "R Interface Thread Use Server Clients\n"
- "? a.h.foo3@3.0::IFoo/3 N/A N/A 4 6\n"
- "? a.h.foo4@4.0::IFoo/4 N/A N/A 5 7\n"
+ "VINTF R Interface Thread Use Server Clients\n"
+ "X ? a.h.foo3@3.0::IFoo/3 N/A N/A 4 6\n"
+ "X ? a.h.foo4@4.0::IFoo/4 N/A N/A 5 7\n"
"\n"
"[fake description 2]\n"
- "R Interface Thread Use Server Clients\n"
- "? a.h.foo5@5.0::IFoo/5 N/A N/A 6 8\n"
- "? a.h.foo6@6.0::IFoo/6 N/A N/A 7 9\n"
+ "VINTF R Interface Thread Use Server Clients\n"
+ "X ? a.h.foo5@5.0::IFoo/5 N/A N/A 6 8\n"
+ "X ? a.h.foo6@6.0::IFoo/6 N/A N/A 7 9\n"
"\n";
optind = 1; // mimic Lshal::parseArg()
diff --git a/cmds/lshal/utils.h b/cmds/lshal/utils.h
index 240155e..04f5272 100644
--- a/cmds/lshal/utils.h
+++ b/cmds/lshal/utils.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_UTILS_H_
-#define FRAMEWORK_NATIVE_CMDS_LSHAL_UTILS_H_
+#pragma once
#include <iomanip>
#include <iostream>
@@ -88,5 +87,3 @@
} // namespace lshal
} // namespace android
-
-#endif // FRAMEWORK_NATIVE_CMDS_LSHAL_UTILS_H_
diff --git a/cmds/service/Android.bp b/cmds/service/Android.bp
index 9513ec1..a5b1ac5 100644
--- a/cmds/service/Android.bp
+++ b/cmds/service/Android.bp
@@ -4,6 +4,7 @@
srcs: ["service.cpp"],
shared_libs: [
+ "libcutils",
"libutils",
"libbinder",
],
@@ -22,6 +23,7 @@
srcs: ["service.cpp"],
shared_libs: [
+ "libcutils",
"libutils",
"libbinder",
],
diff --git a/cmds/service/service.cpp b/cmds/service/service.cpp
index 34a3fdc..18b6b58 100644
--- a/cmds/service/service.cpp
+++ b/cmds/service/service.cpp
@@ -18,13 +18,18 @@
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <binder/TextOutput.h>
+#include <cutils/ashmem.h>
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
+#include <sys/mman.h>
#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
using namespace android;
@@ -70,7 +75,7 @@
{
bool wantsUsage = false;
int result = 0;
-
+
while (1) {
int ic = getopt(argc, argv, "h?");
if (ic < 0)
@@ -97,7 +102,7 @@
aerr << "service: Unable to get default service manager!" << endl;
return 20;
}
-
+
if (optind >= argc) {
wantsUsage = true;
} else if (!wantsUsage) {
@@ -119,8 +124,8 @@
for (unsigned i = 0; i < services.size(); i++) {
String16 name = services[i];
sp<IBinder> service = sm->checkService(name);
- aout << i
- << "\t" << good_old_string(name)
+ aout << i
+ << "\t" << good_old_string(name)
<< ": [" << good_old_string(get_interface_name(service)) << "]"
<< endl;
}
@@ -187,70 +192,120 @@
} else if (strcmp(argv[optind], "null") == 0) {
optind++;
data.writeStrongBinder(nullptr);
- } else if (strcmp(argv[optind], "intent") == 0) {
-
- char* action = nullptr;
- char* dataArg = nullptr;
- char* type = nullptr;
- int launchFlags = 0;
- char* component = nullptr;
- int categoryCount = 0;
- char* categories[16];
-
- char* context1 = nullptr;
-
+ } else if (strcmp(argv[optind], "fd") == 0) {
optind++;
-
- while (optind < argc)
- {
- char* key = strtok_r(argv[optind], "=", &context1);
- char* value = strtok_r(nullptr, "=", &context1);
-
+ if (optind >= argc) {
+ aerr << "service: no path supplied for 'fd'" << endl;
+ wantsUsage = true;
+ result = 10;
+ break;
+ }
+ const char *path = argv[optind++];
+ int fd = open(path, O_RDONLY);
+ if (fd < 0) {
+ aerr << "service: could not open '" << path << "'" << endl;
+ wantsUsage = true;
+ result = 10;
+ break;
+ }
+ data.writeFileDescriptor(fd, true /* take ownership */);
+ } else if (strcmp(argv[optind], "afd") == 0) {
+ optind++;
+ if (optind >= argc) {
+ aerr << "service: no path supplied for 'afd'" << endl;
+ wantsUsage = true;
+ result = 10;
+ break;
+ }
+ const char *path = argv[optind++];
+ int fd = open(path, O_RDONLY);
+ struct stat statbuf;
+ if (fd < 0 || fstat(fd, &statbuf) != 0) {
+ aerr << "service: could not open or stat '" << path << "'" << endl;
+ wantsUsage = true;
+ result = 10;
+ break;
+ }
+ int afd = ashmem_create_region("test", statbuf.st_size);
+ void* ptr = mmap(NULL, statbuf.st_size,
+ PROT_READ | PROT_WRITE, MAP_SHARED, afd, 0);
+ read(fd, ptr, statbuf.st_size);
+ close(fd);
+ data.writeFileDescriptor(afd, true /* take ownership */);
+ } else if (strcmp(argv[optind], "nfd") == 0) {
+ optind++;
+ if (optind >= argc) {
+ aerr << "service: no file descriptor supplied for 'nfd'" << endl;
+ wantsUsage = true;
+ result = 10;
+ break;
+ }
+ data.writeFileDescriptor(
+ atoi(argv[optind++]), true /* take ownership */);
+
+ } else if (strcmp(argv[optind], "intent") == 0) {
+
+ char* action = nullptr;
+ char* dataArg = nullptr;
+ char* type = nullptr;
+ int launchFlags = 0;
+ char* component = nullptr;
+ int categoryCount = 0;
+ char* categories[16];
+
+ char* context1 = nullptr;
+
+ optind++;
+
+ while (optind < argc)
+ {
+ char* key = strtok_r(argv[optind], "=", &context1);
+ char* value = strtok_r(nullptr, "=", &context1);
+
// we have reached the end of the XXX=XXX args.
if (key == nullptr) break;
-
- if (strcmp(key, "action") == 0)
- {
- action = value;
- }
- else if (strcmp(key, "data") == 0)
- {
- dataArg = value;
- }
- else if (strcmp(key, "type") == 0)
- {
- type = value;
- }
- else if (strcmp(key, "launchFlags") == 0)
- {
- launchFlags = atoi(value);
- }
- else if (strcmp(key, "component") == 0)
- {
- component = value;
- }
- else if (strcmp(key, "categories") == 0)
- {
- char* context2 = nullptr;
- int categoryCount = 0;
- categories[categoryCount] = strtok_r(value, ",", &context2);
-
- while (categories[categoryCount] != nullptr)
- {
- categoryCount++;
- categories[categoryCount] = strtok_r(nullptr, ",", &context2);
- }
- }
-
+
+ if (strcmp(key, "action") == 0)
+ {
+ action = value;
+ }
+ else if (strcmp(key, "data") == 0)
+ {
+ dataArg = value;
+ }
+ else if (strcmp(key, "type") == 0)
+ {
+ type = value;
+ }
+ else if (strcmp(key, "launchFlags") == 0)
+ {
+ launchFlags = atoi(value);
+ }
+ else if (strcmp(key, "component") == 0)
+ {
+ component = value;
+ }
+ else if (strcmp(key, "categories") == 0)
+ {
+ char* context2 = nullptr;
+ categories[categoryCount] = strtok_r(value, ",", &context2);
+
+ while (categories[categoryCount] != nullptr)
+ {
+ categoryCount++;
+ categories[categoryCount] = strtok_r(nullptr, ",", &context2);
+ }
+ }
+
optind++;
- }
-
+ }
+
writeString16(data, action);
writeString16(data, dataArg);
writeString16(data, type);
- data.writeInt32(launchFlags);
+ data.writeInt32(launchFlags);
writeString16(data, component);
-
+
if (categoryCount > 0)
{
data.writeInt32(categoryCount);
@@ -262,10 +317,10 @@
else
{
data.writeInt32(0);
- }
-
+ }
+
// for now just set the extra field to be null.
- data.writeInt32(-1);
+ data.writeInt32(-1);
} else {
aerr << "service: unknown option " << argv[optind] << endl;
wantsUsage = true;
@@ -273,7 +328,7 @@
break;
}
}
-
+
service->transact(code, data, &reply);
aout << "Result: " << reply << endl;
} else {
@@ -296,23 +351,29 @@
result = 10;
}
}
-
+
if (wantsUsage) {
aout << "Usage: service [-h|-?]\n"
" service list\n"
" service check SERVICE\n"
- " service call SERVICE CODE [i32 N | i64 N | f N | d N | s16 STR ] ...\n"
+ " service call SERVICE CODE [i32 N | i64 N | f N | d N | s16 STR | null"
+ " | fd f | nfd n | afd f ] ...\n"
"Options:\n"
" i32: Write the 32-bit integer N into the send parcel.\n"
" i64: Write the 64-bit integer N into the send parcel.\n"
" f: Write the 32-bit single-precision number N into the send parcel.\n"
" d: Write the 64-bit double-precision number N into the send parcel.\n"
- " s16: Write the UTF-16 string STR into the send parcel.\n";
+ " s16: Write the UTF-16 string STR into the send parcel.\n"
+ " null: Write a null binder into the send parcel.\n"
+ " fd: Write a file descriptor for the file f to the send parcel.\n"
+ " nfd: Write file descriptor n to the send parcel.\n"
+ " afd: Write an ashmem file descriptor for a region containing the data from"
+ " file f to the send parcel.\n";
// " intent: Write and Intent int the send parcel. ARGS can be\n"
// " action=STR data=STR type=STR launchFlags=INT component=STR categories=STR[,STR,...]\n";
return result;
}
-
+
return result;
}
diff --git a/data/etc/android.hardware.se.omapi.ese.xml b/data/etc/android.hardware.se.omapi.ese.xml
new file mode 100644
index 0000000..3b1d81c
--- /dev/null
+++ b/data/etc/android.hardware.se.omapi.ese.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<!-- This feature indicates that the device supports The device supports
+ Open Mobile API capable ESE-based secure elements-->
+<permissions>
+ <feature name="android.hardware.se.omapi.ese" />
+</permissions>
diff --git a/data/etc/android.hardware.se.omapi.sd.xml b/data/etc/android.hardware.se.omapi.sd.xml
new file mode 100644
index 0000000..8fc2869
--- /dev/null
+++ b/data/etc/android.hardware.se.omapi.sd.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<!-- This feature indicates that the device supports The device supports
+ Open Mobile API capable SD-based secure elements-->
+<permissions>
+ <feature name="android.hardware.se.omapi.sd" />
+</permissions>
diff --git a/data/etc/android.hardware.se.omapi.uicc.xml b/data/etc/android.hardware.se.omapi.uicc.xml
new file mode 100644
index 0000000..9c6f143
--- /dev/null
+++ b/data/etc/android.hardware.se.omapi.uicc.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<!-- This feature indicates that the device supports The device supports
+ Open Mobile API capable UICC-based secure elements-->
+<permissions>
+ <feature name="android.hardware.se.omapi.uicc" />
+</permissions>
diff --git a/data/etc/android.software.ipsec_tunnels.xml b/data/etc/android.software.ipsec_tunnels.xml
new file mode 100644
index 0000000..f7ffc02
--- /dev/null
+++ b/data/etc/android.software.ipsec_tunnels.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 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.
+-->
+
+<!--
+ This is the feature indicating that the device has support for multinetworking-capable IPsec
+ tunnels
+-->
+
+<permissions>
+ <feature name="android.software.ipsec_tunnels" />
+</permissions>
diff --git a/include/audiomanager/OWNERS b/include/audiomanager/OWNERS
new file mode 100644
index 0000000..2bd527c
--- /dev/null
+++ b/include/audiomanager/OWNERS
@@ -0,0 +1,2 @@
+elaurent@google.com
+jmtrivi@google.com
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index da10687..4222e36 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -70,10 +70,10 @@
"ProcessInfoService.cpp",
"ProcessState.cpp",
"Static.cpp",
+ "Stability.cpp",
"Status.cpp",
"TextOutput.cpp",
"IpPrefix.cpp",
- "Value.cpp",
":libbinder_aidl",
],
@@ -115,7 +115,6 @@
},
shared_libs: [
- "libbase",
"liblog",
"libcutils",
"libutils",
@@ -142,6 +141,7 @@
srcs: [
"aidl/android/content/pm/IPackageManagerNative.aidl",
],
+ path: "aidl",
}
subdirs = ["tests"]
diff --git a/libs/binder/Binder.cpp b/libs/binder/Binder.cpp
index 96ee295..985d817 100644
--- a/libs/binder/Binder.cpp
+++ b/libs/binder/Binder.cpp
@@ -124,19 +124,22 @@
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
data.setDataPosition(0);
+ data.setTransactingBinder(this);
status_t err = NO_ERROR;
switch (code) {
case PING_TRANSACTION:
- reply->writeInt32(pingBinder());
+ err = pingBinder();
break;
default:
err = onTransact(code, data, reply, flags);
break;
}
+ // In case this is being transacted on in the same process.
if (reply != nullptr) {
reply->setDataPosition(0);
+ reply->setTransactingBinder(this);
}
return err;
diff --git a/libs/binder/BpBinder.cpp b/libs/binder/BpBinder.cpp
index ec170f7..57440d5 100644
--- a/libs/binder/BpBinder.cpp
+++ b/libs/binder/BpBinder.cpp
@@ -148,6 +148,10 @@
IPCThreadState::self()->incWeakHandle(handle, this);
}
+int32_t BpBinder::handle() const {
+ return mHandle;
+}
+
bool BpBinder::isDescriptorCached() const {
Mutex::Autolock _l(mLock);
return mDescriptorCache.size() ? true : false;
@@ -186,10 +190,7 @@
{
Parcel send;
Parcel reply;
- status_t err = transact(PING_TRANSACTION, send, &reply);
- if (err != NO_ERROR) return err;
- if (reply.dataSize() < sizeof(status_t)) return NOT_ENOUGH_DATA;
- return (status_t)reply.readInt32();
+ return transact(PING_TRANSACTION, send, &reply);
}
status_t BpBinder::dump(int fd, const Vector<String16>& args)
@@ -215,6 +216,11 @@
status_t status = IPCThreadState::self()->transact(
mHandle, code, data, reply, flags);
if (status == DEAD_OBJECT) mAlive = 0;
+
+ if (reply != nullptr) {
+ reply->setTransactingBinder(this);
+ }
+
return status;
}
@@ -387,21 +393,6 @@
}
}
- mLock.lock();
- Vector<Obituary>* obits = mObituaries;
- if(obits != nullptr) {
- if (ipc) ipc->clearDeathNotification(mHandle, this);
- mObituaries = nullptr;
- }
- mLock.unlock();
-
- if (obits != nullptr) {
- // XXX Should we tell any remaining DeathRecipient
- // objects that the last strong ref has gone away, so they
- // are no longer linked?
- delete obits;
- }
-
if (ipc) {
ipc->expungeHandle(mHandle, this);
ipc->decWeakHandle(mHandle);
@@ -423,6 +414,25 @@
}
IPCThreadState* ipc = IPCThreadState::self();
if (ipc) ipc->decStrongHandle(mHandle);
+
+ mLock.lock();
+ Vector<Obituary>* obits = mObituaries;
+ if(obits != nullptr) {
+ if (!obits->isEmpty()) {
+ ALOGI("onLastStrongRef automatically unlinking death recipients");
+ }
+
+ if (ipc) ipc->clearDeathNotification(mHandle, this);
+ mObituaries = nullptr;
+ }
+ mLock.unlock();
+
+ if (obits != nullptr) {
+ // XXX Should we tell any remaining DeathRecipient
+ // objects that the last strong ref has gone away, so they
+ // are no longer linked?
+ delete obits;
+ }
}
bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
diff --git a/libs/binder/BufferedTextOutput.cpp b/libs/binder/BufferedTextOutput.cpp
index 857bbf9..a7d5240 100644
--- a/libs/binder/BufferedTextOutput.cpp
+++ b/libs/binder/BufferedTextOutput.cpp
@@ -23,12 +23,12 @@
#include <utils/RefBase.h>
#include <utils/Vector.h>
-#include <private/binder/Static.h>
-
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
+#include "Static.h"
+
// ---------------------------------------------------------------------------
namespace android {
diff --git a/libs/binder/IAppOpsCallback.cpp b/libs/binder/IAppOpsCallback.cpp
index 2f4dbee..41a0111 100644
--- a/libs/binder/IAppOpsCallback.cpp
+++ b/libs/binder/IAppOpsCallback.cpp
@@ -22,8 +22,6 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
-#include <private/binder/Static.h>
-
namespace android {
// ----------------------------------------------------------------------
diff --git a/libs/binder/IAppOpsService.cpp b/libs/binder/IAppOpsService.cpp
index fb0d521..c839ba5 100644
--- a/libs/binder/IAppOpsService.cpp
+++ b/libs/binder/IAppOpsService.cpp
@@ -22,8 +22,6 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
-#include <private/binder/Static.h>
-
namespace android {
// ----------------------------------------------------------------------
diff --git a/libs/binder/IBatteryStats.cpp b/libs/binder/IBatteryStats.cpp
index b307e3e..cc0022a 100644
--- a/libs/binder/IBatteryStats.cpp
+++ b/libs/binder/IBatteryStats.cpp
@@ -20,8 +20,6 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
-#include <private/binder/Static.h>
-
namespace android {
// ----------------------------------------------------------------------
diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
index 7eec245..4356706 100644
--- a/libs/binder/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -31,7 +31,6 @@
#include <utils/threads.h>
#include <private/binder/binder_module.h>
-#include <private/binder/Static.h>
#include <atomic>
#include <errno.h>
@@ -44,6 +43,8 @@
#include <sys/resource.h>
#include <unistd.h>
+#include "Static.h"
+
#if LOG_NDEBUG
#define IF_LOG_TRANSACTIONS() if (false)
@@ -420,7 +421,7 @@
void IPCThreadState::flushCommands()
{
- if (mProcess->mDriverFD <= 0)
+ if (mProcess->mDriverFD < 0)
return;
talkWithDriver(false);
// The flush could have caused post-write refcount decrements to have
@@ -573,7 +574,7 @@
int IPCThreadState::setupPolling(int* fd)
{
- if (mProcess->mDriverFD <= 0) {
+ if (mProcess->mDriverFD < 0) {
return -EBADF;
}
@@ -632,11 +633,11 @@
if ((flags & TF_ONE_WAY) == 0) {
if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
- ALOGE("Process making non-oneway call but is restricted.");
+ ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
ANDROID_LOG_ERROR);
} else /* FATAL_IF_NOT_ONEWAY */ {
- LOG_ALWAYS_FATAL("Process may not make oneway calls.");
+ LOG_ALWAYS_FATAL("Process may not make oneway calls (code: %u).", code);
}
}
@@ -877,7 +878,7 @@
status_t IPCThreadState::talkWithDriver(bool doReceive)
{
- if (mProcess->mDriverFD <= 0) {
+ if (mProcess->mDriverFD < 0) {
return -EBADF;
}
@@ -935,7 +936,7 @@
#else
err = INVALID_OPERATION;
#endif
- if (mProcess->mDriverFD <= 0) {
+ if (mProcess->mDriverFD < 0) {
err = -EBADF;
}
IF_LOG_COMMANDS() {
@@ -952,7 +953,7 @@
if (err >= NO_ERROR) {
if (bwr.write_consumed > 0) {
if (bwr.write_consumed < mOut.dataSize())
- mOut.remove(0, bwr.write_consumed);
+ LOG_ALWAYS_FATAL("Driver did not consume write buffer");
else {
mOut.setDataSize(0);
processPostWriteDerefs();
@@ -1245,7 +1246,7 @@
if (self) {
self->flushCommands();
#if defined(__ANDROID__)
- if (self->mProcess->mDriverFD > 0) {
+ if (self->mProcess->mDriverFD >= 0) {
ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
}
#endif
diff --git a/libs/binder/IPermissionController.cpp b/libs/binder/IPermissionController.cpp
index 6b99150..bf2f20a 100644
--- a/libs/binder/IPermissionController.cpp
+++ b/libs/binder/IPermissionController.cpp
@@ -22,8 +22,6 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
-#include <private/binder/Static.h>
-
namespace android {
// ----------------------------------------------------------------------
diff --git a/libs/binder/IResultReceiver.cpp b/libs/binder/IResultReceiver.cpp
index 159763d..1e11941 100644
--- a/libs/binder/IResultReceiver.cpp
+++ b/libs/binder/IResultReceiver.cpp
@@ -22,8 +22,6 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
-#include <private/binder/Static.h>
-
namespace android {
// ----------------------------------------------------------------------
diff --git a/libs/binder/IServiceManager.cpp b/libs/binder/IServiceManager.cpp
index 0203d41..9d816e8 100644
--- a/libs/binder/IServiceManager.cpp
+++ b/libs/binder/IServiceManager.cpp
@@ -28,7 +28,7 @@
#include <utils/String8.h>
#include <utils/SystemClock.h>
-#include <private/binder/Static.h>
+#include "Static.h"
#include <unistd.h>
diff --git a/libs/binder/IShellCallback.cpp b/libs/binder/IShellCallback.cpp
index 6c697de..88cc603 100644
--- a/libs/binder/IShellCallback.cpp
+++ b/libs/binder/IShellCallback.cpp
@@ -25,8 +25,6 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
-#include <private/binder/Static.h>
-
namespace android {
// ----------------------------------------------------------------------
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index 9f8c408..a2333ae 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -37,7 +37,6 @@
#include <binder/ProcessState.h>
#include <binder/Status.h>
#include <binder/TextOutput.h>
-#include <binder/Value.h>
#include <cutils/ashmem.h>
#include <utils/Debug.h>
@@ -48,7 +47,7 @@
#include <utils/String16.h>
#include <private/binder/binder_module.h>
-#include <private/binder/Static.h>
+#include "Static.h"
#ifndef INT32_MAX
#define INT32_MAX ((int32_t)(2147483647))
@@ -93,7 +92,7 @@
BLOB_ASHMEM_MUTABLE = 2,
};
-void acquire_object(const sp<ProcessState>& proc,
+static void acquire_object(const sp<ProcessState>& proc,
const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
{
switch (obj.hdr.type) {
@@ -103,10 +102,6 @@
reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
}
return;
- case BINDER_TYPE_WEAK_BINDER:
- if (obj.binder)
- reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
- return;
case BINDER_TYPE_HANDLE: {
const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
if (b != nullptr) {
@@ -115,11 +110,6 @@
}
return;
}
- case BINDER_TYPE_WEAK_HANDLE: {
- const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
- if (b != nullptr) b.get_refs()->incWeak(who);
- return;
- }
case BINDER_TYPE_FD: {
if ((obj.cookie != 0) && (outAshmemSize != nullptr) && ashmem_valid(obj.handle)) {
// If we own an ashmem fd, keep track of how much memory it refers to.
@@ -135,12 +125,6 @@
ALOGD("Invalid object type 0x%08x", obj.hdr.type);
}
-void acquire_object(const sp<ProcessState>& proc,
- const flat_binder_object& obj, const void* who)
-{
- acquire_object(proc, obj, who, nullptr);
-}
-
static void release_object(const sp<ProcessState>& proc,
const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
{
@@ -151,10 +135,6 @@
reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
}
return;
- case BINDER_TYPE_WEAK_BINDER:
- if (obj.binder)
- reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
- return;
case BINDER_TYPE_HANDLE: {
const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
if (b != nullptr) {
@@ -163,11 +143,6 @@
}
return;
}
- case BINDER_TYPE_WEAK_HANDLE: {
- const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
- if (b != nullptr) b.get_refs()->decWeak(who);
- return;
- }
case BINDER_TYPE_FD: {
if (obj.cookie != 0) { // owned
if ((outAshmemSize != nullptr) && ashmem_valid(obj.handle)) {
@@ -189,20 +164,39 @@
ALOGE("Invalid object type 0x%08x", obj.hdr.type);
}
-void release_object(const sp<ProcessState>& proc,
- const flat_binder_object& obj, const void* who)
+status_t Parcel::finishFlattenBinder(
+ const sp<IBinder>& /*binder*/, const flat_binder_object& flat)
{
- release_object(proc, obj, who, nullptr);
+ // internal::Stability::tryMarkCompilationUnit(binder.get());
+
+ status_t status = writeObject(flat, false);
+ if (status != OK) return status;
+
+ // Cannot change wire protocol w/o SM update
+ // return writeInt32(internal::Stability::get(binder.get()));
+ return OK;
}
-inline static status_t finish_flatten_binder(
- const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
+status_t Parcel::finishUnflattenBinder(
+ const sp<IBinder>& binder, sp<IBinder>* out) const
{
- return out->writeObject(flat, false);
+ // int32_t stability;
+ // Cannot change wire protocol w/o SM update
+ // status_t status = readInt32(&stability);
+ // if (status != OK) return status;
+
+ // if (binder != nullptr && !internal::Stability::check(stability, mRequiredStability)) {
+ // return BAD_TYPE;
+ // }
+
+ // status = internal::Stability::set(binder.get(), stability, true /*log*/);
+ // if (status != OK) return status;
+
+ *out = binder;
+ return OK;
}
-status_t flatten_binder(const sp<ProcessState>& /*proc*/,
- const sp<IBinder>& binder, Parcel* out)
+status_t Parcel::flattenBinder(const sp<IBinder>& binder)
{
flat_binder_object obj;
@@ -240,108 +234,24 @@
obj.cookie = 0;
}
- return finish_flatten_binder(binder, obj, out);
+ return finishFlattenBinder(binder, obj);
}
-status_t flatten_binder(const sp<ProcessState>& /*proc*/,
- const wp<IBinder>& binder, Parcel* out)
+status_t Parcel::unflattenBinder(sp<IBinder>* out) const
{
- flat_binder_object obj;
+ const flat_binder_object* flat = readObject(false);
- obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
- if (binder != nullptr) {
- sp<IBinder> real = binder.promote();
- if (real != nullptr) {
- IBinder *local = real->localBinder();
- if (!local) {
- BpBinder *proxy = real->remoteBinder();
- if (proxy == nullptr) {
- ALOGE("null proxy");
- }
- const int32_t handle = proxy ? proxy->handle() : 0;
- obj.hdr.type = BINDER_TYPE_WEAK_HANDLE;
- obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
- obj.handle = handle;
- obj.cookie = 0;
- } else {
- obj.hdr.type = BINDER_TYPE_WEAK_BINDER;
- obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
- obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
+ if (flat) {
+ switch (flat->hdr.type) {
+ case BINDER_TYPE_BINDER: {
+ sp<IBinder> binder = reinterpret_cast<IBinder*>(flat->cookie);
+ return finishUnflattenBinder(binder, out);
}
- return finish_flatten_binder(real, obj, out);
- }
-
- // XXX How to deal? In order to flatten the given binder,
- // we need to probe it for information, which requires a primary
- // reference... but we don't have one.
- //
- // The OpenBinder implementation uses a dynamic_cast<> here,
- // but we can't do that with the different reference counting
- // implementation we are using.
- ALOGE("Unable to unflatten Binder weak reference!");
- obj.hdr.type = BINDER_TYPE_BINDER;
- obj.binder = 0;
- obj.cookie = 0;
- return finish_flatten_binder(nullptr, obj, out);
-
- } else {
- obj.hdr.type = BINDER_TYPE_BINDER;
- obj.binder = 0;
- obj.cookie = 0;
- return finish_flatten_binder(nullptr, obj, out);
- }
-}
-
-inline static status_t finish_unflatten_binder(
- BpBinder* /*proxy*/, const flat_binder_object& /*flat*/,
- const Parcel& /*in*/)
-{
- return NO_ERROR;
-}
-
-status_t unflatten_binder(const sp<ProcessState>& proc,
- const Parcel& in, sp<IBinder>* out)
-{
- const flat_binder_object* flat = in.readObject(false);
-
- if (flat) {
- switch (flat->hdr.type) {
- case BINDER_TYPE_BINDER:
- *out = reinterpret_cast<IBinder*>(flat->cookie);
- return finish_unflatten_binder(nullptr, *flat, in);
- case BINDER_TYPE_HANDLE:
- *out = proc->getStrongProxyForHandle(flat->handle);
- return finish_unflatten_binder(
- static_cast<BpBinder*>(out->get()), *flat, in);
- }
- }
- return BAD_TYPE;
-}
-
-status_t unflatten_binder(const sp<ProcessState>& proc,
- const Parcel& in, wp<IBinder>* out)
-{
- const flat_binder_object* flat = in.readObject(false);
-
- if (flat) {
- switch (flat->hdr.type) {
- case BINDER_TYPE_BINDER:
- *out = reinterpret_cast<IBinder*>(flat->cookie);
- return finish_unflatten_binder(nullptr, *flat, in);
- case BINDER_TYPE_WEAK_BINDER:
- if (flat->binder != 0) {
- out->set_object_and_refs(
- reinterpret_cast<IBinder*>(flat->cookie),
- reinterpret_cast<RefBase::weakref_type*>(flat->binder));
- } else {
- *out = nullptr;
- }
- return finish_unflatten_binder(nullptr, *flat, in);
- case BINDER_TYPE_HANDLE:
- case BINDER_TYPE_WEAK_HANDLE:
- *out = proc->getWeakProxyForHandle(flat->handle);
- return finish_unflatten_binder(
- static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
+ case BINDER_TYPE_HANDLE: {
+ sp<IBinder> binder =
+ ProcessState::self()->getStrongProxyForHandle(flat->handle);
+ return finishUnflattenBinder(binder, out);
+ }
}
}
return BAD_TYPE;
@@ -446,6 +356,10 @@
return NO_ERROR;
}
+void Parcel::setTransactingBinder(const sp<IBinder>& binder) const {
+ mRequiredStability = internal::Stability::get(binder.get());
+}
+
status_t Parcel::setData(const uint8_t* buffer, size_t len)
{
if (len > INT32_MAX) {
@@ -635,11 +549,6 @@
}
}
-const binder_size_t* Parcel::objects() const
-{
- return mObjects;
-}
-
size_t Parcel::objectsCount() const
{
return mObjectsSize;
@@ -1079,7 +988,7 @@
status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
- return flatten_binder(ProcessState::self(), val, this);
+ return flattenBinder(val);
}
status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val)
@@ -1100,11 +1009,6 @@
return readTypedVector(val, &Parcel::readStrongBinder);
}
-status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
-{
- return flatten_binder(ProcessState::self(), val, this);
-}
-
status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
if (!parcelable) {
return writeInt32(0);
@@ -1121,10 +1025,6 @@
return parcelable.writeToParcel(this);
}
-status_t Parcel::writeValue(const binder::Value& value) {
- return value.writeToParcel(this);
-}
-
status_t Parcel::writeNativeHandle(const native_handle* handle)
{
if (!handle || handle->version != sizeof(native_handle))
@@ -1362,125 +1262,6 @@
return status.writeToParcel(this);
}
-status_t Parcel::writeMap(const ::android::binder::Map& map_in)
-{
- using ::std::map;
- using ::android::binder::Value;
- using ::android::binder::Map;
-
- Map::const_iterator iter;
- status_t ret;
-
- ret = writeInt32(map_in.size());
-
- if (ret != NO_ERROR) {
- return ret;
- }
-
- for (iter = map_in.begin(); iter != map_in.end(); ++iter) {
- ret = writeValue(Value(iter->first));
- if (ret != NO_ERROR) {
- return ret;
- }
-
- ret = writeValue(iter->second);
- if (ret != NO_ERROR) {
- return ret;
- }
- }
-
- return ret;
-}
-
-status_t Parcel::writeNullableMap(const std::unique_ptr<binder::Map>& map)
-{
- if (map == nullptr) {
- return writeInt32(-1);
- }
-
- return writeMap(*map.get());
-}
-
-status_t Parcel::readMap(::android::binder::Map* map_out)const
-{
- using ::std::map;
- using ::android::String16;
- using ::android::String8;
- using ::android::binder::Value;
- using ::android::binder::Map;
-
- status_t ret = NO_ERROR;
- int32_t count;
-
- ret = readInt32(&count);
- if (ret != NO_ERROR) {
- return ret;
- }
-
- if (count < 0) {
- ALOGE("readMap: Unexpected count: %d", count);
- return (count == -1)
- ? UNEXPECTED_NULL
- : BAD_VALUE;
- }
-
- map_out->clear();
-
- while (count--) {
- Map::key_type key;
- Value value;
-
- ret = readValue(&value);
- if (ret != NO_ERROR) {
- return ret;
- }
-
- if (!value.getString(&key)) {
- ALOGE("readMap: Key type not a string (parcelType = %d)", value.parcelType());
- return BAD_VALUE;
- }
-
- ret = readValue(&value);
- if (ret != NO_ERROR) {
- return ret;
- }
-
- (*map_out)[key] = value;
- }
-
- return ret;
-}
-
-status_t Parcel::readNullableMap(std::unique_ptr<binder::Map>* map) const
-{
- const size_t start = dataPosition();
- int32_t count;
- status_t status = readInt32(&count);
- map->reset();
-
- if (status != OK || count == -1) {
- return status;
- }
-
- setDataPosition(start);
- map->reset(new binder::Map());
-
- status = readMap(map->get());
-
- if (status != OK) {
- map->reset();
- }
-
- return status;
-}
-
-
-
-void Parcel::remove(size_t /*start*/, size_t /*amt*/)
-{
- LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
-}
-
status_t Parcel::validateReadData(size_t upperBound) const
{
// Don't allow non-object reads on object data
@@ -2145,7 +1926,7 @@
status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
{
- return unflatten_binder(ProcessState::self(), *this, val);
+ return unflattenBinder(val);
}
sp<IBinder> Parcel::readStrongBinder() const
@@ -2158,13 +1939,6 @@
return val;
}
-wp<IBinder> Parcel::readWeakBinder() const
-{
- wp<IBinder> val;
- unflatten_binder(ProcessState::self(), *this, &val);
- return val;
-}
-
status_t Parcel::readParcelable(Parcelable* parcelable) const {
int32_t have_parcelable = 0;
status_t status = readInt32(&have_parcelable);
@@ -2177,10 +1951,6 @@
return parcelable->readFromParcel(this);
}
-status_t Parcel::readValue(binder::Value* value) const {
- return value->readFromParcel(this);
-}
-
int32_t Parcel::readExceptionCode() const
{
binder::Status status;
@@ -2523,7 +2293,7 @@
} else if (dataSize() > 0) {
const uint8_t* DATA = data();
to << indent << HexDump(DATA, dataSize()) << dedent;
- const binder_size_t* OBJS = objects();
+ const binder_size_t* OBJS = mObjects;
const size_t N = objectsCount();
for (size_t i=0; i<N; i++) {
const flat_binder_object* flat
@@ -2845,9 +2615,10 @@
mObjectsCapacity = 0;
mNextObjectHint = 0;
mObjectsSorted = false;
+ mAllowFds = true;
mHasFds = false;
mFdsKnown = true;
- mAllowFds = true;
+ mRequiredStability = internal::Stability::UNDECLARED;
mOwner = nullptr;
mOpenAshmemSize = 0;
diff --git a/libs/binder/include/private/binder/ParcelValTypes.h b/libs/binder/ParcelValTypes.h
similarity index 100%
rename from libs/binder/include/private/binder/ParcelValTypes.h
rename to libs/binder/ParcelValTypes.h
diff --git a/libs/binder/PersistableBundle.cpp b/libs/binder/PersistableBundle.cpp
index c0aec0a..97a6c94 100644
--- a/libs/binder/PersistableBundle.cpp
+++ b/libs/binder/PersistableBundle.cpp
@@ -17,7 +17,6 @@
#define LOG_TAG "PersistableBundle"
#include <binder/PersistableBundle.h>
-#include <private/binder/ParcelValTypes.h>
#include <limits>
@@ -26,6 +25,8 @@
#include <log/log.h>
#include <utils/Errors.h>
+#include "ParcelValTypes.h"
+
using android::BAD_TYPE;
using android::BAD_VALUE;
using android::NO_ERROR;
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index 2d156df..1e1bc3a 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -24,11 +24,10 @@
#include <cutils/atomic.h>
#include <utils/Log.h>
#include <utils/String8.h>
-#include <utils/String8.h>
#include <utils/threads.h>
#include <private/binder/binder_module.h>
-#include <private/binder/Static.h>
+#include "Static.h"
#include <errno.h>
#include <fcntl.h>
@@ -40,7 +39,7 @@
#include <sys/stat.h>
#include <sys/types.h>
-#define DEFAULT_BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
+#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
#define DEFAULT_MAX_BINDER_THREADS 15
#ifdef __ANDROID_VNDK__
@@ -77,13 +76,7 @@
if (gProcess != nullptr) {
return gProcess;
}
- gProcess = new ProcessState(kDefaultDriver, DEFAULT_BINDER_VM_SIZE);
- return gProcess;
-}
-
-sp<ProcessState> ProcessState::selfOrNull()
-{
- Mutex::Autolock _l(gProcessMutex);
+ gProcess = new ProcessState(kDefaultDriver);
return gProcess;
}
@@ -104,25 +97,14 @@
driver = "/dev/binder";
}
- gProcess = new ProcessState(driver, DEFAULT_BINDER_VM_SIZE);
+ gProcess = new ProcessState(driver);
return gProcess;
}
-sp<ProcessState> ProcessState::initWithMmapSize(size_t mmap_size) {
- Mutex::Autolock _l(gProcessMutex);
- if (gProcess != nullptr) {
- LOG_ALWAYS_FATAL_IF(mmap_size != gProcess->getMmapSize(),
- "ProcessState already initialized with a different mmap size.");
- return gProcess;
- }
-
- gProcess = new ProcessState(kDefaultDriver, mmap_size);
- return gProcess;
-}
-
-void ProcessState::setContextObject(const sp<IBinder>& object)
+sp<ProcessState> ProcessState::selfOrNull()
{
- setContextObject(object, String16("default"));
+ Mutex::Autolock _l(gProcessMutex);
+ return gProcess;
}
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
@@ -130,48 +112,6 @@
return getStrongProxyForHandle(0);
}
-void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
-{
- AutoMutex _l(mLock);
- mContexts.add(name, object);
-}
-
-sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
-{
- mLock.lock();
- sp<IBinder> object(
- mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : nullptr);
- mLock.unlock();
-
- //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
-
- if (object != nullptr) return object;
-
- // Don't attempt to retrieve contexts if we manage them
- if (mManagesContexts) {
- ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
- String8(name).string());
- return nullptr;
- }
-
- IPCThreadState* ipc = IPCThreadState::self();
- {
- Parcel data, reply;
- // no interface token on this magic transaction
- data.writeString16(name);
- data.writeStrongBinder(caller);
- status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
- if (result == NO_ERROR) {
- object = reply.readStrongBinder();
- }
- }
-
- ipc->flushCommands();
-
- if (object != nullptr) setContextObject(object, name);
- return object;
-}
-
void ProcessState::startThreadPool()
{
AutoMutex _l(mLock);
@@ -181,41 +121,33 @@
}
}
-bool ProcessState::isContextManager(void) const
-{
- return mManagesContexts;
-}
-
bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
{
- if (!mManagesContexts) {
- AutoMutex _l(mLock);
- mBinderContextCheckFunc = checkFunc;
- mBinderContextUserData = userData;
+ AutoMutex _l(mLock);
+ mBinderContextCheckFunc = checkFunc;
+ mBinderContextUserData = userData;
- flat_binder_object obj {
- .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
- };
+ flat_binder_object obj {
+ .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
+ };
- status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
+ int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
- // fallback to original method
- if (result != 0) {
- android_errorWriteLog(0x534e4554, "121035042");
+ // fallback to original method
+ if (result != 0) {
+ android_errorWriteLog(0x534e4554, "121035042");
- int dummy = 0;
- result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
- }
-
- if (result == 0) {
- mManagesContexts = true;
- } else if (result == -1) {
- mBinderContextCheckFunc = nullptr;
- mBinderContextUserData = nullptr;
- ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
- }
+ int dummy = 0;
+ result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
}
- return mManagesContexts;
+
+ if (result == -1) {
+ mBinderContextCheckFunc = nullptr;
+ mBinderContextUserData = nullptr;
+ ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
+ }
+
+ return result == 0;
}
// Get references to userspace objects held by the kernel binder driver
@@ -249,10 +181,6 @@
return count;
}
-size_t ProcessState::getMmapSize() {
- return mMmapSize;
-}
-
void ProcessState::setCallRestriction(CallRestriction restriction) {
LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull(), "Call restrictions must be set before the threadpool is started.");
@@ -282,8 +210,12 @@
if (e != nullptr) {
// We need to create a new BpBinder if there isn't currently one, OR we
- // are unable to acquire a weak reference on this current one. See comment
- // in getWeakProxyForHandle() for more info about this.
+ // are unable to acquire a weak reference on this current one. The
+ // attemptIncWeak() is safe because we know the BpBinder destructor will always
+ // call expungeHandle(), which acquires the same lock we are holding now.
+ // We need to do this because there is a race condition between someone
+ // releasing a reference on this BpBinder, and a new reference on its handle
+ // arriving from the driver.
IBinder* b = e->binder;
if (b == nullptr || !e->refs->attemptIncWeak(this)) {
if (handle == 0) {
@@ -329,37 +261,6 @@
return result;
}
-wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
-{
- wp<IBinder> result;
-
- AutoMutex _l(mLock);
-
- handle_entry* e = lookupHandleLocked(handle);
-
- if (e != nullptr) {
- // We need to create a new BpBinder if there isn't currently one, OR we
- // are unable to acquire a weak reference on this current one. The
- // attemptIncWeak() is safe because we know the BpBinder destructor will always
- // call expungeHandle(), which acquires the same lock we are holding now.
- // We need to do this because there is a race condition between someone
- // releasing a reference on this BpBinder, and a new reference on its handle
- // arriving from the driver.
- IBinder* b = e->binder;
- if (b == nullptr || !e->refs->attemptIncWeak(this)) {
- b = BpBinder::create(handle);
- result = b;
- e->binder = b;
- if (b) e->refs = b->getWeakRefs();
- } else {
- result = b;
- e->refs->decWeak(this);
- }
- }
-
- return result;
-}
-
void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
{
AutoMutex _l(mLock);
@@ -437,7 +338,7 @@
return fd;
}
-ProcessState::ProcessState(const char *driver, size_t mmap_size)
+ProcessState::ProcessState(const char *driver)
: mDriverName(String8(driver))
, mDriverFD(open_driver(driver))
, mVMStart(MAP_FAILED)
@@ -446,17 +347,15 @@
, mExecutingThreadsCount(0)
, mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
, mStarvationStartTimeMs(0)
- , mManagesContexts(false)
, mBinderContextCheckFunc(nullptr)
, mBinderContextUserData(nullptr)
, mThreadPoolStarted(false)
, mThreadPoolSeq(1)
- , mMmapSize(mmap_size)
, mCallRestriction(CallRestriction::NONE)
{
if (mDriverFD >= 0) {
// mmap the binder, providing a chunk of virtual address space to receive transactions.
- mVMStart = mmap(nullptr, mMmapSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
+ mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
if (mVMStart == MAP_FAILED) {
// *sigh*
ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());
@@ -466,14 +365,14 @@
}
}
- LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
+ LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver '%s' could not be opened. Terminating.", driver);
}
ProcessState::~ProcessState()
{
if (mDriverFD >= 0) {
if (mVMStart != MAP_FAILED) {
- munmap(mVMStart, mMmapSize);
+ munmap(mVMStart, BINDER_VM_SIZE);
}
close(mDriverFD);
}
diff --git a/libs/binder/Stability.cpp b/libs/binder/Stability.cpp
new file mode 100644
index 0000000..0a10a1d
--- /dev/null
+++ b/libs/binder/Stability.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2019 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 <binder/Stability.h>
+
+namespace android {
+namespace internal {
+
+void Stability::markCompilationUnit(IBinder* binder) {
+ status_t result = set(binder, kLocalStability, true /*log*/);
+ LOG_ALWAYS_FATAL_IF(result != OK, "Should only mark known object.");
+}
+
+void Stability::markVintf(IBinder* binder) {
+ status_t result = set(binder, Level::VINTF, true /*log*/);
+ LOG_ALWAYS_FATAL_IF(result != OK, "Should only mark known object.");
+}
+
+void Stability::debugLogStability(const std::string& tag, const sp<IBinder>& binder) {
+ ALOGE("%s: stability is %s", tag.c_str(), stabilityString(get(binder.get())).c_str());
+}
+
+void Stability::tryMarkCompilationUnit(IBinder* binder) {
+ (void) set(binder, kLocalStability, false /*log*/);
+}
+
+status_t Stability::set(IBinder* binder, int32_t stability, bool log) {
+ Level currentStability = get(binder);
+
+ // null binder is always written w/ 'UNDECLARED' stability
+ if (binder == nullptr) {
+ if (stability == UNDECLARED) {
+ return OK;
+ } else {
+ if (log) {
+ ALOGE("Null binder written with stability %s.",
+ stabilityString(stability).c_str());
+ }
+ return BAD_TYPE;
+ }
+ }
+
+ if (!isDeclaredStability(stability)) {
+ if (log) {
+ ALOGE("Can only set known stability, not %d.", stability);
+ }
+ return BAD_TYPE;
+ }
+
+ if (currentStability != Level::UNDECLARED && currentStability != stability) {
+ if (log) {
+ ALOGE("Interface being set with %s but it is already marked as %s.",
+ stabilityString(stability).c_str(), stabilityString(currentStability).c_str());
+ }
+ return BAD_TYPE;
+ }
+
+ if (currentStability == stability) return OK;
+
+ binder->attachObject(
+ reinterpret_cast<void*>(&Stability::get),
+ reinterpret_cast<void*>(stability),
+ nullptr /*cleanupCookie*/,
+ nullptr /*cleanup function*/);
+
+ return OK;
+}
+
+Stability::Level Stability::get(IBinder* binder) {
+ if (binder == nullptr) return UNDECLARED;
+
+ return static_cast<Level>(reinterpret_cast<intptr_t>(
+ binder->findObject(reinterpret_cast<void*>(&Stability::get))));
+}
+
+bool Stability::check(int32_t provided, Level required) {
+ bool stable = (provided & required) == required;
+
+ if (!isDeclaredStability(provided) && provided != UNDECLARED) {
+ ALOGE("Unknown stability when checking interface stability %d.", provided);
+
+ stable = false;
+ }
+
+ if (!stable) {
+ ALOGE("Interface with %s cannot accept interface with %s.",
+ stabilityString(required).c_str(),
+ stabilityString(provided).c_str());
+ }
+
+ return stable;
+}
+
+bool Stability::isDeclaredStability(int32_t stability) {
+ return stability == VENDOR || stability == SYSTEM || stability == VINTF;
+}
+
+std::string Stability::stabilityString(int32_t stability) {
+ switch (stability) {
+ case Level::UNDECLARED: return "undeclared stability";
+ case Level::VENDOR: return "vendor stability";
+ case Level::SYSTEM: return "system stability";
+ case Level::VINTF: return "vintf stability";
+ }
+ return "unknown stability " + std::to_string(stability);
+}
+
+} // namespace internal
+} // namespace stability
\ No newline at end of file
diff --git a/libs/binder/Static.cpp b/libs/binder/Static.cpp
index 8625c6f..a6fd8c4 100644
--- a/libs/binder/Static.cpp
+++ b/libs/binder/Static.cpp
@@ -17,7 +17,7 @@
// All static variables go here, to control initialization and
// destruction order in the library.
-#include <private/binder/Static.h>
+#include "Static.h"
#include <binder/BufferedTextOutput.h>
#include <binder/IPCThreadState.h>
diff --git a/libs/binder/include/private/binder/Static.h b/libs/binder/Static.h
similarity index 100%
rename from libs/binder/include/private/binder/Static.h
rename to libs/binder/Static.h
diff --git a/libs/binder/TEST_MAPPING b/libs/binder/TEST_MAPPING
new file mode 100644
index 0000000..01e57d3
--- /dev/null
+++ b/libs/binder/TEST_MAPPING
@@ -0,0 +1,16 @@
+{
+ "presubmit": [
+ {
+ "name": "binderSafeInterfaceTest"
+ },
+ {
+ "name": "binderDriverInterfaceTest"
+ },
+ {
+ "name": "binderTextOutputTest"
+ },
+ {
+ "name": "binderLibTest"
+ }
+ ]
+}
diff --git a/libs/binder/Value.cpp b/libs/binder/Value.cpp
deleted file mode 100644
index 19c57ba..0000000
--- a/libs/binder/Value.cpp
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
- * Copyright (C) 2015 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 "Value"
-
-#include <binder/Value.h>
-
-#include <limits>
-
-#include <binder/IBinder.h>
-#include <binder/Parcel.h>
-#include <binder/Map.h>
-#include <private/binder/ParcelValTypes.h>
-#include <log/log.h>
-#include <utils/Errors.h>
-
-using android::BAD_TYPE;
-using android::BAD_VALUE;
-using android::NO_ERROR;
-using android::UNEXPECTED_NULL;
-using android::Parcel;
-using android::sp;
-using android::status_t;
-using std::map;
-using std::set;
-using std::vector;
-using android::binder::Value;
-using android::IBinder;
-using android::os::PersistableBundle;
-using namespace android::binder;
-
-// ====================================================================
-
-#define RETURN_IF_FAILED(calledOnce) \
- do { \
- status_t returnStatus = calledOnce; \
- if (returnStatus) { \
- ALOGE("Failed at %s:%d (%s)", __FILE__, __LINE__, __func__); \
- return returnStatus; \
- } \
- } while(false)
-
-// ====================================================================
-
-/* These `internal_type_ptr()` functions allow this
- * class to work without C++ RTTI support. This technique
- * only works properly when called directly from this file,
- * but that is OK because that is the only place we will
- * be calling them from. */
-template<class T> const void* internal_type_ptr()
-{
- static const T *marker;
- return (void*)▮
-}
-
-/* Allows the type to be specified by the argument
- * instead of inside angle brackets. */
-template<class T> const void* internal_type_ptr(const T&)
-{
- return internal_type_ptr<T>();
-}
-
-// ====================================================================
-
-namespace android {
-
-namespace binder {
-
-class Value::ContentBase {
-public:
- virtual ~ContentBase() = default;
- virtual const void* type_ptr() const = 0;
- virtual ContentBase * clone() const = 0;
- virtual bool operator==(const ContentBase& rhs) const = 0;
-
-#ifdef LIBBINDER_VALUE_SUPPORTS_TYPE_INFO
- virtual const std::type_info &type() const = 0;
-#endif
-
- template<typename T> bool get(T* out) const;
-};
-
-/* This is the actual class that holds the value. */
-template<typename T> class Value::Content : public Value::ContentBase {
-public:
- Content() = default;
- explicit Content(const T & value) : mValue(value) { }
-
- virtual ~Content() = default;
-
-#ifdef LIBBINDER_VALUE_SUPPORTS_TYPE_INFO
- virtual const std::type_info &type() const override
- {
- return typeid(T);
- }
-#endif
-
- virtual const void* type_ptr() const override
- {
- return internal_type_ptr<T>();
- }
-
- virtual ContentBase * clone() const override
- {
- return new Content(mValue);
- };
-
- virtual bool operator==(const ContentBase& rhs) const override
- {
- if (type_ptr() != rhs.type_ptr()) {
- return false;
- }
- return mValue == static_cast<const Content<T>* >(&rhs)->mValue;
- }
-
- T mValue;
-};
-
-template<typename T> bool Value::ContentBase::get(T* out) const
-{
- if (internal_type_ptr(*out) != type_ptr())
- {
- return false;
- }
-
- *out = static_cast<const Content<T>*>(this)->mValue;
-
- return true;
-}
-
-// ====================================================================
-
-Value::Value() : mContent(nullptr)
-{
-}
-
-Value::Value(const Value& value)
- : mContent(value.mContent ? value.mContent->clone() : nullptr)
-{
-}
-
-Value::~Value()
-{
- delete mContent;
-}
-
-bool Value::operator==(const Value& rhs) const
-{
- const Value& lhs(*this);
-
- if (lhs.empty() && rhs.empty()) {
- return true;
- }
-
- if ( (lhs.mContent == nullptr)
- || (rhs.mContent == nullptr)
- ) {
- return false;
- }
-
- return *lhs.mContent == *rhs.mContent;
-}
-
-Value& Value::swap(Value &rhs)
-{
- std::swap(mContent, rhs.mContent);
- return *this;
-}
-
-Value& Value::operator=(const Value& rhs)
-{
- if (this != &rhs) {
- delete mContent;
- mContent = rhs.mContent
- ? rhs.mContent->clone()
- : nullptr;
- }
- return *this;
-}
-
-bool Value::empty() const
-{
- return mContent == nullptr;
-}
-
-void Value::clear()
-{
- delete mContent;
- mContent = nullptr;
-}
-
-int32_t Value::parcelType() const
-{
- const void* t_info(mContent ? mContent->type_ptr() : nullptr);
-
- if (t_info == internal_type_ptr<bool>()) return VAL_BOOLEAN;
- if (t_info == internal_type_ptr<uint8_t>()) return VAL_BYTE;
- if (t_info == internal_type_ptr<int32_t>()) return VAL_INTEGER;
- if (t_info == internal_type_ptr<int64_t>()) return VAL_LONG;
- if (t_info == internal_type_ptr<double>()) return VAL_DOUBLE;
- if (t_info == internal_type_ptr<String16>()) return VAL_STRING;
-
- if (t_info == internal_type_ptr<vector<bool>>()) return VAL_BOOLEANARRAY;
- if (t_info == internal_type_ptr<vector<uint8_t>>()) return VAL_BYTEARRAY;
- if (t_info == internal_type_ptr<vector<int32_t>>()) return VAL_INTARRAY;
- if (t_info == internal_type_ptr<vector<int64_t>>()) return VAL_LONGARRAY;
- if (t_info == internal_type_ptr<vector<double>>()) return VAL_DOUBLEARRAY;
- if (t_info == internal_type_ptr<vector<String16>>()) return VAL_STRINGARRAY;
-
- if (t_info == internal_type_ptr<Map>()) return VAL_MAP;
- if (t_info == internal_type_ptr<PersistableBundle>()) return VAL_PERSISTABLEBUNDLE;
-
- return VAL_NULL;
-}
-
-#ifdef LIBBINDER_VALUE_SUPPORTS_TYPE_INFO
-const std::type_info& Value::type() const
-{
- return mContent != nullptr
- ? mContent->type()
- : typeid(void);
-}
-#endif // ifdef LIBBINDER_VALUE_SUPPORTS_TYPE_INFO
-
-#define DEF_TYPE_ACCESSORS(T, TYPENAME) \
- bool Value::is ## TYPENAME() const \
- { \
- return mContent \
- ? internal_type_ptr<T>() == mContent->type_ptr() \
- : false; \
- } \
- bool Value::get ## TYPENAME(T* out) const \
- { \
- return mContent \
- ? mContent->get(out) \
- : false; \
- } \
- void Value::put ## TYPENAME(const T& in) \
- { \
- *this = in; \
- } \
- Value& Value::operator=(const T& rhs) \
- { \
- delete mContent; \
- mContent = new Content< T >(rhs); \
- return *this; \
- } \
- Value::Value(const T& value) \
- : mContent(new Content< T >(value)) \
- { }
-
-DEF_TYPE_ACCESSORS(bool, Boolean)
-DEF_TYPE_ACCESSORS(int8_t, Byte)
-DEF_TYPE_ACCESSORS(int32_t, Int)
-DEF_TYPE_ACCESSORS(int64_t, Long)
-DEF_TYPE_ACCESSORS(double, Double)
-DEF_TYPE_ACCESSORS(String16, String)
-
-DEF_TYPE_ACCESSORS(std::vector<bool>, BooleanVector)
-DEF_TYPE_ACCESSORS(std::vector<uint8_t>, ByteVector)
-DEF_TYPE_ACCESSORS(std::vector<int32_t>, IntVector)
-DEF_TYPE_ACCESSORS(std::vector<int64_t>, LongVector)
-DEF_TYPE_ACCESSORS(std::vector<double>, DoubleVector)
-DEF_TYPE_ACCESSORS(std::vector<String16>, StringVector)
-
-DEF_TYPE_ACCESSORS(::android::binder::Map, Map)
-DEF_TYPE_ACCESSORS(PersistableBundle, PersistableBundle)
-
-bool Value::getString(String8* out) const
-{
- String16 val;
- bool ret = getString(&val);
- if (ret) {
- *out = String8(val);
- }
- return ret;
-}
-
-bool Value::getString(::std::string* out) const
-{
- String8 val;
- bool ret = getString(&val);
- if (ret) {
- *out = val.string();
- }
- return ret;
-}
-
-status_t Value::writeToParcel(Parcel* parcel) const
-{
- // This implementation needs to be kept in sync with the writeValue
- // implementation in frameworks/base/core/java/android/os/Parcel.java
-
-#define BEGIN_HANDLE_WRITE() \
- do { \
- const void* t_info(mContent?mContent->type_ptr():nullptr); \
- if (false) { }
-#define HANDLE_WRITE_TYPE(T, TYPEVAL, TYPEMETHOD) \
- else if (t_info == internal_type_ptr<T>()) { \
- RETURN_IF_FAILED(parcel->writeInt32(TYPEVAL)); \
- RETURN_IF_FAILED(parcel->TYPEMETHOD(static_cast<const Content<T>*>(mContent)->mValue)); \
- }
-#define HANDLE_WRITE_PARCELABLE(T, TYPEVAL) \
- else if (t_info == internal_type_ptr<T>()) { \
- RETURN_IF_FAILED(parcel->writeInt32(TYPEVAL)); \
- RETURN_IF_FAILED(static_cast<const Content<T>*>(mContent)->mValue.writeToParcel(parcel)); \
- }
-#define END_HANDLE_WRITE() \
- else { \
- ALOGE("writeToParcel: Type not supported"); \
- return BAD_TYPE; \
- } \
- } while (false);
-
- BEGIN_HANDLE_WRITE()
-
- HANDLE_WRITE_TYPE(bool, VAL_BOOLEAN, writeBool)
- HANDLE_WRITE_TYPE(int8_t, VAL_BYTE, writeByte)
- HANDLE_WRITE_TYPE(int8_t, VAL_BYTE, writeByte)
- HANDLE_WRITE_TYPE(int32_t, VAL_INTEGER, writeInt32)
- HANDLE_WRITE_TYPE(int64_t, VAL_LONG, writeInt64)
- HANDLE_WRITE_TYPE(double, VAL_DOUBLE, writeDouble)
- HANDLE_WRITE_TYPE(String16, VAL_STRING, writeString16)
-
- HANDLE_WRITE_TYPE(vector<bool>, VAL_BOOLEANARRAY, writeBoolVector)
- HANDLE_WRITE_TYPE(vector<uint8_t>, VAL_BYTEARRAY, writeByteVector)
- HANDLE_WRITE_TYPE(vector<int8_t>, VAL_BYTEARRAY, writeByteVector)
- HANDLE_WRITE_TYPE(vector<int32_t>, VAL_INTARRAY, writeInt32Vector)
- HANDLE_WRITE_TYPE(vector<int64_t>, VAL_LONGARRAY, writeInt64Vector)
- HANDLE_WRITE_TYPE(vector<double>, VAL_DOUBLEARRAY, writeDoubleVector)
- HANDLE_WRITE_TYPE(vector<String16>, VAL_STRINGARRAY, writeString16Vector)
-
- HANDLE_WRITE_PARCELABLE(PersistableBundle, VAL_PERSISTABLEBUNDLE)
-
- END_HANDLE_WRITE()
-
- return NO_ERROR;
-
-#undef BEGIN_HANDLE_WRITE
-#undef HANDLE_WRITE_TYPE
-#undef HANDLE_WRITE_PARCELABLE
-#undef END_HANDLE_WRITE
-}
-
-status_t Value::readFromParcel(const Parcel* parcel)
-{
- // This implementation needs to be kept in sync with the readValue
- // implementation in frameworks/base/core/java/android/os/Parcel.javai
-
-#define BEGIN_HANDLE_READ() \
- switch(value_type) { \
- default: \
- ALOGE("readFromParcel: Parcel type %d is not supported", value_type); \
- return BAD_TYPE;
-#define HANDLE_READ_TYPE(T, TYPEVAL, TYPEMETHOD) \
- case TYPEVAL: \
- mContent = new Content<T>(); \
- RETURN_IF_FAILED(parcel->TYPEMETHOD(&static_cast<Content<T>*>(mContent)->mValue)); \
- break;
-#define HANDLE_READ_PARCELABLE(T, TYPEVAL) \
- case TYPEVAL: \
- mContent = new Content<T>(); \
- RETURN_IF_FAILED(static_cast<Content<T>*>(mContent)->mValue.readFromParcel(parcel)); \
- break;
-#define END_HANDLE_READ() \
- }
-
- int32_t value_type = VAL_NULL;
-
- delete mContent;
- mContent = nullptr;
-
- RETURN_IF_FAILED(parcel->readInt32(&value_type));
-
- BEGIN_HANDLE_READ()
-
- HANDLE_READ_TYPE(bool, VAL_BOOLEAN, readBool)
- HANDLE_READ_TYPE(int8_t, VAL_BYTE, readByte)
- HANDLE_READ_TYPE(int32_t, VAL_INTEGER, readInt32)
- HANDLE_READ_TYPE(int64_t, VAL_LONG, readInt64)
- HANDLE_READ_TYPE(double, VAL_DOUBLE, readDouble)
- HANDLE_READ_TYPE(String16, VAL_STRING, readString16)
-
- HANDLE_READ_TYPE(vector<bool>, VAL_BOOLEANARRAY, readBoolVector)
- HANDLE_READ_TYPE(vector<uint8_t>, VAL_BYTEARRAY, readByteVector)
- HANDLE_READ_TYPE(vector<int32_t>, VAL_INTARRAY, readInt32Vector)
- HANDLE_READ_TYPE(vector<int64_t>, VAL_LONGARRAY, readInt64Vector)
- HANDLE_READ_TYPE(vector<double>, VAL_DOUBLEARRAY, readDoubleVector)
- HANDLE_READ_TYPE(vector<String16>, VAL_STRINGARRAY, readString16Vector)
-
- HANDLE_READ_PARCELABLE(PersistableBundle, VAL_PERSISTABLEBUNDLE)
-
- END_HANDLE_READ()
-
- return NO_ERROR;
-
-#undef BEGIN_HANDLE_READ
-#undef HANDLE_READ_TYPE
-#undef HANDLE_READ_PARCELABLE
-#undef END_HANDLE_READ
-}
-
-} // namespace binder
-
-} // namespace android
-
-/* vim: set ts=4 sw=4 tw=0 et :*/
diff --git a/libs/binder/aidl/android/content/pm/OWNERS b/libs/binder/aidl/android/content/pm/OWNERS
new file mode 100644
index 0000000..a967a7f
--- /dev/null
+++ b/libs/binder/aidl/android/content/pm/OWNERS
@@ -0,0 +1,4 @@
+narayan@google.com
+patb@google.com
+svetoslavganov@google.com
+toddke@google.com
diff --git a/libs/binder/include/binder/Binder.h b/libs/binder/include/binder/Binder.h
index cf3ef84..1537e69 100644
--- a/libs/binder/include/binder/Binder.h
+++ b/libs/binder/include/binder/Binder.h
@@ -54,9 +54,9 @@
virtual void attachObject( const void* objectID,
void* object,
void* cleanupCookie,
- object_cleanup_func func);
- virtual void* findObject(const void* objectID) const;
- virtual void detachObject(const void* objectID);
+ object_cleanup_func func) final;
+ virtual void* findObject(const void* objectID) const final;
+ virtual void detachObject(const void* objectID) final;
virtual BBinder* localBinder();
diff --git a/libs/binder/include/binder/BpBinder.h b/libs/binder/include/binder/BpBinder.h
index 78f2e1d..e71541b 100644
--- a/libs/binder/include/binder/BpBinder.h
+++ b/libs/binder/include/binder/BpBinder.h
@@ -34,7 +34,7 @@
public:
static BpBinder* create(int32_t handle);
- inline int32_t handle() const { return mHandle; }
+ int32_t handle() const;
virtual const String16& getInterfaceDescriptor() const;
virtual bool isBinderAlive() const;
@@ -61,9 +61,9 @@
virtual void attachObject( const void* objectID,
void* object,
void* cleanupCookie,
- object_cleanup_func func);
- virtual void* findObject(const void* objectID) const;
- virtual void detachObject(const void* objectID);
+ object_cleanup_func func) final;
+ virtual void* findObject(const void* objectID) const final;
+ virtual void detachObject(const void* objectID) final;
virtual BpBinder* remoteBinder();
diff --git a/libs/binder/include/binder/Map.h b/libs/binder/include/binder/Map.h
deleted file mode 100644
index 96a4f8a..0000000
--- a/libs/binder/include/binder/Map.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2005 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 ANDROID_MAP_H
-#define ANDROID_MAP_H
-
-#include <map>
-#include <string>
-
-// ---------------------------------------------------------------------------
-namespace android {
-namespace binder {
-
-class Value;
-
-/**
- * Convenience typedef for ::std::map<::std::string,::android::binder::Value>
- */
-typedef ::std::map<::std::string, Value> Map;
-
-} // namespace binder
-} // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_MAP_H
diff --git a/libs/binder/include/binder/Parcel.h b/libs/binder/include/binder/Parcel.h
index f6560a7..a0a91d7 100644
--- a/libs/binder/include/binder/Parcel.h
+++ b/libs/binder/include/binder/Parcel.h
@@ -17,6 +17,7 @@
#ifndef ANDROID_PARCEL_H
#define ANDROID_PARCEL_H
+#include <map> // for legacy reasons
#include <string>
#include <vector>
@@ -32,7 +33,7 @@
#include <binder/IInterface.h>
#include <binder/Parcelable.h>
-#include <binder/Map.h>
+#include <binder/Stability.h>
// ---------------------------------------------------------------------------
namespace android {
@@ -67,7 +68,9 @@
status_t setDataSize(size_t size);
void setDataPosition(size_t pos) const;
status_t setDataCapacity(size_t size);
-
+
+ void setTransactingBinder(const sp<IBinder>& binder) const;
+
status_t setData(const uint8_t* buffer, size_t len);
status_t appendFrom(const Parcel *parcel,
@@ -97,10 +100,6 @@
void freeData();
-private:
- const binder_size_t* objects() const;
-
-public:
size_t objectsCount() const;
status_t errorCheck() const;
@@ -121,7 +120,6 @@
status_t writeString16(const std::unique_ptr<String16>& str);
status_t writeString16(const char16_t* str, size_t len);
status_t writeStrongBinder(const sp<IBinder>& val);
- status_t writeWeakBinder(const wp<IBinder>& val);
status_t writeInt32Array(size_t len, const int32_t *val);
status_t writeByteArray(size_t len, const uint8_t *val);
status_t writeBool(bool val);
@@ -170,8 +168,6 @@
status_t writeParcelable(const Parcelable& parcelable);
- status_t writeValue(const binder::Value& value);
-
template<typename T>
status_t write(const Flattenable<T>& val);
@@ -183,9 +179,6 @@
template<typename T>
status_t writeVectorSize(const std::unique_ptr<std::vector<T>>& val);
- status_t writeMap(const binder::Map& map);
- status_t writeNullableMap(const std::unique_ptr<binder::Map>& map);
-
// Place a native_handle into the parcel (the native_handle's file-
// descriptors are dup'ed, so it is safe to delete the native_handle
// when this function returns).
@@ -242,8 +235,6 @@
// Currently the native implementation doesn't do any of the StrictMode
// stack gathering and serialization that the Java implementation does.
status_t writeNoException();
-
- void remove(size_t start, size_t amt);
status_t read(void* outData, size_t len) const;
const void* readInplace(size_t len) const;
@@ -282,7 +273,6 @@
sp<IBinder> readStrongBinder() const;
status_t readStrongBinder(sp<IBinder>* val) const;
status_t readNullableStrongBinder(sp<IBinder>* val) const;
- wp<IBinder> readWeakBinder() const;
template<typename T>
status_t readParcelableVector(
@@ -295,8 +285,6 @@
template<typename T>
status_t readParcelable(std::unique_ptr<T>* parcelable) const;
- status_t readValue(binder::Value* value) const;
-
template<typename T>
status_t readStrongBinder(sp<T>* val) const;
@@ -340,9 +328,6 @@
template<typename T>
status_t resizeOutVector(std::unique_ptr<std::vector<T>>* val) const;
- status_t readMap(binder::Map* map)const;
- status_t readNullableMap(std::unique_ptr<binder::Map>* map) const;
-
// Like Parcel.java's readExceptionCode(). Reads the first int32
// off of a Parcel's header, returning 0 or the negative error
// code on exceptions, but also deals with skipping over rich
@@ -426,7 +411,13 @@
void initState();
void scanForFds() const;
status_t validateReadData(size_t len) const;
-
+
+ status_t finishFlattenBinder(const sp<IBinder>& binder,
+ const flat_binder_object& flat);
+ status_t finishUnflattenBinder(const sp<IBinder>& binder, sp<IBinder>* out) const;
+ status_t flattenBinder(const sp<IBinder>& binder);
+ status_t unflattenBinder(sp<IBinder>* out) const;
+
template<class T>
status_t readAligned(T *pArg) const;
@@ -473,10 +464,12 @@
size_t mObjectsCapacity;
mutable size_t mNextObjectHint;
mutable bool mObjectsSorted;
+ bool mAllowFds;
mutable bool mFdsKnown;
mutable bool mHasFds;
- bool mAllowFds;
+
+ mutable internal::Stability::Level mRequiredStability;
release_func mOwner;
void* mOwnerCookie;
@@ -918,23 +911,6 @@
return to;
}
-// ---------------------------------------------------------------------------
-
-// Generic acquire and release of objects.
-void acquire_object(const sp<ProcessState>& proc,
- const flat_binder_object& obj, const void* who);
-void release_object(const sp<ProcessState>& proc,
- const flat_binder_object& obj, const void* who);
-
-void flatten_binder(const sp<ProcessState>& proc,
- const sp<IBinder>& binder, flat_binder_object* out);
-void flatten_binder(const sp<ProcessState>& proc,
- const wp<IBinder>& binder, flat_binder_object* out);
-status_t unflatten_binder(const sp<ProcessState>& proc,
- const flat_binder_object& flat, sp<IBinder>* out);
-status_t unflatten_binder(const sp<ProcessState>& proc,
- const flat_binder_object& flat, wp<IBinder>* out);
-
}; // namespace android
// ---------------------------------------------------------------------------
diff --git a/libs/binder/include/binder/ProcessState.h b/libs/binder/include/binder/ProcessState.h
index 1622ba2..8339976 100644
--- a/libs/binder/include/binder/ProcessState.h
+++ b/libs/binder/include/binder/ProcessState.h
@@ -36,8 +36,6 @@
public:
static sp<ProcessState> self();
static sp<ProcessState> selfOrNull();
- // Note: don't call self() or selfOrNull() before initWithMmapSize()
- static sp<ProcessState> initWithMmapSize(size_t mmapSize); // size in bytes
/* initWithDriver() can be used to configure libbinder to use
* a different binder driver dev node. It must be called *before*
@@ -47,27 +45,19 @@
*/
static sp<ProcessState> initWithDriver(const char *driver);
- void setContextObject(const sp<IBinder>& object);
sp<IBinder> getContextObject(const sp<IBinder>& caller);
-
- void setContextObject(const sp<IBinder>& object,
- const String16& name);
- sp<IBinder> getContextObject(const String16& name,
- const sp<IBinder>& caller);
void startThreadPool();
typedef bool (*context_check_func)(const String16& name,
const sp<IBinder>& caller,
void* userData);
-
- bool isContextManager(void) const;
+
bool becomeContextManager(
context_check_func checkFunc,
void* userData);
sp<IBinder> getStrongProxyForHandle(int32_t handle);
- wp<IBinder> getWeakProxyForHandle(int32_t handle);
void expungeHandle(int32_t handle, IBinder* binder);
void spawnPooledThread(bool isMain);
@@ -78,7 +68,6 @@
String8 getDriverName();
ssize_t getKernelReferences(size_t count, uintptr_t* buf);
- size_t getMmapSize();
enum class CallRestriction {
// all calls okay
@@ -95,7 +84,7 @@
private:
friend class IPCThreadState;
- explicit ProcessState(const char* driver, size_t mmap_size);
+ explicit ProcessState(const char* driver);
~ProcessState();
ProcessState(const ProcessState& o);
@@ -124,23 +113,15 @@
int64_t mStarvationStartTimeMs;
mutable Mutex mLock; // protects everything below.
- // TODO: mManagesContexts is often accessed without the lock.
- // Explain why that's safe.
Vector<handle_entry>mHandleToObject;
- bool mManagesContexts;
context_check_func mBinderContextCheckFunc;
void* mBinderContextUserData;
- KeyedVector<String16, sp<IBinder> >
- mContexts;
-
-
String8 mRootDir;
bool mThreadPoolStarted;
volatile int32_t mThreadPoolSeq;
- const size_t mMmapSize;
CallRestriction mCallRestriction;
};
diff --git a/libs/binder/include/binder/Stability.h b/libs/binder/include/binder/Stability.h
new file mode 100644
index 0000000..9d98c7f
--- /dev/null
+++ b/libs/binder/include/binder/Stability.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#pragma once
+
+#include <binder/IBinder.h>
+#include <string>
+
+namespace android {
+namespace internal {
+
+// WARNING: These APIs are only ever expected to be called by auto-generated code.
+// Instead of calling them, you should set the stability of a .aidl interface
+class Stability final {
+public:
+ // WARNING: This is only ever expected to be called by auto-generated code. You likely want to
+ // change or modify the stability class of the interface you are using.
+ // This must be called as soon as the binder in question is constructed. No thread safety
+ // is provided.
+ // E.g. stability is according to libbinder compilation unit
+ static void markCompilationUnit(IBinder* binder);
+ // WARNING: This is only ever expected to be called by auto-generated code. You likely want to
+ // change or modify the stability class of the interface you are using.
+ // This must be called as soon as the binder in question is constructed. No thread safety
+ // is provided.
+ // E.g. stability is according to libbinder_ndk or Java SDK AND the interface
+ // expressed here is guaranteed to be stable for multiple years (Stable AIDL)
+ static void markVintf(IBinder* binder);
+
+ // WARNING: for debugging only
+ static void debugLogStability(const std::string& tag, const sp<IBinder>& binder);
+
+private:
+ // Parcel needs to store stability level since this is more efficient than storing and looking
+ // up the efficiency level of a binder object. So, we expose the underlying type.
+ friend ::android::Parcel;
+
+ static void tryMarkCompilationUnit(IBinder* binder);
+
+ enum Level : int16_t {
+ UNDECLARED = 0,
+
+ VENDOR = 0b000011,
+ SYSTEM = 0b001100,
+ VINTF = 0b111111,
+ };
+
+#ifdef __ANDROID_VNDK__
+ static constexpr Level kLocalStability = Level::VENDOR;
+#else
+ static constexpr Level kLocalStability = Level::SYSTEM;
+#endif
+
+ // applies stability to binder if stability level is known
+ __attribute__((warn_unused_result))
+ static status_t set(IBinder* binder, int32_t stability, bool log);
+
+ static Level get(IBinder* binder);
+
+ static bool check(int32_t provided, Level required);
+
+ static bool isDeclaredStability(int32_t stability);
+ static std::string stabilityString(int32_t stability);
+
+ Stability();
+};
+
+} // namespace internal
+} // namespace android
diff --git a/libs/binder/include/binder/Value.h b/libs/binder/include/binder/Value.h
deleted file mode 100644
index 735f40e..0000000
--- a/libs/binder/include/binder/Value.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2015 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 ANDROID_VALUE_H
-#define ANDROID_VALUE_H
-
-#include <stdint.h>
-#include <map>
-#include <set>
-#include <vector>
-#include <string>
-
-#include <binder/Parcelable.h>
-#include <binder/PersistableBundle.h>
-#include <binder/Map.h>
-#include <utils/String8.h>
-#include <utils/String16.h>
-#include <utils/StrongPointer.h>
-
-namespace android {
-
-class Parcel;
-
-namespace binder {
-
-/**
- * A limited C++ generic type. The purpose of this class is to allow C++
- * programs to make use of (or implement) Binder interfaces which make use
- * the Java "Object" generic type (either via the use of the Map type or
- * some other mechanism).
- *
- * This class only supports a limited set of types, but additional types
- * may be easily added to this class in the future as needed---without
- * breaking binary compatability.
- *
- * This class was written in such a way as to help avoid type errors by
- * giving each type their own explicity-named accessor methods (rather than
- * overloaded methods).
- *
- * When reading or writing this class to a Parcel, use the `writeValue()`
- * and `readValue()` methods.
- */
-class Value {
-public:
- Value();
- virtual ~Value();
-
- Value& swap(Value &);
-
- bool empty() const;
-
- void clear();
-
-#ifdef LIBBINDER_VALUE_SUPPORTS_TYPE_INFO
- const std::type_info& type() const;
-#endif
-
- int32_t parcelType() const;
-
- bool operator==(const Value& rhs) const;
- bool operator!=(const Value& rhs) const { return !this->operator==(rhs); }
-
- Value(const Value& value);
- Value(const bool& value); // NOLINT(google-explicit-constructor)
- Value(const int8_t& value); // NOLINT(google-explicit-constructor)
- Value(const int32_t& value); // NOLINT(google-explicit-constructor)
- Value(const int64_t& value); // NOLINT(google-explicit-constructor)
- Value(const double& value); // NOLINT(google-explicit-constructor)
- Value(const String16& value); // NOLINT(google-explicit-constructor)
- Value(const std::vector<bool>& value); // NOLINT(google-explicit-constructor)
- Value(const std::vector<uint8_t>& value); // NOLINT(google-explicit-constructor)
- Value(const std::vector<int32_t>& value); // NOLINT(google-explicit-constructor)
- Value(const std::vector<int64_t>& value); // NOLINT(google-explicit-constructor)
- Value(const std::vector<double>& value); // NOLINT(google-explicit-constructor)
- Value(const std::vector<String16>& value); // NOLINT(google-explicit-constructor)
- Value(const os::PersistableBundle& value); // NOLINT(google-explicit-constructor)
- Value(const binder::Map& value); // NOLINT(google-explicit-constructor)
-
- Value& operator=(const Value& rhs);
- Value& operator=(const int8_t& rhs);
- Value& operator=(const bool& rhs);
- Value& operator=(const int32_t& rhs);
- Value& operator=(const int64_t& rhs);
- Value& operator=(const double& rhs);
- Value& operator=(const String16& rhs);
- Value& operator=(const std::vector<bool>& rhs);
- Value& operator=(const std::vector<uint8_t>& rhs);
- Value& operator=(const std::vector<int32_t>& rhs);
- Value& operator=(const std::vector<int64_t>& rhs);
- Value& operator=(const std::vector<double>& rhs);
- Value& operator=(const std::vector<String16>& rhs);
- Value& operator=(const os::PersistableBundle& rhs);
- Value& operator=(const binder::Map& rhs);
-
- void putBoolean(const bool& value);
- void putByte(const int8_t& value);
- void putInt(const int32_t& value);
- void putLong(const int64_t& value);
- void putDouble(const double& value);
- void putString(const String16& value);
- void putBooleanVector(const std::vector<bool>& value);
- void putByteVector(const std::vector<uint8_t>& value);
- void putIntVector(const std::vector<int32_t>& value);
- void putLongVector(const std::vector<int64_t>& value);
- void putDoubleVector(const std::vector<double>& value);
- void putStringVector(const std::vector<String16>& value);
- void putPersistableBundle(const os::PersistableBundle& value);
- void putMap(const binder::Map& value);
-
- bool getBoolean(bool* out) const;
- bool getByte(int8_t* out) const;
- bool getInt(int32_t* out) const;
- bool getLong(int64_t* out) const;
- bool getDouble(double* out) const;
- bool getString(String16* out) const;
- bool getBooleanVector(std::vector<bool>* out) const;
- bool getByteVector(std::vector<uint8_t>* out) const;
- bool getIntVector(std::vector<int32_t>* out) const;
- bool getLongVector(std::vector<int64_t>* out) const;
- bool getDoubleVector(std::vector<double>* out) const;
- bool getStringVector(std::vector<String16>* out) const;
- bool getPersistableBundle(os::PersistableBundle* out) const;
- bool getMap(binder::Map* out) const;
-
- bool isBoolean() const;
- bool isByte() const;
- bool isInt() const;
- bool isLong() const;
- bool isDouble() const;
- bool isString() const;
- bool isBooleanVector() const;
- bool isByteVector() const;
- bool isIntVector() const;
- bool isLongVector() const;
- bool isDoubleVector() const;
- bool isStringVector() const;
- bool isPersistableBundle() const;
- bool isMap() const;
-
- // String Convenience Adapters
- // ---------------------------
-
- explicit Value(const String8& value): Value(String16(value)) { }
- explicit Value(const ::std::string& value): Value(String8(value.c_str())) { }
- void putString(const String8& value) { return putString(String16(value)); }
- void putString(const ::std::string& value) { return putString(String8(value.c_str())); }
- Value& operator=(const String8& rhs) { return *this = String16(rhs); }
- Value& operator=(const ::std::string& rhs) { return *this = String8(rhs.c_str()); }
- bool getString(String8* out) const;
- bool getString(::std::string* out) const;
-
-private:
-
- // This allows ::android::Parcel to call the two methods below.
- friend class ::android::Parcel;
-
- // This is called by ::android::Parcel::writeValue()
- status_t writeToParcel(Parcel* parcel) const;
-
- // This is called by ::android::Parcel::readValue()
- status_t readFromParcel(const Parcel* parcel);
-
- template<typename T> class Content;
- class ContentBase;
-
- ContentBase* mContent;
-};
-
-} // namespace binder
-
-} // namespace android
-
-#endif // ANDROID_VALUE_H
diff --git a/libs/binder/ndk/Android.bp b/libs/binder/ndk/Android.bp
index 21bef2e..6da3086 100644
--- a/libs/binder/ndk/Android.bp
+++ b/libs/binder/ndk/Android.bp
@@ -16,7 +16,6 @@
cc_library {
name: "libbinder_ndk",
- vendor_available: true,
export_include_dirs: [
"include_ndk",
@@ -74,3 +73,12 @@
symbol_file: "libbinder_ndk.map.txt",
first_version: "29",
}
+
+llndk_library {
+ name: "libbinder_ndk",
+ symbol_file: "libbinder_ndk.map.txt",
+ export_include_dirs: [
+ "include_ndk",
+ "include_apex",
+ ],
+}
diff --git a/libs/binder/ndk/include_apex/android/binder_process.h b/libs/binder/ndk/include_apex/android/binder_process.h
index 69e6387..fdefbb4 100644
--- a/libs/binder/ndk/include_apex/android/binder_process.h
+++ b/libs/binder/ndk/include_apex/android/binder_process.h
@@ -27,7 +27,7 @@
void ABinderProcess_startThreadPool();
/**
* This sets the maximum number of threads that can be started in the threadpool. By default, after
- * startThreadPool is called, this is one. If it is called additional times, it will only prevent
+ * startThreadPool is called, this is 15. If it is called additional times, it will only prevent
* the kernel from starting new threads and will not delete already existing threads.
*/
bool ABinderProcess_setThreadPoolMaxThreadCount(uint32_t numThreads);
diff --git a/libs/binder/ndk/libbinder_ndk.map.txt b/libs/binder/ndk/libbinder_ndk.map.txt
index 7e65817..4f685d1 100644
--- a/libs/binder/ndk/libbinder_ndk.map.txt
+++ b/libs/binder/ndk/libbinder_ndk.map.txt
@@ -89,12 +89,12 @@
AStatus_getStatus;
AStatus_isOk;
AStatus_newOk;
- ABinderProcess_joinThreadPool; # apex
- ABinderProcess_setThreadPoolMaxThreadCount; # apex
- ABinderProcess_startThreadPool; # apex
- AServiceManager_addService; # apex
- AServiceManager_checkService; # apex
- AServiceManager_getService; # apex
+ ABinderProcess_joinThreadPool; # apex vndk
+ ABinderProcess_setThreadPoolMaxThreadCount; # apex vndk
+ ABinderProcess_startThreadPool; # apex vndk
+ AServiceManager_addService; # apex vndk
+ AServiceManager_checkService; # apex vndk
+ AServiceManager_getService; # apex vndk
local:
*;
};
diff --git a/libs/binder/ndk/scripts/init_map.sh b/libs/binder/ndk/scripts/init_map.sh
deleted file mode 100755
index 3529b72..0000000
--- a/libs/binder/ndk/scripts/init_map.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env bash
-
-# Simple helper for ease of development until this API is frozen.
-
-echo "LIBBINDER_NDK { # introduced=29"
-echo " global:"
-{
- grep -oP "AIBinder_[a-zA-Z0-9_]+(?=\()" include_ndk/android/binder_ibinder.h;
- grep -oP "AIBinder_[a-zA-Z0-9_]+(?=\()" include_ndk/android/binder_ibinder_jni.h;
- grep -oP "AParcel_[a-zA-Z0-9_]+(?=\()" include_ndk/android/binder_parcel.h;
- grep -oP "AStatus_[a-zA-Z0-9_]+(?=\()" include_ndk/android/binder_status.h;
-} | sort | uniq | awk '{ print " " $0 ";"; }'
-{
- grep -oP "AServiceManager_[a-zA-Z0-9_]+(?=\()" include_apex/android/binder_manager.h;
- grep -oP "ABinderProcess_[a-zA-Z0-9_]+(?=\()" include_apex/android/binder_process.h;
-} | sort | uniq | awk '{ print " " $0 "; # apex"; }'
-echo " local:"
-echo " *;"
-echo "};"
diff --git a/libs/binder/ndk/update.sh b/libs/binder/ndk/update.sh
index 9a4577f..1eba892 100755
--- a/libs/binder/ndk/update.sh
+++ b/libs/binder/ndk/update.sh
@@ -20,4 +20,3 @@
# This script makes sure that the source code is in sync with the various scripts
./scripts/gen_parcel_helper.py
./scripts/format.sh
-./scripts/init_map.sh > libbinder_ndk.map.txt
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index c451780..05db81e 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -19,45 +19,34 @@
cflags: [
"-Wall",
"-Werror",
- "-Wno-unused-private-field",
- "-Wno-unused-variable",
],
}
cc_test {
name: "binderDriverInterfaceTest_IPC_32",
- srcs: ["binderDriverInterfaceTest.cpp"],
defaults: ["binder_test_defaults"],
+ srcs: ["binderDriverInterfaceTest.cpp"],
compile_multilib: "32",
cflags: ["-DBINDER_IPC_32BIT=1"],
}
cc_test {
+ name: "binderDriverInterfaceTest",
+ defaults: ["binder_test_defaults"],
product_variables: {
binder32bit: {
cflags: ["-DBINDER_IPC_32BIT=1"],
},
},
- name: "binderDriverInterfaceTest",
srcs: ["binderDriverInterfaceTest.cpp"],
- defaults: ["binder_test_defaults"],
-}
-
-cc_test {
- name: "binderValueTypeTest",
- srcs: ["binderValueTypeTest.cpp"],
- defaults: ["binder_test_defaults"],
- shared_libs: [
- "libbinder",
- "libutils",
- ],
+ test_suites: ["device-tests"],
}
cc_test {
name: "binderLibTest_IPC_32",
- srcs: ["binderLibTest.cpp"],
defaults: ["binder_test_defaults"],
+ srcs: ["binderLibTest.cpp"],
shared_libs: [
"libbinder",
"libutils",
@@ -67,25 +56,26 @@
}
cc_test {
+ name: "binderLibTest",
+ defaults: ["binder_test_defaults"],
product_variables: {
binder32bit: {
cflags: ["-DBINDER_IPC_32BIT=1"],
},
},
- defaults: ["binder_test_defaults"],
- name: "binderLibTest",
srcs: ["binderLibTest.cpp"],
shared_libs: [
"libbinder",
"libutils",
],
+ test_suites: ["device-tests"],
}
cc_test {
name: "binderThroughputTest",
- srcs: ["binderThroughputTest.cpp"],
defaults: ["binder_test_defaults"],
+ srcs: ["binderThroughputTest.cpp"],
shared_libs: [
"libbinder",
"libutils",
@@ -101,19 +91,20 @@
cc_test {
name: "binderTextOutputTest",
- srcs: ["binderTextOutputTest.cpp"],
defaults: ["binder_test_defaults"],
+ srcs: ["binderTextOutputTest.cpp"],
shared_libs: [
"libbinder",
"libutils",
"libbase",
],
+ test_suites: ["device-tests"],
}
cc_test {
name: "schd-dbg",
- srcs: ["schd-dbg.cpp"],
defaults: ["binder_test_defaults"],
+ srcs: ["schd-dbg.cpp"],
shared_libs: [
"libbinder",
"libutils",
@@ -123,8 +114,8 @@
cc_test {
name: "binderSafeInterfaceTest",
- srcs: ["binderSafeInterfaceTest.cpp"],
defaults: ["binder_test_defaults"],
+ srcs: ["binderSafeInterfaceTest.cpp"],
cppflags: [
"-Weverything",
@@ -144,4 +135,20 @@
"liblog",
"libutils",
],
+ test_suites: ["device-tests"],
+}
+
+cc_test {
+ name: "binderStabilityTest",
+ defaults: ["binder_test_defaults"],
+ srcs: [
+ "binderStabilityTest.cpp",
+ "IBinderStabilityTest.aidl",
+ ],
+
+ shared_libs: [
+ "libbinder",
+ "libutils",
+ ],
+ test_suites: ["device-tests"],
}
diff --git a/libs/binder/tests/IBinderStabilityTest.aidl b/libs/binder/tests/IBinderStabilityTest.aidl
new file mode 100644
index 0000000..7540ec9
--- /dev/null
+++ b/libs/binder/tests/IBinderStabilityTest.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+// DO NOT EVER IN A MILLION YEARS WRITE AN INTERFACE LIKE THIS!
+// THIS IS ONLY FOR TESTING!
+interface IBinderStabilityTest {
+ // DO NOT EVER IN A MILLION YEARS WRITE AN INTERFACE LIKE THIS!
+ // THIS IS ONLY FOR TESTING!
+ void sendBinder(IBinder binder);
+
+ // DO NOT EVER IN A MILLION YEARS WRITE AN INTERFACE LIKE THIS!
+ // THIS IS ONLY FOR TESTING!
+ IBinder returnNoStabilityBinder();
+
+ // DO NOT EVER IN A MILLION YEARS WRITE AN INTERFACE LIKE THIS!
+ // THIS IS ONLY FOR TESTING!
+ IBinder returnLocalStabilityBinder();
+
+ // DO NOT EVER IN A MILLION YEARS WRITE AN INTERFACE LIKE THIS!
+ // THIS IS ONLY FOR TESTING!
+ IBinder returnVintfStabilityBinder();
+}
+// DO NOT EVER IN A MILLION YEARS WRITE AN INTERFACE LIKE THIS!
+// THIS IS ONLY FOR TESTING!
+// Construct and return a binder with a specific stability
diff --git a/libs/binder/tests/binderDriverInterfaceTest.cpp b/libs/binder/tests/binderDriverInterfaceTest.cpp
index 77ebac8..f3ed6a6 100644
--- a/libs/binder/tests/binderDriverInterfaceTest.cpp
+++ b/libs/binder/tests/binderDriverInterfaceTest.cpp
@@ -230,7 +230,6 @@
}
TEST_F(BinderDriverInterfaceTest, Transaction) {
- binder_uintptr_t cookie = 1234;
struct {
uint32_t cmd1;
struct binder_transaction_data arg1;
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index 99a71bd..4f0c969 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -66,7 +66,6 @@
BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
- BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION,
BINDER_LIB_TEST_EXIT_TRANSACTION,
BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
@@ -550,50 +549,6 @@
ASSERT_TRUE(server != nullptr);
}
-TEST_F(BinderLibTest, DeathNotificationNoRefs)
-{
- status_t ret;
-
- sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
-
- {
- sp<IBinder> binder = addServer();
- ASSERT_TRUE(binder != nullptr);
- ret = binder->linkToDeath(testDeathRecipient);
- EXPECT_EQ(NO_ERROR, ret);
- }
- IPCThreadState::self()->flushCommands();
- ret = testDeathRecipient->waitEvent(5);
- EXPECT_EQ(NO_ERROR, ret);
-#if 0 /* Is there an unlink api that does not require a strong reference? */
- ret = binder->unlinkToDeath(testDeathRecipient);
- EXPECT_EQ(NO_ERROR, ret);
-#endif
-}
-
-TEST_F(BinderLibTest, DeathNotificationWeakRef)
-{
- status_t ret;
- wp<IBinder> wbinder;
-
- sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
-
- {
- sp<IBinder> binder = addServer();
- ASSERT_TRUE(binder != nullptr);
- ret = binder->linkToDeath(testDeathRecipient);
- EXPECT_EQ(NO_ERROR, ret);
- wbinder = binder;
- }
- IPCThreadState::self()->flushCommands();
- ret = testDeathRecipient->waitEvent(5);
- EXPECT_EQ(NO_ERROR, ret);
-#if 0 /* Is there an unlink api that does not require a strong reference? */
- ret = binder->unlinkToDeath(testDeathRecipient);
- EXPECT_EQ(NO_ERROR, ret);
-#endif
-}
-
TEST_F(BinderLibTest, DeathNotificationStrongRef)
{
status_t ret;
@@ -811,22 +766,6 @@
EXPECT_TRUE(strong_from_weak == nullptr);
}
-TEST_F(BinderLibTest, PromoteRemote) {
- int ret;
- Parcel data, reply;
- sp<IBinder> strong = new BBinder();
- sp<IBinder> server = addServer();
-
- ASSERT_TRUE(server != nullptr);
- ASSERT_TRUE(strong != nullptr);
-
- ret = data.writeWeakBinder(strong);
- EXPECT_EQ(NO_ERROR, ret);
-
- ret = server->transact(BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION, data, &reply);
- EXPECT_GE(ret, 0);
-}
-
TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
status_t ret;
Parcel data, reply;
@@ -852,7 +791,6 @@
wp<IBinder> keepFreedBinder;
{
Parcel data, reply;
- data.writeBool(false); /* request weak reference */
ret = server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply);
ASSERT_EQ(NO_ERROR, ret);
struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
@@ -861,8 +799,9 @@
* delete its reference to it - otherwise the transaction
* fails regardless of whether the driver is fixed.
*/
- keepFreedBinder = reply.readWeakBinder();
+ keepFreedBinder = reply.readStrongBinder();
}
+ IPCThreadState::self()->flushCommands();
{
Parcel data, reply;
data.writeStrongBinder(server);
@@ -998,7 +937,6 @@
case BINDER_LIB_TEST_ADD_POLL_SERVER:
case BINDER_LIB_TEST_ADD_SERVER: {
int ret;
- uint8_t buf[1] = { 0 };
int serverid;
if (m_id != 0) {
@@ -1196,29 +1134,6 @@
if (ret != size) return UNKNOWN_ERROR;
return NO_ERROR;
}
- case BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION: {
- int ret;
- wp<IBinder> weak;
- sp<IBinder> strong;
- Parcel data2, reply2;
- sp<IServiceManager> sm = defaultServiceManager();
- sp<IBinder> server = sm->getService(binderLibTestServiceName);
-
- weak = data.readWeakBinder();
- if (weak == nullptr) {
- return BAD_VALUE;
- }
- strong = weak.promote();
-
- ret = server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data2, &reply2);
- if (ret != NO_ERROR)
- exit(EXIT_FAILURE);
-
- if (strong == nullptr) {
- reply->setError(1);
- }
- return NO_ERROR;
- }
case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
alarm(10);
return NO_ERROR;
@@ -1227,13 +1142,8 @@
;
exit(EXIT_SUCCESS);
case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
- bool strongRef = data.readBool();
sp<IBinder> binder = new BBinder();
- if (strongRef) {
- reply->writeStrongBinder(binder);
- } else {
- reply->writeWeakBinder(binder);
- }
+ reply->writeStrongBinder(binder);
return NO_ERROR;
}
default:
@@ -1248,7 +1158,6 @@
bool m_serverStartRequested;
sp<IBinder> m_serverStarted;
sp<IBinder> m_strongRef;
- bool m_callbackPending;
sp<IBinder> m_callback;
};
@@ -1310,7 +1219,7 @@
* We simulate a single-threaded process using the binder poll
* interface; besides handling binder commands, it can also
* issue outgoing transactions, by storing a callback in
- * m_callback and setting m_callbackPending.
+ * m_callback.
*
* processPendingCall() will then issue that transaction.
*/
@@ -1337,8 +1246,6 @@
}
int main(int argc, char **argv) {
- int ret;
-
if (argc == 4 && !strcmp(argv[1], "--servername")) {
binderservername = argv[2];
} else {
diff --git a/libs/binder/tests/binderSafeInterfaceTest.cpp b/libs/binder/tests/binderSafeInterfaceTest.cpp
index 6a16e24..ce026e9 100644
--- a/libs/binder/tests/binderSafeInterfaceTest.cpp
+++ b/libs/binder/tests/binderSafeInterfaceTest.cpp
@@ -75,7 +75,7 @@
private:
int32_t mValue = 0;
- uint8_t mPadding[4] = {}; // Avoids a warning from -Wpadded
+ __attribute__((unused)) uint8_t mPadding[4] = {}; // Avoids a warning from -Wpadded
};
struct TestFlattenable : Flattenable<TestFlattenable> {
@@ -727,6 +727,7 @@
const std::vector<TestParcelable> a{TestParcelable{1}, TestParcelable{2}};
std::vector<TestParcelable> aPlusOne;
status_t result = mSafeInterfaceTest->increment(a, &aPlusOne);
+ ASSERT_EQ(NO_ERROR, result);
ASSERT_EQ(a.size(), aPlusOne.size());
for (size_t i = 0; i < a.size(); ++i) {
ASSERT_EQ(a[i].getValue() + 1, aPlusOne[i].getValue());
diff --git a/libs/binder/tests/binderStabilityTest.cpp b/libs/binder/tests/binderStabilityTest.cpp
new file mode 100644
index 0000000..d8159e3
--- /dev/null
+++ b/libs/binder/tests/binderStabilityTest.cpp
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2019 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 <binder/Binder.h>
+#include <binder/IBinder.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/Stability.h>
+#include <gtest/gtest.h>
+
+#include <sys/prctl.h>
+
+#include "BnBinderStabilityTest.h"
+#include "BpBinderStabilityTest.h"
+
+using namespace android;
+using android::binder::Status;
+
+const String16 kNoStabilityServer = String16("binder_stability_test_service_low");
+const String16 kCompilationUnitServer = String16("binder_stability_test_service_compl");
+const String16 kVintfServer = String16("binder_stability_test_service_vintf");
+
+sp<IBinder> getCompilationUnitStability() {
+ sp<IBinder> binder = new BBinder();
+ // NO! NO! NO! NO! DO NOT EVERY DO SOMETHING LIKE THIS?
+ // WHAT ARE YOU CRAZY? IT'S VERY DANGEROUS
+ internal::Stability::markCompilationUnit(binder.get()); // <- BAD, NO! DO NOT COPY
+ return binder;
+}
+
+sp<IBinder> getVintfStability() {
+ sp<IBinder> binder = new BBinder();
+ // NO! NO! NO! NO! DO NOT EVERY DO SOMETHING LIKE THIS?
+ // WHAT ARE YOU CRAZY? IT'S VERY DANGEROUS
+ internal::Stability::markVintf(binder.get()); // <- BAD, NO! DO NOT COPY
+ return binder;
+}
+
+// NO! NO! NO! Do not even think of doing something like this!
+// This is for testing! If a class like this was actually used in production,
+// it would ruin everything!
+class BadStabilityTester : public BnBinderStabilityTest {
+public:
+ Status sendBinder(const sp<IBinder>& /*binder*/) override {
+ return Status::ok();
+ }
+ Status returnNoStabilityBinder(sp<IBinder>* _aidl_return) override {
+ *_aidl_return = new BBinder();
+ return Status::ok();
+ }
+ Status returnLocalStabilityBinder(sp<IBinder>* _aidl_return) override {
+ *_aidl_return = getCompilationUnitStability();
+ return Status::ok();
+ }
+ Status returnVintfStabilityBinder(sp<IBinder>* _aidl_return) override {
+ *_aidl_return = getVintfStability();
+ return Status::ok();
+ }
+
+ static sp<IBinderStabilityTest> getNoStabilityServer() {
+ sp<IBinder> remote = new BadStabilityTester;
+ return new BpBinderStabilityTest(remote);
+ }
+ static sp<IBinderStabilityTest> getCompilationUnitStabilityServer() {
+ sp<IBinder> remote = new BadStabilityTester;
+ internal::Stability::markCompilationUnit(remote.get());
+ return new BpBinderStabilityTest(remote);
+ }
+ static sp<IBinderStabilityTest> getVintfStabilityServer() {
+ sp<IBinder> remote = new BadStabilityTester;
+ internal::Stability::markVintf(remote.get()); // <- BAD, NO! DO NOT COPY
+ return new BpBinderStabilityTest(remote);
+ }
+};
+
+void checkLocalStabilityBinder(const sp<IBinderStabilityTest>& complServer) {
+ // this binder should automatically be set to local stability
+ EXPECT_TRUE(complServer->sendBinder(new BBinder()).isOk());
+ EXPECT_TRUE(complServer->sendBinder(getCompilationUnitStability()).isOk());
+ EXPECT_TRUE(complServer->sendBinder(getVintfStability()).isOk());
+
+ sp<IBinder> out;
+ // should automatically be set to local stability
+ EXPECT_TRUE(complServer->returnNoStabilityBinder(&out).isOk());
+ EXPECT_NE(nullptr, out.get());
+
+ EXPECT_TRUE(complServer->returnLocalStabilityBinder(&out).isOk());
+ EXPECT_NE(nullptr, out.get());
+
+ EXPECT_TRUE(complServer->returnVintfStabilityBinder(&out).isOk());
+ EXPECT_NE(nullptr, out.get());
+}
+
+void checkHighStabilityServer(const sp<IBinderStabilityTest>& highStability) {
+ EXPECT_FALSE(highStability->sendBinder(new BBinder()).isOk());
+ EXPECT_FALSE(highStability->sendBinder(getCompilationUnitStability()).isOk());
+ EXPECT_TRUE(highStability->sendBinder(getVintfStability()).isOk());
+
+ sp<IBinder> out;
+ EXPECT_FALSE(highStability->returnNoStabilityBinder(&out).isOk());
+ EXPECT_EQ(nullptr, out.get());
+
+ EXPECT_FALSE(highStability->returnLocalStabilityBinder(&out).isOk());
+ EXPECT_EQ(nullptr, out.get());
+
+ EXPECT_TRUE(highStability->returnVintfStabilityBinder(&out).isOk());
+ EXPECT_NE(nullptr, out.get());
+}
+
+TEST(BinderStability, LocalNoStabilityServer) {
+ // in practice, a low stability server is probably one that hasn't been rebuilt
+ // or was written by hand.
+ auto server = BadStabilityTester::getNoStabilityServer();
+ ASSERT_NE(nullptr, IInterface::asBinder(server)->localBinder());
+
+ // it should be considered to have local stability
+ checkLocalStabilityBinder(server);
+}
+
+TEST(BinderStability, LocalLowStabilityServer) {
+ auto server = BadStabilityTester::getCompilationUnitStabilityServer();
+ ASSERT_NE(nullptr, IInterface::asBinder(server)->localBinder());
+ checkLocalStabilityBinder(server);
+}
+
+TEST(BinderStability, LocalHighStabilityServer) {
+ auto server = BadStabilityTester::getVintfStabilityServer();
+ ASSERT_NE(nullptr, IInterface::asBinder(server)->localBinder());
+ checkHighStabilityServer(server);
+}
+
+TEST(BinderStability, RemoteNoStabilityServer) {
+ sp<IBinder> remoteBinder = android::defaultServiceManager()->getService(kNoStabilityServer);
+ auto remoteServer = interface_cast<IBinderStabilityTest>(remoteBinder);
+
+ ASSERT_NE(nullptr, remoteServer.get());
+ ASSERT_NE(nullptr, IInterface::asBinder(remoteServer)->remoteBinder());
+
+ // it should be considered to have local stability
+ checkLocalStabilityBinder(remoteServer);
+}
+
+TEST(BinderStability, RemoteLowStabilityServer) {
+ sp<IBinder> remoteBinder = android::defaultServiceManager()->getService(kCompilationUnitServer);
+ auto remoteServer = interface_cast<IBinderStabilityTest>(remoteBinder);
+
+ ASSERT_NE(nullptr, remoteServer.get());
+ ASSERT_NE(nullptr, IInterface::asBinder(remoteServer)->remoteBinder());
+
+ checkLocalStabilityBinder(remoteServer);
+}
+
+TEST(BinderStability, RemoteVintfServer) {
+ sp<IBinder> remoteBinder = android::defaultServiceManager()->getService(kVintfServer);
+ auto remoteServer = interface_cast<IBinderStabilityTest>(remoteBinder);
+
+ ASSERT_NE(nullptr, remoteServer.get());
+ ASSERT_NE(nullptr, IInterface::asBinder(remoteServer)->remoteBinder());
+
+ checkHighStabilityServer(remoteServer);
+}
+
+class MarksStabilityInConstructor : public BBinder {
+public:
+ static bool gDestructed;
+
+ MarksStabilityInConstructor() {
+ internal::Stability::markCompilationUnit(this);
+ }
+ ~MarksStabilityInConstructor() {
+ gDestructed = true;
+ }
+};
+bool MarksStabilityInConstructor::gDestructed = false;
+
+TEST(BinderStability, MarkingObjectNoDestructTest) {
+ ASSERT_FALSE(MarksStabilityInConstructor::gDestructed);
+
+ // best practice is to put this directly in an sp, but for this test, we
+ // want to explicitly check what happens before that happens
+ MarksStabilityInConstructor* binder = new MarksStabilityInConstructor();
+ ASSERT_FALSE(MarksStabilityInConstructor::gDestructed);
+
+ sp<MarksStabilityInConstructor> binderSp = binder;
+ ASSERT_FALSE(MarksStabilityInConstructor::gDestructed);
+
+ binderSp = nullptr;
+ ASSERT_TRUE(MarksStabilityInConstructor::gDestructed);
+}
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+
+ if (fork() == 0) {
+ // child process
+ prctl(PR_SET_PDEATHSIG, SIGHUP);
+
+ sp<IBinder> noStability = new BadStabilityTester;
+ android::defaultServiceManager()->addService(kNoStabilityServer, noStability);
+
+ sp<IBinder> compil = new BadStabilityTester;
+ internal::Stability::markCompilationUnit(compil.get());
+ android::defaultServiceManager()->addService(kCompilationUnitServer, compil);
+
+ sp<IBinder> vintf = new BadStabilityTester;
+ internal::Stability::markVintf(vintf.get());
+ android::defaultServiceManager()->addService(kVintfServer, vintf);
+
+ IPCThreadState::self()->joinThreadPool(true);
+ exit(1); // should not reach
+ }
+
+ // This is not racey. Just giving these services some time to register before we call
+ // getService which sleeps for much longer...
+ usleep(10000);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/libs/binder/tests/binderValueTypeTest.cpp b/libs/binder/tests/binderValueTypeTest.cpp
deleted file mode 100644
index f8922b0..0000000
--- a/libs/binder/tests/binderValueTypeTest.cpp
+++ /dev/null
@@ -1,110 +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 <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <limits>
-#include <cstddef>
-#include <vector>
-
-#include "android-base/file.h"
-#include <gtest/gtest.h>
-
-#include <binder/Parcel.h>
-#include <binder/Value.h>
-#include <binder/Debug.h>
-
-using ::android::binder::Value;
-using ::android::os::PersistableBundle;
-using ::android::String16;
-using ::std::vector;
-
-#define VALUE_TYPE_TEST(T, TYPENAME, VAL) \
- TEST(ValueType, Handles ## TYPENAME) { \
- T x = VAL; \
- T y = T(); \
- Value value = VAL; \
- ASSERT_FALSE(value.empty()); \
- ASSERT_TRUE(value.is ## TYPENAME ()); \
- ASSERT_TRUE(value.get ## TYPENAME (&y)); \
- ASSERT_EQ(x, y); \
- ASSERT_EQ(value, Value(y)); \
- value.put ## TYPENAME (x); \
- ASSERT_EQ(value, Value(y)); \
- value = Value(); \
- ASSERT_TRUE(value.empty()); \
- ASSERT_NE(value, Value(y)); \
- value = y; \
- ASSERT_EQ(value, Value(x)); \
- }
-
-#define VALUE_TYPE_VECTOR_TEST(T, TYPENAME, VAL) \
- TEST(ValueType, Handles ## TYPENAME ## Vector) { \
- vector<T> x; \
- vector<T> y; \
- x.push_back(VAL); \
- x.push_back(T()); \
- Value value(x); \
- ASSERT_FALSE(value.empty()); \
- ASSERT_TRUE(value.is ## TYPENAME ## Vector()); \
- ASSERT_TRUE(value.get ## TYPENAME ## Vector(&y)); \
- ASSERT_EQ(x, y); \
- ASSERT_EQ(value, Value(y)); \
- value.put ## TYPENAME ## Vector(x); \
- ASSERT_EQ(value, Value(y)); \
- value = Value(); \
- ASSERT_TRUE(value.empty()); \
- ASSERT_NE(value, Value(y)); \
- value = y; \
- ASSERT_EQ(value, Value(x)); \
- }
-
-VALUE_TYPE_TEST(bool, Boolean, true)
-VALUE_TYPE_TEST(int32_t, Int, 31337)
-VALUE_TYPE_TEST(int64_t, Long, 13370133701337L)
-VALUE_TYPE_TEST(double, Double, 3.14159265358979323846)
-VALUE_TYPE_TEST(String16, String, String16("Lovely"))
-
-VALUE_TYPE_VECTOR_TEST(bool, Boolean, true)
-VALUE_TYPE_VECTOR_TEST(int32_t, Int, 31337)
-VALUE_TYPE_VECTOR_TEST(int64_t, Long, 13370133701337L)
-VALUE_TYPE_VECTOR_TEST(double, Double, 3.14159265358979323846)
-VALUE_TYPE_VECTOR_TEST(String16, String, String16("Lovely"))
-
-VALUE_TYPE_TEST(PersistableBundle, PersistableBundle, PersistableBundle())
-
-TEST(ValueType, HandlesClear) {
- Value value;
- ASSERT_TRUE(value.empty());
- value.putInt(31337);
- ASSERT_FALSE(value.empty());
- value.clear();
- ASSERT_TRUE(value.empty());
-}
-
-TEST(ValueType, HandlesSwap) {
- Value value_a, value_b;
- int32_t int_x;
- value_a.putInt(31337);
- ASSERT_FALSE(value_a.empty());
- ASSERT_TRUE(value_b.empty());
- value_a.swap(value_b);
- ASSERT_FALSE(value_b.empty());
- ASSERT_TRUE(value_a.empty());
- ASSERT_TRUE(value_b.getInt(&int_x));
- ASSERT_EQ(31337, int_x);
-}
diff --git a/libs/binder/tests/schd-dbg.cpp b/libs/binder/tests/schd-dbg.cpp
index ec9534a..ab4c56a 100644
--- a/libs/binder/tests/schd-dbg.cpp
+++ b/libs/binder/tests/schd-dbg.cpp
@@ -290,6 +290,7 @@
sta = tickNow();
status_t ret = workers[target]->transact(BINDER_NOP, data, &reply);
+ ASSERT(ret == NO_ERROR);
end = tickNow();
results_fifo->add_time(tickNano(sta, end));
diff --git a/libs/dumputils/Android.bp b/libs/dumputils/Android.bp
index 3412e14..e23de8e 100644
--- a/libs/dumputils/Android.bp
+++ b/libs/dumputils/Android.bp
@@ -17,7 +17,6 @@
shared_libs: [
"libbase",
- "libbinder",
"libhidlbase",
"libhidltransport",
"liblog",
diff --git a/libs/dumputils/dump_utils.cpp b/libs/dumputils/dump_utils.cpp
index d0cea0b..f924863 100644
--- a/libs/dumputils/dump_utils.cpp
+++ b/libs/dumputils/dump_utils.cpp
@@ -32,6 +32,7 @@
"/system/bin/mediametrics", // media.metrics
"/system/bin/mediaserver",
"/system/bin/netd",
+ "/system/bin/vold",
"/system/bin/sdcard",
"/system/bin/statsd",
"/system/bin/surfaceflinger",
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index c96a2dd..9d7f14c 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -989,14 +989,6 @@
mCallbackCondition.broadcast();
}
- // Wait without lock held
- if (connectedApi == NATIVE_WINDOW_API_EGL) {
- // Waiting here allows for two full buffers to be queued but not a
- // third. In the event that frames take varying time, this makes a
- // small trade-off in favor of latency rather than throughput.
- lastQueuedFence->waitForever("Throttling EGL Production");
- }
-
// Update and get FrameEventHistory.
nsecs_t postedTime = systemTime(SYSTEM_TIME_MONOTONIC);
NewFrameEventsEntry newFrameEventsEntry = {
@@ -1008,6 +1000,14 @@
addAndGetFrameTimestamps(&newFrameEventsEntry,
getFrameTimestamps ? &output->frameTimestamps : nullptr);
+ // Wait without lock held
+ if (connectedApi == NATIVE_WINDOW_API_EGL) {
+ // Waiting here allows for two full buffers to be queued but not a
+ // third. In the event that frames take varying time, this makes a
+ // small trade-off in favor of latency rather than throughput.
+ lastQueuedFence->waitForever("Throttling EGL Production");
+ }
+
return NO_ERROR;
}
diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp
index 76d242d..8aaa436 100644
--- a/libs/gui/ISurfaceComposer.cpp
+++ b/libs/gui/ISurfaceComposer.cpp
@@ -103,9 +103,10 @@
}
virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
+ bool& outCapturedSecureLayers,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
int32_t minLayerZ, int32_t maxLayerZ, bool useIdentityTransform,
- ISurfaceComposer::Rotation rotation) {
+ ISurfaceComposer::Rotation rotation, bool captureSecureLayers) {
Parcel data, reply;
data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
data.writeStrongBinder(display);
@@ -116,6 +117,7 @@
data.writeInt32(maxLayerZ);
data.writeInt32(static_cast<int32_t>(useIdentityTransform));
data.writeInt32(static_cast<int32_t>(rotation));
+ data.writeInt32(static_cast<int32_t>(captureSecureLayers));
status_t err = remote()->transact(BnSurfaceComposer::CAPTURE_SCREEN, data, &reply);
if (err != NO_ERROR) {
@@ -129,6 +131,8 @@
*outBuffer = new GraphicBuffer();
reply.read(**outBuffer);
+ outCapturedSecureLayers = reply.readBool();
+
return err;
}
@@ -644,13 +648,17 @@
int32_t maxLayerZ = data.readInt32();
bool useIdentityTransform = static_cast<bool>(data.readInt32());
int32_t rotation = data.readInt32();
+ bool captureSecureLayers = static_cast<bool>(data.readInt32());
- status_t res = captureScreen(display, &outBuffer, sourceCrop, reqWidth, reqHeight,
- minLayerZ, maxLayerZ, useIdentityTransform,
- static_cast<ISurfaceComposer::Rotation>(rotation));
+ bool capturedSecureLayers = false;
+ status_t res = captureScreen(display, &outBuffer, capturedSecureLayers, sourceCrop, reqWidth,
+ reqHeight, minLayerZ, maxLayerZ, useIdentityTransform,
+ static_cast<ISurfaceComposer::Rotation>(rotation), captureSecureLayers);
+
reply->writeInt32(res);
if (res == NO_ERROR) {
reply->write(*outBuffer);
+ reply->writeBool(capturedSecureLayers);
}
return NO_ERROR;
}
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index f3c6fd2..1002576 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -768,18 +768,29 @@
status_t ScreenshotClient::capture(const sp<IBinder>& display, Rect sourceCrop, uint32_t reqWidth,
uint32_t reqHeight, int32_t minLayerZ, int32_t maxLayerZ,
bool useIdentityTransform, uint32_t rotation,
- sp<GraphicBuffer>* outBuffer) {
+ bool captureSecureLayers, sp<GraphicBuffer>* outBuffer,
+ bool& outCapturedSecureLayers) {
sp<ISurfaceComposer> s(ComposerService::getComposerService());
if (s == NULL) return NO_INIT;
- status_t ret = s->captureScreen(display, outBuffer, sourceCrop, reqWidth, reqHeight, minLayerZ,
- maxLayerZ, useIdentityTransform,
- static_cast<ISurfaceComposer::Rotation>(rotation));
+ status_t ret = s->captureScreen(display, outBuffer, outCapturedSecureLayers, sourceCrop,
+ reqWidth, reqHeight, minLayerZ, maxLayerZ, useIdentityTransform,
+ static_cast<ISurfaceComposer::Rotation>(rotation),
+ captureSecureLayers);
if (ret != NO_ERROR) {
return ret;
}
return ret;
}
+status_t ScreenshotClient::capture(const sp<IBinder>& display, Rect sourceCrop, uint32_t reqWidth,
+ uint32_t reqHeight, int32_t minLayerZ, int32_t maxLayerZ,
+ bool useIdentityTransform, uint32_t rotation,
+ sp<GraphicBuffer>* outBuffer) {
+ bool ignored;
+ return capture(display, sourceCrop, reqWidth, reqHeight,
+ minLayerZ, maxLayerZ, useIdentityTransform, rotation, false, outBuffer, ignored);
+}
+
status_t ScreenshotClient::captureLayers(const sp<IBinder>& layerHandle, Rect sourceCrop,
float frameScale, sp<GraphicBuffer>* outBuffer) {
sp<ISurfaceComposer> s(ComposerService::getComposerService());
diff --git a/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp b/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp
index b1e44bb..ee88c23 100644
--- a/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp
+++ b/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp
@@ -1056,7 +1056,7 @@
status_t H2BGraphicBufferProducer::attachBuffer(
int* outSlot, const sp<GraphicBuffer>& buffer) {
- AnwBuffer tBuffer;
+ AnwBuffer tBuffer{};
wrapAs(&tBuffer, *buffer);
status_t fnStatus;
status_t transStatus = toStatusT(mBase->attachBuffer(tBuffer,
@@ -1071,7 +1071,7 @@
int slot,
const QueueBufferInput& input,
QueueBufferOutput* output) {
- HGraphicBufferProducer::QueueBufferInput tInput;
+ HGraphicBufferProducer::QueueBufferInput tInput{};
native_handle_t* nh;
if (!wrapAs(&tInput, &nh, input)) {
ALOGE("H2BGraphicBufferProducer::queueBuffer - "
diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h
index 5f79804..53b9a90 100644
--- a/libs/gui/include/gui/ISurfaceComposer.h
+++ b/libs/gui/include/gui/ISurfaceComposer.h
@@ -195,10 +195,22 @@
* it) around its center.
*/
virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
- Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
- int32_t minLayerZ, int32_t maxLayerZ, bool useIdentityTransform,
- Rotation rotation = eRotateNone) = 0;
+ bool& outCapturedSecureLayers, Rect sourceCrop,
+ uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
+ int32_t maxLayerZ, bool useIdentityTransform,
+ Rotation rotation = eRotateNone,
+ bool captureSecureLayers = false) = 0;
+ virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
+ Rect sourceCrop,
+ uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
+ int32_t maxLayerZ, bool useIdentityTransform,
+ Rotation rotation = eRotateNone,
+ bool captureSecureLayers = false) {
+ bool ignored;
+ return captureScreen(display, outBuffer, ignored, sourceCrop, reqWidth, reqHeight, minLayerZ,
+ maxLayerZ, useIdentityTransform, rotation, captureSecureLayers);
+ }
/**
* Capture a subtree of the layer hierarchy, potentially ignoring the root node.
*/
diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h
index ad8a8b0..49bb687 100644
--- a/libs/gui/include/gui/SurfaceComposerClient.h
+++ b/libs/gui/include/gui/SurfaceComposerClient.h
@@ -315,6 +315,11 @@
static status_t capture(const sp<IBinder>& display, Rect sourceCrop, uint32_t reqWidth,
uint32_t reqHeight, int32_t minLayerZ, int32_t maxLayerZ,
bool useIdentityTransform, uint32_t rotation,
+ bool captureSecureLayers, sp<GraphicBuffer>* outBuffer,
+ bool& outCapturedSecureLayers);
+ static status_t capture(const sp<IBinder>& display, Rect sourceCrop, uint32_t reqWidth,
+ uint32_t reqHeight, int32_t minLayerZ, int32_t maxLayerZ,
+ bool useIdentityTransform, uint32_t rotation,
sp<GraphicBuffer>* outBuffer);
static status_t captureLayers(const sp<IBinder>& layerHandle, Rect sourceCrop, float frameScale,
sp<GraphicBuffer>* outBuffer);
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index 959aafc..0fd4231 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -126,7 +126,7 @@
}
// This test probably doesn't belong here.
-TEST_F(SurfaceTest, ScreenshotsOfProtectedBuffersSucceed) {
+TEST_F(SurfaceTest, ScreenshotsOfProtectedBuffersDontSucceed) {
sp<ANativeWindow> anw(mSurface);
// Verify the screenshot works with no protected buffers.
@@ -134,7 +134,8 @@
sp<IBinder> display(sf->getBuiltInDisplay(
ISurfaceComposer::eDisplayIdMain));
sp<GraphicBuffer> outBuffer;
- ASSERT_EQ(NO_ERROR, sf->captureScreen(display, &outBuffer, Rect(),
+ bool ignored;
+ ASSERT_EQ(NO_ERROR, sf->captureScreen(display, &outBuffer, ignored, Rect(),
64, 64, 0, 0x7fffffff, false));
ASSERT_EQ(NO_ERROR, native_window_api_connect(anw.get(),
@@ -165,7 +166,7 @@
&buf));
ASSERT_EQ(NO_ERROR, anw->queueBuffer(anw.get(), buf, -1));
}
- ASSERT_EQ(NO_ERROR, sf->captureScreen(display, &outBuffer, Rect(),
+ ASSERT_EQ(NO_ERROR, sf->captureScreen(display, &outBuffer, ignored, Rect(),
64, 64, 0, 0x7fffffff, false));
}
@@ -601,10 +602,12 @@
ColorMode /*colorMode*/) override { return NO_ERROR; }
status_t captureScreen(const sp<IBinder>& /*display*/,
sp<GraphicBuffer>* /*outBuffer*/,
+ bool& /* outCapturedSecureLayers */,
Rect /*sourceCrop*/, uint32_t /*reqWidth*/, uint32_t /*reqHeight*/,
int32_t /*minLayerZ*/, int32_t /*maxLayerZ*/,
bool /*useIdentityTransform*/,
- Rotation /*rotation*/) override { return NO_ERROR; }
+ Rotation /*rotation*/,
+ bool /*captureSecureLayers*/) override { return NO_ERROR; }
virtual status_t captureLayers(const sp<IBinder>& /*parentHandle*/,
sp<GraphicBuffer>* /*outBuffer*/, const Rect& /*sourceCrop*/,
float /*frameScale*/, bool /*childrenOnly*/) override {
diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp
index ec7f927..6f570af 100644
--- a/libs/ui/Android.bp
+++ b/libs/ui/Android.bp
@@ -84,7 +84,6 @@
"android.hardware.configstore-utils",
"libbase",
"libcutils",
- "libhardware",
"libhidlbase",
"libhidltransport",
"libhwbinder",
diff --git a/libs/vr/libbufferhubqueue/Android.bp b/libs/vr/libbufferhubqueue/Android.bp
index 9f72c05..77c7911 100644
--- a/libs/vr/libbufferhubqueue/Android.bp
+++ b/libs/vr/libbufferhubqueue/Android.bp
@@ -26,10 +26,8 @@
]
sharedLibraries = [
- "libbase",
"libbinder",
"libcutils",
- "libhardware",
"liblog",
"libui",
"libutils",
diff --git a/opengl/libs/Android.bp b/opengl/libs/Android.bp
index d43c164..75dda6d 100644
--- a/opengl/libs/Android.bp
+++ b/opengl/libs/Android.bp
@@ -201,6 +201,10 @@
defaults: ["gles_libs_defaults"],
srcs: ["GLES2/gl2.cpp"],
cflags: ["-DLOG_TAG=\"libGLESv2\""],
+
+ // Bug: http://b/133874658 Disable native_coverage as we investigate a
+ // crash in surfaceflinger on coverage-enabled cuttlefish builds.
+ native_coverage: false,
}
//##############################################################################
diff --git a/opengl/libs/ETC1/etc1.cpp b/opengl/libs/ETC1/etc1.cpp
index 97d1085..19d428a 100644
--- a/opengl/libs/ETC1/etc1.cpp
+++ b/opengl/libs/ETC1/etc1.cpp
@@ -378,34 +378,30 @@
const etc1_byte* pColors, etc_compressed* pCompressed) {
int r1, g1, b1, r2, g2, b2; // 8 bit base colors for sub-blocks
bool differential;
- {
- int r51 = convert8To5(pColors[0]);
- int g51 = convert8To5(pColors[1]);
- int b51 = convert8To5(pColors[2]);
- int r52 = convert8To5(pColors[3]);
- int g52 = convert8To5(pColors[4]);
- int b52 = convert8To5(pColors[5]);
+ int r51 = convert8To5(pColors[0]);
+ int g51 = convert8To5(pColors[1]);
+ int b51 = convert8To5(pColors[2]);
+ int r52 = convert8To5(pColors[3]);
+ int g52 = convert8To5(pColors[4]);
+ int b52 = convert8To5(pColors[5]);
- r1 = convert5To8(r51);
- g1 = convert5To8(g51);
- b1 = convert5To8(b51);
+ r1 = convert5To8(r51);
+ g1 = convert5To8(g51);
+ b1 = convert5To8(b51);
- int dr = r52 - r51;
- int dg = g52 - g51;
- int db = b52 - b51;
+ int dr = r52 - r51;
+ int dg = g52 - g51;
+ int db = b52 - b51;
- differential = inRange4bitSigned(dr) && inRange4bitSigned(dg)
- && inRange4bitSigned(db);
- if (differential) {
- r2 = convert5To8(r51 + dr);
- g2 = convert5To8(g51 + dg);
- b2 = convert5To8(b51 + db);
- pCompressed->high |= (r51 << 27) | ((7 & dr) << 24) | (g51 << 19)
- | ((7 & dg) << 16) | (b51 << 11) | ((7 & db) << 8) | 2;
- }
- }
-
- if (!differential) {
+ differential = inRange4bitSigned(dr) && inRange4bitSigned(dg)
+ && inRange4bitSigned(db);
+ if (differential) {
+ r2 = convert5To8(r51 + dr);
+ g2 = convert5To8(g51 + dg);
+ b2 = convert5To8(b51 + db);
+ pCompressed->high |= (r51 << 27) | ((7 & dr) << 24) | (g51 << 19)
+ | ((7 & dg) << 16) | (b51 << 11) | ((7 & db) << 8) | 2;
+ } else {
int r41 = convert8To4(pColors[0]);
int g41 = convert8To4(pColors[1]);
int b41 = convert8To4(pColors[2]);
diff --git a/services/gpuservice/OWNERS b/services/gpuservice/OWNERS
new file mode 100644
index 0000000..5d02839
--- /dev/null
+++ b/services/gpuservice/OWNERS
@@ -0,0 +1,3 @@
+chrisforbes@google.com
+lpy@google.com
+zzyiwei@google.com
diff --git a/services/nativeperms/.clang-format b/services/nativeperms/.clang-format
deleted file mode 100644
index 6006e6f..0000000
--- a/services/nativeperms/.clang-format
+++ /dev/null
@@ -1,13 +0,0 @@
-BasedOnStyle: Google
-AllowShortFunctionsOnASingleLine: Inline
-AllowShortIfStatementsOnASingleLine: true
-AllowShortLoopsOnASingleLine: true
-BinPackArguments: true
-BinPackParameters: true
-ColumnLimit: 80
-CommentPragmas: NOLINT:.*
-ContinuationIndentWidth: 8
-DerivePointerAlignment: false
-IndentWidth: 4
-PointerAlignment: Left
-TabWidth: 4
diff --git a/services/nativeperms/Android.bp b/services/nativeperms/Android.bp
deleted file mode 100644
index cbc7d66..0000000
--- a/services/nativeperms/Android.bp
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 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.
-//
-
-cc_binary {
- name: "nativeperms",
- srcs: [
- "nativeperms.cpp",
- "android/os/IPermissionController.aidl",
- ],
- cflags: [
- "-Wall",
- "-Werror",
- ],
- shared_libs: [
- "libbinder",
- "libbrillo",
- "libbrillo-binder",
- "libchrome",
- "libutils",
- ],
- init_rc: ["nativeperms.rc"],
-}
diff --git a/services/nativeperms/android/os/IPermissionController.aidl b/services/nativeperms/android/os/IPermissionController.aidl
deleted file mode 100644
index 89db85c..0000000
--- a/services/nativeperms/android/os/IPermissionController.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-/* //device/java/android/android/os/IPowerManager.aidl
-**
-** Copyright 2007, 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.
-*/
-
-package android.os;
-
-/** @hide */
-interface IPermissionController {
- boolean checkPermission(String permission, int pid, int uid);
- String[] getPackagesForUid(int uid);
- boolean isRuntimePermission(String permission);
-}
diff --git a/services/nativeperms/android/os/README b/services/nativeperms/android/os/README
deleted file mode 100644
index e414499..0000000
--- a/services/nativeperms/android/os/README
+++ /dev/null
@@ -1,4 +0,0 @@
-IPermissionController.aidl in this directory is a verbatim copy of
-https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/IPermissionController.aidl,
-because some Brillo manifests do not currently include the frameworks/base repo.
-TODO(jorgelo): Figure out a way to use the .aidl file in frameworks/base.
diff --git a/services/nativeperms/nativeperms.cpp b/services/nativeperms/nativeperms.cpp
deleted file mode 100644
index 7f03bed..0000000
--- a/services/nativeperms/nativeperms.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright 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 <base/at_exit.h>
-#include <base/logging.h>
-#include <base/message_loop/message_loop.h>
-#include <binder/IServiceManager.h>
-#include <binder/Status.h>
-#include <brillo/binder_watcher.h>
-#include <brillo/message_loops/base_message_loop.h>
-#include <brillo/syslog_logging.h>
-#include <utils/String16.h>
-
-#include "android/os/BnPermissionController.h"
-
-namespace {
-static android::String16 serviceName("permission");
-}
-
-namespace android {
-
-class PermissionService : public android::os::BnPermissionController {
- public:
- ::android::binder::Status checkPermission(
- const ::android::String16& permission, int32_t pid, int32_t uid,
- bool* _aidl_return) {
- (void)permission;
- (void)pid;
- (void)uid;
- *_aidl_return = true;
- return binder::Status::ok();
- }
-
- ::android::binder::Status getPackagesForUid(
- int32_t uid, ::std::vector<::android::String16>* _aidl_return) {
- (void)uid;
- // Brillo doesn't currently have installable packages.
- if (_aidl_return) {
- _aidl_return->clear();
- }
- return binder::Status::ok();
- }
-
- ::android::binder::Status isRuntimePermission(
- const ::android::String16& permission, bool* _aidl_return) {
- (void)permission;
- // Brillo doesn't currently have runtime permissions.
- *_aidl_return = false;
- return binder::Status::ok();
- }
-};
-
-} // namespace android
-
-int main() {
- base::AtExitManager atExitManager;
- brillo::InitLog(brillo::kLogToSyslog);
- // Register the service with servicemanager.
- android::status_t status = android::defaultServiceManager()->addService(
- serviceName, new android::PermissionService());
- CHECK(status == android::OK) << "Failed to get IPermissionController "
- "binder from servicemanager.";
-
- // Create a message loop.
- base::MessageLoopForIO messageLoopForIo;
- brillo::BaseMessageLoop messageLoop{&messageLoopForIo};
-
- // Initialize a binder watcher.
- brillo::BinderWatcher watcher(&messageLoop);
- watcher.Init();
-
- // Run the message loop.
- messageLoop.Run();
-}
diff --git a/services/nativeperms/nativeperms.rc b/services/nativeperms/nativeperms.rc
deleted file mode 100644
index 704c0a2..0000000
--- a/services/nativeperms/nativeperms.rc
+++ /dev/null
@@ -1,4 +0,0 @@
-service nativeperms /system/bin/nativeperms
- class main
- user system
- group system
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index 5d4ac23..c8b2d91 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -152,6 +152,10 @@
lto: {
thin: true,
},
+ // TODO(b/131771163): Fix broken fuzzer support with LTO.
+ sanitize: {
+ fuzzer: false,
+ },
}
cc_binary {
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index d779ca4..725ae35 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -344,17 +344,19 @@
: DisplayRenderArea(device, device->getBounds(), device->getWidth(), device->getHeight(),
rotation) {}
DisplayRenderArea(const sp<const DisplayDevice> device, Rect sourceCrop, uint32_t reqWidth,
- uint32_t reqHeight, Transform::orientation_flags rotation)
+ uint32_t reqHeight, Transform::orientation_flags rotation,
+ bool allowSecureLayers = true)
: RenderArea(reqWidth, reqHeight, CaptureFill::OPAQUE,
getDisplayRotation(rotation, device->getInstallOrientation())),
mDevice(device),
- mSourceCrop(sourceCrop) {}
+ mSourceCrop(sourceCrop),
+ mAllowSecureLayers(allowSecureLayers) {}
const Transform& getTransform() const override { return mDevice->getTransform(); }
Rect getBounds() const override { return mDevice->getBounds(); }
int getHeight() const override { return mDevice->getHeight(); }
int getWidth() const override { return mDevice->getWidth(); }
- bool isSecure() const override { return mDevice->isSecure(); }
+ bool isSecure() const override { return mAllowSecureLayers && mDevice->isSecure(); }
bool needsFiltering() const override {
// check if the projection from the logical display to the physical
@@ -456,6 +458,7 @@
const sp<const DisplayDevice> mDevice;
const Rect mSourceCrop;
+ const bool mAllowSecureLayers;
};
}; // namespace android
diff --git a/services/surfaceflinger/RenderEngine/ProgramCache.cpp b/services/surfaceflinger/RenderEngine/ProgramCache.cpp
index fe992f1..2073b05 100644
--- a/services/surfaceflinger/RenderEngine/ProgramCache.cpp
+++ b/services/surfaceflinger/RenderEngine/ProgramCache.cpp
@@ -220,7 +220,7 @@
const highp float c2 = (2413.0 / 4096.0) * 32.0;
const highp float c3 = (2392.0 / 4096.0) * 32.0;
- highp vec3 tmp = pow(color, 1.0 / vec3(m2));
+ highp vec3 tmp = pow(clamp(color, 0.0, 1.0), 1.0 / vec3(m2));
tmp = max(tmp - c1, 0.0) / (c2 - c3 * tmp);
return pow(tmp, 1.0 / vec3(m1));
}
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 78d751a..5324470 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -494,9 +494,9 @@
// wait patiently for the window manager death
const String16 name("window");
- sp<IBinder> window(defaultServiceManager()->getService(name));
- if (window != 0) {
- window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
+ mWindowManager = defaultServiceManager()->getService(name);
+ if (mWindowManager != 0) {
+ mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
}
if (mVrFlinger) {
@@ -4849,10 +4849,11 @@
};
status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
- Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
- int32_t minLayerZ, int32_t maxLayerZ,
- bool useIdentityTransform,
- ISurfaceComposer::Rotation rotation) {
+ bool& outCapturedSecureLayers, Rect sourceCrop,
+ uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
+ int32_t maxLayerZ, bool useIdentityTransform,
+ ISurfaceComposer::Rotation rotation,
+ bool captureSecureLayers) {
ATRACE_CALL();
if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
@@ -4874,11 +4875,13 @@
}
}
- DisplayRenderArea renderArea(device, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
+ DisplayRenderArea renderArea(device, sourceCrop, reqWidth, reqHeight, renderAreaRotation,
+ captureSecureLayers);
auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
device, minLayerZ, maxLayerZ, std::placeholders::_1);
- return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
+ return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform,
+ outCapturedSecureLayers);
}
status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
@@ -5007,13 +5010,16 @@
visitor(layer);
});
};
- return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
+ bool outCapturedSecureLayers = false;
+ return captureScreenCommon(renderArea, traverseLayers, outBuffer, false,
+ outCapturedSecureLayers);
}
status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
TraverseLayersFunction traverseLayers,
sp<GraphicBuffer>* outBuffer,
- bool useIdentityTransform) {
+ bool useIdentityTransform,
+ bool& outCapturedSecureLayers) {
ATRACE_CALL();
const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
@@ -5049,7 +5055,8 @@
Mutex::Autolock _l(mStateLock);
renderArea.render([&]() {
result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
- useIdentityTransform, forSystem, &fd);
+ useIdentityTransform, forSystem, &fd,
+ outCapturedSecureLayers);
});
}
@@ -5122,21 +5129,19 @@
status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
TraverseLayersFunction traverseLayers,
ANativeWindowBuffer* buffer,
- bool useIdentityTransform,
- bool forSystem,
- int* outSyncFd) {
+ bool useIdentityTransform, bool forSystem,
+ int* outSyncFd, bool& outCapturedSecureLayers) {
ATRACE_CALL();
- bool secureLayerIsVisible = false;
-
traverseLayers([&](Layer* layer) {
- secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
+ outCapturedSecureLayers =
+ outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
});
// We allow the system server to take screenshots of secure layers for
// use in situations like the Screen-rotation animation and place
// the impetus on WindowManager to not persist them.
- if (secureLayerIsVisible && !forSystem) {
+ if (outCapturedSecureLayers && !forSystem) {
ALOGW("FB is protected: PERMISSION_DENIED");
return PERMISSION_DENIED;
}
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 0914a09..fce877c 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -422,9 +422,10 @@
virtual sp<IDisplayEventConnection> createDisplayEventConnection(
ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp);
virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
+ bool& outCapturedSecureLayers,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
int32_t minLayerZ, int32_t maxLayerZ, bool useIdentityTransform,
- ISurfaceComposer::Rotation rotation);
+ ISurfaceComposer::Rotation rotation, bool captureSecureLayers);
virtual status_t captureLayers(const sp<IBinder>& parentHandle, sp<GraphicBuffer>* outBuffer,
const Rect& sourceCrop, float frameScale, bool childrenOnly);
virtual status_t getDisplayStats(const sp<IBinder>& display,
@@ -577,11 +578,11 @@
bool yswap, bool useIdentityTransform);
status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
sp<GraphicBuffer>* outBuffer,
- bool useIdentityTransform);
+ bool useIdentityTransform, bool& outCapturedSecureLayers);
status_t captureScreenImplLocked(const RenderArea& renderArea,
TraverseLayersFunction traverseLayers,
ANativeWindowBuffer* buffer, bool useIdentityTransform,
- bool forSystem, int* outSyncFd);
+ bool forSystem, int* outSyncFd, bool& outCapturedSecureLayers);
void traverseLayersInDisplay(const sp<const DisplayDevice>& display, int32_t minLayerZ,
int32_t maxLayerZ, const LayerVector::Visitor& visitor);
@@ -892,6 +893,9 @@
// either AID_GRAPHICS or AID_SYSTEM.
status_t CheckTransactCodeCredentials(uint32_t code);
+ // to linkToDeath
+ sp<IBinder> mWindowManager;
+
std::unique_ptr<dvr::VrFlinger> mVrFlinger;
std::atomic<bool> mVrFlingerRequestsDisplay;
static bool useVrFlinger;
diff --git a/services/surfaceflinger/TimeStats/TimeStats.cpp b/services/surfaceflinger/TimeStats/TimeStats.cpp
index d4f1e29..9c34aa7 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.cpp
+++ b/services/surfaceflinger/TimeStats/TimeStats.cpp
@@ -277,6 +277,9 @@
std::lock_guard<std::mutex> lock(mMutex);
if (!timeStatsTracker.count(layerName)) return;
LayerRecord& layerRecord = timeStatsTracker[layerName];
+ if (layerRecord.waitData < 0 ||
+ layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+ return;
TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
if (timeRecord.frameNumber == frameNumber) {
timeRecord.latchTime = latchTime;
@@ -294,6 +297,9 @@
std::lock_guard<std::mutex> lock(mMutex);
if (!timeStatsTracker.count(layerName)) return;
LayerRecord& layerRecord = timeStatsTracker[layerName];
+ if (layerRecord.waitData < 0 ||
+ layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+ return;
TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
if (timeRecord.frameNumber == frameNumber) {
timeRecord.desiredTime = desiredTime;
@@ -311,6 +317,9 @@
std::lock_guard<std::mutex> lock(mMutex);
if (!timeStatsTracker.count(layerName)) return;
LayerRecord& layerRecord = timeStatsTracker[layerName];
+ if (layerRecord.waitData < 0 ||
+ layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+ return;
TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
if (timeRecord.frameNumber == frameNumber) {
timeRecord.acquireTime = acquireTime;
@@ -328,6 +337,9 @@
std::lock_guard<std::mutex> lock(mMutex);
if (!timeStatsTracker.count(layerName)) return;
LayerRecord& layerRecord = timeStatsTracker[layerName];
+ if (layerRecord.waitData < 0 ||
+ layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+ return;
TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
if (timeRecord.frameNumber == frameNumber) {
timeRecord.acquireFence = acquireFence;
@@ -345,6 +357,9 @@
std::lock_guard<std::mutex> lock(mMutex);
if (!timeStatsTracker.count(layerName)) return;
LayerRecord& layerRecord = timeStatsTracker[layerName];
+ if (layerRecord.waitData < 0 ||
+ layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+ return;
TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
if (timeRecord.frameNumber == frameNumber) {
timeRecord.presentTime = presentTime;
@@ -366,6 +381,9 @@
std::lock_guard<std::mutex> lock(mMutex);
if (!timeStatsTracker.count(layerName)) return;
LayerRecord& layerRecord = timeStatsTracker[layerName];
+ if (layerRecord.waitData < 0 ||
+ layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+ return;
TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
if (timeRecord.frameNumber == frameNumber) {
timeRecord.presentFence = presentFence;
diff --git a/services/surfaceflinger/layerproto/Android.bp b/services/surfaceflinger/layerproto/Android.bp
index ac147fe..172f5ac 100644
--- a/services/surfaceflinger/layerproto/Android.bp
+++ b/services/surfaceflinger/layerproto/Android.bp
@@ -43,7 +43,7 @@
type: "nano",
},
srcs: ["*.proto"],
- no_framework_libs: true,
+ sdk_version: "core_platform",
target: {
android: {
jarjar_rules: "jarjar-rules.txt",
diff --git a/services/surfaceflinger/tests/Transaction_test.cpp b/services/surfaceflinger/tests/Transaction_test.cpp
index 79f27df..e04e1e9 100644
--- a/services/surfaceflinger/tests/Transaction_test.cpp
+++ b/services/surfaceflinger/tests/Transaction_test.cpp
@@ -29,6 +29,7 @@
#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>
#include <private/gui/ComposerService.h>
+#include <private/android_filesystem_config.h>
#include <ui/DisplayInfo.h>
#include <ui/Rect.h>
@@ -36,6 +37,8 @@
#include <math.h>
#include <math/vec3.h>
+#include <sys/types.h>
+#include <unistd.h>
namespace android {
@@ -68,6 +71,30 @@
}
// Fill a region with the specified color.
+void fillANativeWindowBufferColor(const ANativeWindow_Buffer& buffer, const Rect& rect,
+ const Color& color) {
+ Rect r(0, 0, buffer.width, buffer.height);
+ if (!r.intersect(rect, &r)) {
+ return;
+ }
+
+ int32_t width = r.right - r.left;
+ int32_t height = r.bottom - r.top;
+
+ for (int32_t row = 0; row < height; row++) {
+ uint8_t* dst =
+ static_cast<uint8_t*>(buffer.bits) + (buffer.stride * (r.top + row) + r.left) * 4;
+ for (int32_t column = 0; column < width; column++) {
+ dst[0] = color.r;
+ dst[1] = color.g;
+ dst[2] = color.b;
+ dst[3] = color.a;
+ dst += 4;
+ }
+ }
+}
+
+// Fill a region with the specified color.
void fillBufferColor(const ANativeWindow_Buffer& buffer, const Rect& rect, const Color& color) {
int32_t x = rect.left;
int32_t y = rect.top;
@@ -319,6 +346,16 @@
return layer;
}
+ ANativeWindow_Buffer getBufferQueueLayerBuffer(const sp<SurfaceControl>& layer) {
+ // wait for previous transactions (such as setSize) to complete
+ Transaction().apply(true);
+
+ ANativeWindow_Buffer buffer = {};
+ EXPECT_EQ(NO_ERROR, layer->getSurface()->lock(&buffer, nullptr));
+
+ return buffer;
+ }
+
ANativeWindow_Buffer getLayerBuffer(const sp<SurfaceControl>& layer) {
// wait for previous transactions (such as setSize) to complete
Transaction().apply(true);
@@ -336,6 +373,21 @@
waitForLayerBuffers();
}
+ void postBufferQueueLayerBuffer(const sp<SurfaceControl>& layer) {
+ ASSERT_EQ(NO_ERROR, layer->getSurface()->unlockAndPost());
+
+ // wait for the newly posted buffer to be latched
+ waitForLayerBuffers();
+ }
+
+ virtual void fillBufferQueueLayerColor(const sp<SurfaceControl>& layer, const Color& color,
+ int32_t bufferWidth, int32_t bufferHeight) {
+ ANativeWindow_Buffer buffer;
+ ASSERT_NO_FATAL_FAILURE(buffer = getBufferQueueLayerBuffer(layer));
+ fillANativeWindowBufferColor(buffer, Rect(0, 0, bufferWidth, bufferHeight), color);
+ postBufferQueueLayerBuffer(layer);
+ }
+
void fillLayerColor(const sp<SurfaceControl>& layer, const Color& color) {
ANativeWindow_Buffer buffer;
ASSERT_NO_FATAL_FAILURE(buffer = getLayerBuffer(layer));
@@ -847,6 +899,57 @@
false));
}
+/** RAII Wrapper around get/seteuid */
+class UIDFaker {
+ uid_t oldId;
+public:
+ UIDFaker(uid_t uid) {
+ oldId = geteuid();
+ seteuid(uid);
+ }
+ ~UIDFaker() {
+ seteuid(oldId);
+ }
+};
+
+TEST_F(LayerTransactionTest, SetFlagsSecureEUidSystem) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
+
+ sp<ISurfaceComposer> composer = ComposerService::getComposerService();
+ sp<GraphicBuffer> outBuffer;
+ Transaction()
+ .setFlags(layer, layer_state_t::eLayerSecure, layer_state_t::eLayerSecure)
+ .apply(true);
+
+ ASSERT_EQ(PERMISSION_DENIED,
+ composer->captureScreen(mDisplay, &outBuffer, Rect(), 0, 0, 0, INT_MAX, false));
+
+ UIDFaker f(AID_SYSTEM);
+
+ // By default the system can capture screenshots with secure layers but they
+ // will be blacked out
+ ASSERT_EQ(NO_ERROR,
+ composer->captureScreen(mDisplay, &outBuffer, Rect(), 0, 0, 0, INT_MAX, false));
+
+ {
+ SCOPED_TRACE("as system");
+ auto shot = screenshot();
+ shot->expectColor(Rect(0, 0, 32, 32), Color::BLACK);
+ }
+
+ // Here we pass captureSecureLayers = true and since we are AID_SYSTEM we should be able
+ // to receive them...we are expected to take care with the results.
+ bool outCapturedSecureLayers = false;
+ ASSERT_EQ(NO_ERROR,
+ composer->captureScreen(mDisplay, &outBuffer, outCapturedSecureLayers,
+ Rect(), 0, 0, 0, INT_MAX, false, ISurfaceComposer::eRotateNone, true));
+ ASSERT_EQ(true, outCapturedSecureLayers);
+ ScreenCapture sc(outBuffer);
+ sc.expectColor(Rect(0, 0, 32, 32), Color::RED);
+}
+
TEST_F(LayerTransactionTest, SetTransparentRegionHintBasic) {
const Rect top(0, 0, 32, 16);
const Rect bottom(0, 16, 32, 32);
diff --git a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
index 9b31985..28cac2e 100644
--- a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
+++ b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
@@ -54,10 +54,11 @@
namespace {
// Mock test helpers
+using ::testing::_;
+using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SetArgPointee;
-using ::testing::_;
using Transaction = SurfaceComposerClient::Transaction;
diff --git a/services/thermalservice/Android.bp b/services/thermalservice/Android.bp
index d754560..1519618 100644
--- a/services/thermalservice/Android.bp
+++ b/services/thermalservice/Android.bp
@@ -1,34 +1,3 @@
-subdirs = [
- "libthermalcallback"
-]
-
-cc_library {
- name: "libthermalservice",
-
- srcs: [
- "aidl/android/os/IThermalEventListener.aidl",
- "aidl/android/os/IThermalService.aidl",
- "aidl/android/os/Temperature.cpp",
- ],
- aidl: {
- include_dirs: ["frameworks/native/services/thermalservice/aidl"],
- export_aidl_headers: true,
- },
- export_include_dirs: ["aidl"],
-
- shared_libs: [
- "libbinder",
- "libutils",
- ],
-
- cflags: [
- "-Wall",
- "-Werror",
- "-Wunused",
- "-Wunreachable-code",
- ],
-}
-
cc_binary {
name: "thermalserviced",
diff --git a/services/thermalservice/aidl/Android.bp b/services/thermalservice/aidl/Android.bp
new file mode 100644
index 0000000..f1ec656
--- /dev/null
+++ b/services/thermalservice/aidl/Android.bp
@@ -0,0 +1,26 @@
+cc_library {
+ name: "libthermalservice",
+
+ srcs: [
+ "android/os/IThermalEventListener.aidl",
+ "android/os/IThermalService.aidl",
+ "android/os/Temperature.cpp",
+ ],
+ aidl: {
+ local_include_dirs: ["."],
+ export_aidl_headers: true,
+ },
+ export_include_dirs: ["."],
+
+ shared_libs: [
+ "libbinder",
+ "libutils",
+ ],
+
+ cflags: [
+ "-Wall",
+ "-Werror",
+ "-Wunused",
+ "-Wunreachable-code",
+ ],
+}
diff --git a/services/vr/hardware_composer/Android.bp b/services/vr/hardware_composer/Android.bp
index 90edf69..dddbc76 100644
--- a/services/vr/hardware_composer/Android.bp
+++ b/services/vr/hardware_composer/Android.bp
@@ -1,174 +1,147 @@
cc_library_shared {
- name: "libvr_hwc-hal",
+ name: "libvr_hwc-hal",
- srcs: [
- "impl/vr_hwc.cpp",
- "impl/vr_composer_client.cpp",
- ],
+ srcs: [
+ "impl/vr_hwc.cpp",
+ "impl/vr_composer_client.cpp",
+ ],
- static_libs: [
- "libbroadcastring",
- "libdisplay",
- ],
+ static_libs: [
+ "libbroadcastring",
+ "libdisplay",
+ ],
- shared_libs: [
- "android.frameworks.vr.composer@1.0",
- "android.hardware.graphics.composer@2.1",
- "android.hardware.graphics.mapper@2.0",
- "libbase",
- "libbufferhubqueue",
- "libbinder",
- "libcutils",
- "libfmq",
- "libhardware",
- "libhidlbase",
- "libhidltransport",
- "liblog",
- "libsync",
- "libui",
- "libutils",
- "libpdx_default_transport",
- ],
+ shared_libs: [
+ "android.frameworks.vr.composer@1.0",
+ "android.hardware.graphics.composer@2.1",
+ "android.hardware.graphics.mapper@2.0",
+ "libbase",
+ "libbufferhubqueue",
+ "libbinder",
+ "libcutils",
+ "libfmq",
+ "libhardware",
+ "libhidlbase",
+ "libhidltransport",
+ "liblog",
+ "libsync",
+ "libui",
+ "libutils",
+ "libpdx_default_transport",
+ ],
- header_libs: [
- "android.hardware.graphics.composer@2.1-command-buffer",
- "android.hardware.graphics.composer@2.1-hal",
- ],
+ header_libs: [
+ "android.hardware.graphics.composer@2.1-command-buffer",
+ "android.hardware.graphics.composer@2.1-hal",
+ ],
- export_header_lib_headers: [
- "android.hardware.graphics.composer@2.1-hal",
- ],
+ export_header_lib_headers: [
+ "android.hardware.graphics.composer@2.1-hal",
+ ],
- export_shared_lib_headers: [
- "android.frameworks.vr.composer@1.0",
- "android.hardware.graphics.composer@2.1",
- ],
+ export_shared_lib_headers: [
+ "android.frameworks.vr.composer@1.0",
+ "android.hardware.graphics.composer@2.1",
+ ],
- export_include_dirs: ["."],
+ export_include_dirs: ["."],
- cflags: [
- "-DLOG_TAG=\"vr_hwc\"",
- "-Wall",
- "-Werror",
- // mVrClient unused in vr_composer_client.cpp
- "-Wno-error=unused-private-field",
- // Warnings in vr_hwc.cpp to be fixed after sync of goog/master.
- "-Wno-sign-compare",
- "-Wno-unused-parameter",
- ],
+ cflags: [
+ "-DLOG_TAG=\"vr_hwc\"",
+ "-Wall",
+ "-Werror",
+ // mVrClient unused in vr_composer_client.cpp
+ "-Wno-error=unused-private-field",
+ // Warnings in vr_hwc.cpp to be fixed after sync of goog/master.
+ "-Wno-sign-compare",
+ "-Wno-unused-parameter",
+ ],
}
cc_library_static {
- name: "libvr_hwc-binder",
- srcs: [
- "aidl/android/dvr/IVrComposer.aidl",
- "aidl/android/dvr/IVrComposerCallback.aidl",
- "aidl/android/dvr/parcelable_composer_frame.cpp",
- "aidl/android/dvr/parcelable_composer_layer.cpp",
- "aidl/android/dvr/parcelable_unique_fd.cpp",
- ],
- aidl: {
- include_dirs: ["frameworks/native/services/vr/hardware_composer/aidl"],
- export_aidl_headers: true,
- },
- export_include_dirs: ["aidl"],
-
- cflags: [
- "-Wall",
- "-Werror",
- ],
-
- shared_libs: [
- "libbinder",
- "libui",
- "libutils",
- "libvr_hwc-hal",
- ],
-}
-
-cc_library_static {
- name: "libvr_hwc-impl",
- srcs: [
- "vr_composer.cpp",
- ],
- static_libs: [
- "libvr_hwc-binder",
- ],
- shared_libs: [
- "libbase",
- "libbinder",
- "liblog",
- "libui",
- "libutils",
- "libvr_hwc-hal",
- ],
- export_shared_lib_headers: [
- "libvr_hwc-hal",
- ],
- cflags: [
- "-DLOG_TAG=\"vr_hwc\"",
- "-Wall",
- "-Werror",
- ],
+ name: "libvr_hwc-impl",
+ srcs: [
+ "vr_composer.cpp",
+ ],
+ static_libs: [
+ "libvr_hwc-binder",
+ ],
+ shared_libs: [
+ "libbase",
+ "libbinder",
+ "liblog",
+ "libui",
+ "libutils",
+ "libvr_hwc-hal",
+ ],
+ export_shared_lib_headers: [
+ "libvr_hwc-hal",
+ ],
+ cflags: [
+ "-DLOG_TAG=\"vr_hwc\"",
+ "-Wall",
+ "-Werror",
+ ],
}
cc_binary {
- name: "vr_hwc",
- srcs: [
- "vr_hardware_composer_service.cpp"
- ],
- static_libs: [
- "libvr_hwc-impl",
- // NOTE: This needs to be included after the *-impl lib otherwise the
- // symbols in the *-binder library get optimized out.
- "libvr_hwc-binder",
- ],
- shared_libs: [
- "android.frameworks.vr.composer@1.0",
- "android.hardware.graphics.composer@2.1",
- "libbase",
- "libbinder",
- "liblog",
- "libhardware",
- "libhwbinder",
- "libui",
- "libutils",
- "libvr_hwc-hal",
- ],
- cflags: [
- "-DLOG_TAG=\"vr_hwc\"",
- "-Wall",
- "-Werror",
- ],
- init_rc: [
- "vr_hwc.rc",
- ],
+ name: "vr_hwc",
+ srcs: [
+ "vr_hardware_composer_service.cpp",
+ ],
+ static_libs: [
+ "libvr_hwc-impl",
+ // NOTE: This needs to be included after the *-impl lib otherwise the
+ // symbols in the *-binder library get optimized out.
+ "libvr_hwc-binder",
+ ],
+ shared_libs: [
+ "android.frameworks.vr.composer@1.0",
+ "android.hardware.graphics.composer@2.1",
+ "libbase",
+ "libbinder",
+ "liblog",
+ "libhardware",
+ "libhwbinder",
+ "libhidlbase",
+ "libui",
+ "libutils",
+ "libvr_hwc-hal",
+ ],
+ cflags: [
+ "-DLOG_TAG=\"vr_hwc\"",
+ "-Wall",
+ "-Werror",
+ ],
+ init_rc: [
+ "vr_hwc.rc",
+ ],
}
cc_test {
- name: "vr_hwc_test",
- gtest: true,
- srcs: ["tests/vr_composer_test.cpp"],
- static_libs: [
- "libgtest",
- "libvr_hwc-impl",
- // NOTE: This needs to be included after the *-impl lib otherwise the
- // symbols in the *-binder library get optimized out.
- "libvr_hwc-binder",
- ],
- cflags: [
- "-Wall",
- "-Werror",
- // warnings in vr_composer_test.cpp to be fixed after merge of goog/master
- "-Wno-sign-compare",
- "-Wno-unused-parameter",
- ],
- shared_libs: [
- "libbase",
- "libbinder",
- "liblog",
- "libui",
- "libutils",
- ],
+ name: "vr_hwc_test",
+ gtest: true,
+ srcs: ["tests/vr_composer_test.cpp"],
+ static_libs: [
+ "libgtest",
+ "libvr_hwc-impl",
+ // NOTE: This needs to be included after the *-impl lib otherwise the
+ // symbols in the *-binder library get optimized out.
+ "libvr_hwc-binder",
+ ],
+ cflags: [
+ "-Wall",
+ "-Werror",
+ // warnings in vr_composer_test.cpp to be fixed after merge of goog/master
+ "-Wno-sign-compare",
+ "-Wno-unused-parameter",
+ ],
+ shared_libs: [
+ "libbase",
+ "libbinder",
+ "liblog",
+ "libui",
+ "libutils",
+ ],
}
diff --git a/services/vr/hardware_composer/aidl/Android.bp b/services/vr/hardware_composer/aidl/Android.bp
new file mode 100644
index 0000000..a1d5392
--- /dev/null
+++ b/services/vr/hardware_composer/aidl/Android.bp
@@ -0,0 +1,27 @@
+cc_library_static {
+ name: "libvr_hwc-binder",
+ srcs: [
+ "android/dvr/IVrComposer.aidl",
+ "android/dvr/IVrComposerCallback.aidl",
+ "android/dvr/parcelable_composer_frame.cpp",
+ "android/dvr/parcelable_composer_layer.cpp",
+ "android/dvr/parcelable_unique_fd.cpp",
+ ],
+ aidl: {
+ local_include_dirs: ["."],
+ export_aidl_headers: true,
+ },
+ export_include_dirs: ["."],
+
+ cflags: [
+ "-Wall",
+ "-Werror",
+ ],
+
+ shared_libs: [
+ "libbinder",
+ "libui",
+ "libutils",
+ "libvr_hwc-hal",
+ ],
+}
diff --git a/services/vr/virtual_touchpad/Android.bp b/services/vr/virtual_touchpad/Android.bp
index 131a306..dcaa663 100644
--- a/services/vr/virtual_touchpad/Android.bp
+++ b/services/vr/virtual_touchpad/Android.bp
@@ -62,7 +62,7 @@
service_src = [
"main.cpp",
"VirtualTouchpadService.cpp",
- "aidl/android/dvr/IVirtualTouchpadService.aidl",
+ ":virtualtouchpad_aidl",
]
service_static_libs = [
@@ -99,7 +99,7 @@
client_src = [
"VirtualTouchpadClient.cpp",
"DvrVirtualTouchpadClient.cpp",
- "aidl/android/dvr/IVirtualTouchpadService.aidl",
+ ":virtualtouchpad_aidl",
]
client_shared_libs = [
@@ -122,3 +122,9 @@
name: "libvirtualtouchpadclient",
export_include_dirs: ["include"],
}
+
+filegroup {
+ name: "virtualtouchpad_aidl",
+ srcs: ["aidl/android/dvr/IVirtualTouchpadService.aidl"],
+ path: "aidl",
+}
diff --git a/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h b/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h
index 7d73f06..268e4bd 100644
--- a/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h
+++ b/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h
@@ -13,12 +13,6 @@
public:
// VirtualTouchpad implementation:
static std::unique_ptr<VirtualTouchpad> Create();
- status_t Attach() override;
- status_t Detach() override;
- status_t Touch(int touchpad, float x, float y, float pressure) override;
- status_t ButtonState(int touchpad, int buttons) override;
- status_t Scroll(int touchpad, float x, float y) override;
- void dumpInternal(String8& result) override;
protected:
VirtualTouchpadClient() {}
diff --git a/vulkan/libvulkan/layers_extensions.cpp b/vulkan/libvulkan/layers_extensions.cpp
index ba4cf00..a7b7a6f 100644
--- a/vulkan/libvulkan/layers_extensions.cpp
+++ b/vulkan/libvulkan/layers_extensions.cpp
@@ -385,9 +385,8 @@
return;
}
std::string prefix(dir_in_zip + "/");
- const ZipString prefix_str(prefix.c_str());
void* iter_cookie = nullptr;
- if ((err = StartIteration(zip, &iter_cookie, &prefix_str, nullptr)) != 0) {
+ if ((err = StartIteration(zip, &iter_cookie, prefix, "")) != 0) {
ALOGE("failed to iterate entries in apk '%s': %d", zipname.c_str(),
err);
CloseArchive(zip);
@@ -396,11 +395,9 @@
ALOGD("searching for layers in '%s!/%s'", zipname.c_str(),
dir_in_zip.c_str());
ZipEntry entry;
- ZipString name;
+ std::string name;
while (Next(iter_cookie, &entry, &name) == 0) {
- std::string filename(
- reinterpret_cast<const char*>(name.name) + prefix.length(),
- name.name_length - prefix.length());
+ std::string filename(name.substr(prefix.length()));
// only enumerate direct entries of the directory, not subdirectories
if (filename.find('/') != filename.npos)
continue;