Merge "libbinder: split out PackageManagerNative aidl"
diff --git a/cmds/cmd/fuzzer/Android.bp b/cmds/cmd/fuzzer/Android.bp
index 8262bc2..a65f6de 100644
--- a/cmds/cmd/fuzzer/Android.bp
+++ b/cmds/cmd/fuzzer/Android.bp
@@ -30,12 +30,12 @@
],
static_libs: [
"libcmd",
- "libutils",
"liblog",
"libselinux",
],
shared_libs: [
"libbinder",
+ "libutils",
],
fuzz_config: {
cc: [
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index 68fed30..9592562 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -265,6 +265,15 @@
defaults: ["libbinder_tls_defaults"],
}
+// For testing
+cc_library_static {
+ name: "libbinder_tls_static",
+ defaults: ["libbinder_tls_defaults"],
+ visibility: [
+ ":__subpackages__",
+ ],
+}
+
// AIDL interface between libbinder and framework.jar
filegroup {
name: "libbinder_aidl",
@@ -328,6 +337,8 @@
"//packages/modules/Virtualization/authfs:__subpackages__",
"//packages/modules/Virtualization/compos:__subpackages__",
"//packages/modules/Virtualization/microdroid",
+ "//packages/modules/Virtualization/microdroid_manager",
+ "//packages/modules/Virtualization/virtualizationservice",
],
}
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index e623874..99b6be8 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -104,7 +104,7 @@
switch (obj.hdr.type) {
case BINDER_TYPE_BINDER:
if (obj.binder) {
- LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
+ LOG_REFS("Parcel %p acquiring reference on local %llu", who, obj.cookie);
reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
}
return;
@@ -137,7 +137,7 @@
switch (obj.hdr.type) {
case BINDER_TYPE_BINDER:
if (obj.binder) {
- LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
+ LOG_REFS("Parcel %p releasing reference on local %llu", who, obj.cookie);
reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
}
return;
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index 52a6cf1..8ab0e88 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -18,6 +18,7 @@
#include <binder/ProcessState.h>
+#include <android-base/result.h>
#include <binder/BpBinder.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
@@ -384,68 +385,73 @@
return mDriverName;
}
-static int open_driver(const char *driver)
-{
+static base::Result<int> open_driver(const char* driver) {
int fd = open(driver, O_RDWR | O_CLOEXEC);
- if (fd >= 0) {
- int vers = 0;
- status_t result = ioctl(fd, BINDER_VERSION, &vers);
- if (result == -1) {
- ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
- close(fd);
- fd = -1;
- }
- if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
- ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
- vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
- close(fd);
- fd = -1;
- }
- size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
- result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
- if (result == -1) {
- ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
- }
- uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
- result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
- if (result == -1) {
- ALOGV("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
- }
- } else {
- ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));
+ if (fd < 0) {
+ return base::ErrnoError() << "Opening '" << driver << "' failed";
+ }
+ int vers = 0;
+ status_t result = ioctl(fd, BINDER_VERSION, &vers);
+ if (result == -1) {
+ close(fd);
+ return base::ErrnoError() << "Binder ioctl to obtain version failed";
+ }
+ if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
+ close(fd);
+ return base::Error() << "Binder driver protocol(" << vers
+ << ") does not match user space protocol("
+ << BINDER_CURRENT_PROTOCOL_VERSION
+ << ")! ioctl() return value: " << result;
+ }
+ size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
+ result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
+ if (result == -1) {
+ ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
+ }
+ uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
+ result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
+ if (result == -1) {
+ ALOGV("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
}
return fd;
}
-ProcessState::ProcessState(const char *driver)
- : mDriverName(String8(driver))
- , mDriverFD(open_driver(driver))
- , mVMStart(MAP_FAILED)
- , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
- , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
- , mExecutingThreadsCount(0)
- , mWaitingForThreads(0)
- , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
- , mStarvationStartTimeMs(0)
- , mThreadPoolStarted(false)
- , mThreadPoolSeq(1)
- , mCallRestriction(CallRestriction::NONE)
-{
- if (mDriverFD >= 0) {
+ProcessState::ProcessState(const char* driver)
+ : mDriverName(String8(driver)),
+ mDriverFD(-1),
+ mVMStart(MAP_FAILED),
+ mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
+ mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
+ mExecutingThreadsCount(0),
+ mWaitingForThreads(0),
+ mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
+ mStarvationStartTimeMs(0),
+ mThreadPoolStarted(false),
+ mThreadPoolSeq(1),
+ mCallRestriction(CallRestriction::NONE) {
+ base::Result<int> opened = open_driver(driver);
+
+ if (opened.ok()) {
// mmap the binder, providing a chunk of virtual address space to receive transactions.
- mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
+ mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
+ opened.value(), 0);
if (mVMStart == MAP_FAILED) {
+ close(opened.value());
// *sigh*
- ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());
- close(mDriverFD);
- mDriverFD = -1;
+ opened = base::Error()
+ << "Using " << driver << " failed: unable to mmap transaction memory.";
mDriverName.clear();
}
}
#ifdef __ANDROID__
- LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver '%s' could not be opened. Terminating.", driver);
+ LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
+ driver, opened.error().message().c_str());
#endif
+
+ if (opened.ok()) {
+ mDriverFD = opened.value();
+ }
}
ProcessState::~ProcessState()
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index a20445b..ad9ba96 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -39,8 +39,7 @@
using base::ScopeGuard;
using base::unique_fd;
-RpcServer::RpcServer(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
- : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {}
+RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
RpcServer::~RpcServer() {
(void)shutdown();
}
@@ -49,7 +48,9 @@
// Default is without TLS.
if (rpcTransportCtxFactory == nullptr)
rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
- return sp<RpcServer>::make(std::move(rpcTransportCtxFactory));
+ auto ctx = rpcTransportCtxFactory->newServerCtx();
+ if (ctx == nullptr) return nullptr;
+ return sp<RpcServer>::make(std::move(ctx));
}
void RpcServer::iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction() {
@@ -138,6 +139,20 @@
return ret;
}
+std::string RpcServer::getCertificate(CertificateFormat format) {
+ std::lock_guard<std::mutex> _l(mLock);
+ return mCtx->getCertificate(format);
+}
+
+status_t RpcServer::addTrustedPeerCertificate(CertificateFormat format, std::string_view cert) {
+ std::lock_guard<std::mutex> _l(mLock);
+ // Ensure that join thread is not running or shutdown trigger is not set up. In either case,
+ // it means there are child threads running. It is invalid to add trusted peer certificates
+ // after join thread and/or child threads are running to avoid race condition.
+ if (mJoinThreadRunning || mShutdownTrigger != nullptr) return INVALID_OPERATION;
+ return mCtx->addTrustedPeerCertificate(format, cert);
+}
+
static void joinRpcServer(sp<RpcServer>&& thiz) {
thiz->join();
}
@@ -159,10 +174,6 @@
mJoinThreadRunning = true;
mShutdownTrigger = FdTrigger::make();
LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Cannot create join signaler");
-
- mCtx = mRpcTransportCtxFactory->newServerCtx();
- LOG_ALWAYS_FATAL_IF(mCtx == nullptr, "Unable to create RpcTransportCtx with %s sockets",
- mRpcTransportCtxFactory->toCString());
}
status_t status;
@@ -229,7 +240,6 @@
LOG_RPC_DETAIL("Finished waiting on shutdown.");
mShutdownTrigger = nullptr;
- mCtx = nullptr;
return true;
}
diff --git a/libs/binder/RpcSession.cpp b/libs/binder/RpcSession.cpp
index 4c47005..c57b749 100644
--- a/libs/binder/RpcSession.cpp
+++ b/libs/binder/RpcSession.cpp
@@ -49,8 +49,7 @@
using base::unique_fd;
-RpcSession::RpcSession(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
- : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {
+RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
LOG_RPC_DETAIL("RpcSession created %p", this);
mState = std::make_unique<RpcState>();
@@ -63,11 +62,26 @@
"Should not be able to destroy a session with servers in use.");
}
-sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
+sp<RpcSession> RpcSession::make() {
// Default is without TLS.
- if (rpcTransportCtxFactory == nullptr)
- rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
- return sp<RpcSession>::make(std::move(rpcTransportCtxFactory));
+ return make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
+}
+
+sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory,
+ std::optional<CertificateFormat> serverCertificateFormat,
+ std::optional<std::string> serverCertificate) {
+ auto ctx = rpcTransportCtxFactory->newClientCtx();
+ if (ctx == nullptr) return nullptr;
+ LOG_ALWAYS_FATAL_IF(serverCertificateFormat.has_value() != serverCertificate.has_value());
+ if (serverCertificateFormat.has_value() && serverCertificate.has_value()) {
+ status_t status =
+ ctx->addTrustedPeerCertificate(*serverCertificateFormat, *serverCertificate);
+ if (status != OK) {
+ ALOGE("Cannot add trusted server certificate: %s", statusToString(status).c_str());
+ return nullptr;
+ }
+ }
+ return sp<RpcSession>::make(std::move(ctx));
}
void RpcSession::setMaxThreads(size_t threads) {
@@ -155,12 +169,7 @@
return -savedErrno;
}
- auto ctx = mRpcTransportCtxFactory->newClientCtx();
- if (ctx == nullptr) {
- ALOGE("Unable to create RpcTransportCtx for null debugging client");
- return NO_MEMORY;
- }
- auto server = ctx->newTransport(std::move(serverFd), mShutdownTrigger.get());
+ auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
if (server == nullptr) {
ALOGE("Unable to set up RpcTransport");
return UNKNOWN_ERROR;
@@ -484,37 +493,39 @@
}
if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
- if (errno == ECONNRESET) {
+ int connErrno = errno;
+ if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
+ // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
+ // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
+ status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
+ if (pollStatus != OK) {
+ ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
+ statusToString(pollStatus).c_str());
+ return pollStatus;
+ }
+ // Set connErrno to the errno that connect() would have set if the fd were blocking.
+ socklen_t connErrnoLen = sizeof(connErrno);
+ int ret =
+ getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
+ if (ret == -1) {
+ int savedErrno = errno;
+ ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
+ "(Original error from connect() is: %s)",
+ strerror(savedErrno), strerror(connErrno));
+ return -savedErrno;
+ }
+ // Retrieved the real connErrno as if connect() was called with a blocking socket
+ // fd. Continue checking connErrno.
+ }
+ if (connErrno == ECONNRESET) {
ALOGW("Connection reset on %s", addr.toString().c_str());
continue;
}
- if (errno != EAGAIN && errno != EINPROGRESS) {
- int savedErrno = errno;
+ // connErrno could be zero if getsockopt determines so. Hence zero-check again.
+ if (connErrno != 0) {
ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
- strerror(savedErrno));
- return -savedErrno;
- }
- // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
- // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
- status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
- if (pollStatus != OK) {
- ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
- statusToString(pollStatus).c_str());
- return pollStatus;
- }
- int soError;
- socklen_t soErrorLen = sizeof(soError);
- int ret = getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &soError, &soErrorLen);
- if (ret == -1) {
- int savedErrno = errno;
- ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s",
- strerror(savedErrno));
- return -savedErrno;
- }
- if (soError != 0) {
- ALOGE("After connect(), getsockopt() returns error for socket at %s: %s",
- addr.toString().c_str(), strerror(soError));
- return -soError;
+ strerror(connErrno));
+ return -connErrno;
}
}
LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
@@ -529,15 +540,9 @@
status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
bool incoming) {
LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
- auto ctx = mRpcTransportCtxFactory->newClientCtx();
- if (ctx == nullptr) {
- ALOGE("Unable to create client RpcTransportCtx with %s sockets",
- mRpcTransportCtxFactory->toCString());
- return NO_MEMORY;
- }
- auto server = ctx->newTransport(std::move(fd), mShutdownTrigger.get());
+ auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
if (server == nullptr) {
- ALOGE("Unable to set up RpcTransport in %s context", mRpcTransportCtxFactory->toCString());
+ ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
return UNKNOWN_ERROR;
}
@@ -692,6 +697,10 @@
return false;
}
+std::string RpcSession::getCertificate(CertificateFormat format) {
+ return mCtx->getCertificate(format);
+}
+
status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
ExclusiveConnection* connection) {
connection->mSession = session;
diff --git a/libs/binder/RpcTransportRaw.cpp b/libs/binder/RpcTransportRaw.cpp
index d77fc52..930df12 100644
--- a/libs/binder/RpcTransportRaw.cpp
+++ b/libs/binder/RpcTransportRaw.cpp
@@ -111,7 +111,10 @@
std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd, FdTrigger*) const {
return std::make_unique<RpcTransportRaw>(std::move(fd));
}
+ std::string getCertificate(CertificateFormat) const override { return {}; }
+ status_t addTrustedPeerCertificate(CertificateFormat, std::string_view) override { return OK; }
};
+
} // namespace
std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryRaw::newServerCtx() const {
diff --git a/libs/binder/RpcTransportTls.cpp b/libs/binder/RpcTransportTls.cpp
index a102913..e6cb04e 100644
--- a/libs/binder/RpcTransportTls.cpp
+++ b/libs/binder/RpcTransportTls.cpp
@@ -166,6 +166,34 @@
}
}
+// Helper class to ErrorQueue::toString
+class ErrorQueueString {
+public:
+ static std::string toString() {
+ ErrorQueueString thiz;
+ ERR_print_errors_cb(staticCallback, &thiz);
+ return thiz.mSs.str();
+ }
+
+private:
+ static int staticCallback(const char* str, size_t len, void* ctx) {
+ return reinterpret_cast<ErrorQueueString*>(ctx)->callback(str, len);
+ }
+ int callback(const char* str, size_t len) {
+ if (len == 0) return 1; // continue
+ // ERR_print_errors_cb place a new line at the end, but it doesn't say so in the API.
+ if (str[len - 1] == '\n') len -= 1;
+ if (!mIsFirst) {
+ mSs << '\n';
+ }
+ mSs << std::string_view(str, len);
+ mIsFirst = false;
+ return 1; // continue
+ }
+ std::stringstream mSs;
+ bool mIsFirst = true;
+};
+
// Handles libssl's error queue.
//
// Call into any of its member functions to ensure the error queue is properly handled or cleared.
@@ -182,17 +210,10 @@
// Stores the error queue in |ssl| into a string, then clears the error queue.
std::string toString() {
- std::stringstream ss;
- ERR_print_errors_cb(
- [](const char* str, size_t len, void* ctx) {
- auto ss = (std::stringstream*)ctx;
- (*ss) << std::string_view(str, len) << "\n";
- return 1; // continue
- },
- &ss);
+ auto ret = ErrorQueueString::toString();
// Though ERR_print_errors_cb should have cleared it, it is okay to clear again.
clear();
- return ss.str();
+ return ret;
}
// |sslError| should be from Ssl::getError().
@@ -428,65 +449,46 @@
}
}
-class RpcTransportCtxTlsServer : public RpcTransportCtx {
+class RpcTransportCtxTls : public RpcTransportCtx {
public:
- static std::unique_ptr<RpcTransportCtxTlsServer> create();
- std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd acceptedFd,
+ template <typename Impl,
+ typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>>
+ static std::unique_ptr<RpcTransportCtxTls> create();
+ std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
FdTrigger* fdTrigger) const override;
+ std::string getCertificate(CertificateFormat) const override;
+ status_t addTrustedPeerCertificate(CertificateFormat, std::string_view cert) override;
-private:
+protected:
+ virtual void preHandshake(Ssl* ssl) const = 0;
bssl::UniquePtr<SSL_CTX> mCtx;
};
-std::unique_ptr<RpcTransportCtxTlsServer> RpcTransportCtxTlsServer::create() {
+std::string RpcTransportCtxTls::getCertificate(CertificateFormat) const {
+ // TODO(b/195166979): return certificate here
+ return {};
+}
+
+status_t RpcTransportCtxTls::addTrustedPeerCertificate(CertificateFormat, std::string_view) {
+ // TODO(b/195166979): set certificate here
+ return OK;
+}
+
+// Common implementation for creating server and client contexts. The child class, |Impl|, is
+// provided as a template argument so that this function can initialize an |Impl| object.
+template <typename Impl, typename>
+std::unique_ptr<RpcTransportCtxTls> RpcTransportCtxTls::create() {
bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
TEST_AND_RETURN(nullptr, ctx != nullptr);
- // Server use self-signing cert
auto evp_pkey = makeKeyPairForSelfSignedCert();
TEST_AND_RETURN(nullptr, evp_pkey != nullptr);
auto cert = makeSelfSignedCert(evp_pkey.get(), kCertValidDays);
TEST_AND_RETURN(nullptr, cert != nullptr);
TEST_AND_RETURN(nullptr, SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get()));
TEST_AND_RETURN(nullptr, SSL_CTX_use_certificate(ctx.get(), cert.get()));
- // Require at least TLS 1.3
- TEST_AND_RETURN(nullptr, SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
- if constexpr (SHOULD_LOG_TLS_DETAIL) { // NOLINT
- SSL_CTX_set_info_callback(ctx.get(), sslDebugLog);
- }
-
- auto rpcTransportTlsServerCtx = std::make_unique<RpcTransportCtxTlsServer>();
- rpcTransportTlsServerCtx->mCtx = std::move(ctx);
- return rpcTransportTlsServerCtx;
-}
-
-std::unique_ptr<RpcTransport> RpcTransportCtxTlsServer::newTransport(
- android::base::unique_fd acceptedFd, FdTrigger* fdTrigger) const {
- bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
- TEST_AND_RETURN(nullptr, ssl != nullptr);
- Ssl wrapped(std::move(ssl));
-
- wrapped.call(SSL_set_accept_state).errorQueue.clear();
- TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, acceptedFd, fdTrigger));
- return std::make_unique<RpcTransportTls>(std::move(acceptedFd), std::move(wrapped));
-}
-
-class RpcTransportCtxTlsClient : public RpcTransportCtx {
-public:
- static std::unique_ptr<RpcTransportCtxTlsClient> create();
- std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd connectedFd,
- FdTrigger* fdTrigger) const override;
-
-private:
- bssl::UniquePtr<SSL_CTX> mCtx;
-};
-
-std::unique_ptr<RpcTransportCtxTlsClient> RpcTransportCtxTlsClient::create() {
- bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
- TEST_AND_RETURN(nullptr, ctx != nullptr);
-
- // TODO(b/195166979): server should send certificate in a different channel, and client
+ // TODO(b/195166979): peer should send certificate in a different channel, and this class
// should verify it here.
SSL_CTX_set_custom_verify(ctx.get(), SSL_VERIFY_PEER,
[](SSL*, uint8_t*) -> ssl_verify_result_t { return ssl_verify_ok; });
@@ -498,30 +500,44 @@
SSL_CTX_set_info_callback(ctx.get(), sslDebugLog);
}
- auto rpcTransportTlsClientCtx = std::make_unique<RpcTransportCtxTlsClient>();
- rpcTransportTlsClientCtx->mCtx = std::move(ctx);
- return rpcTransportTlsClientCtx;
+ auto ret = std::make_unique<Impl>();
+ ret->mCtx = std::move(ctx);
+ return ret;
}
-std::unique_ptr<RpcTransport> RpcTransportCtxTlsClient::newTransport(
- android::base::unique_fd connectedFd, FdTrigger* fdTrigger) const {
+std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd,
+ FdTrigger* fdTrigger) const {
bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
TEST_AND_RETURN(nullptr, ssl != nullptr);
Ssl wrapped(std::move(ssl));
- wrapped.call(SSL_set_connect_state).errorQueue.clear();
- TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, connectedFd, fdTrigger));
- return std::make_unique<RpcTransportTls>(std::move(connectedFd), std::move(wrapped));
+ preHandshake(&wrapped);
+ TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger));
+ return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped));
}
+class RpcTransportCtxTlsServer : public RpcTransportCtxTls {
+protected:
+ void preHandshake(Ssl* ssl) const override {
+ ssl->call(SSL_set_accept_state).errorQueue.clear();
+ }
+};
+
+class RpcTransportCtxTlsClient : public RpcTransportCtxTls {
+protected:
+ void preHandshake(Ssl* ssl) const override {
+ ssl->call(SSL_set_connect_state).errorQueue.clear();
+ }
+};
+
} // namespace
std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newServerCtx() const {
- return android::RpcTransportCtxTlsServer::create();
+ return android::RpcTransportCtxTls::create<RpcTransportCtxTlsServer>();
}
std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newClientCtx() const {
- return android::RpcTransportCtxTlsClient::create();
+ return android::RpcTransportCtxTls::create<RpcTransportCtxTlsClient>();
}
const char* RpcTransportCtxFactoryTls::toCString() const {
diff --git a/libs/binder/RpcWireFormat.h b/libs/binder/RpcWireFormat.h
index 0f8efd2..c73d8c2 100644
--- a/libs/binder/RpcWireFormat.h
+++ b/libs/binder/RpcWireFormat.h
@@ -115,12 +115,12 @@
uint32_t reserved[4];
- uint8_t data[0];
+ uint8_t data[];
};
struct RpcWireReply {
int32_t status; // transact return
- uint8_t data[0];
+ uint8_t data[];
};
#pragma clang diagnostic pop
diff --git a/libs/binder/TEST_MAPPING b/libs/binder/TEST_MAPPING
index 9c5ce67..ebb0d27 100644
--- a/libs/binder/TEST_MAPPING
+++ b/libs/binder/TEST_MAPPING
@@ -34,6 +34,9 @@
"name": "binderStabilityTest"
},
{
+ "name": "binderRpcWireProtocolTest"
+ },
+ {
"name": "binderUtilsHostTest"
},
{
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index bf3e7e0..d0e4e27 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -134,6 +134,17 @@
sp<IBinder> getRootObject();
/**
+ * See RpcTransportCtx::getCertificate
+ */
+ std::string getCertificate(CertificateFormat);
+
+ /**
+ * See RpcTransportCtx::addTrustedPeerCertificate.
+ * Thread-safe. This is only possible before the server is join()-ing.
+ */
+ status_t addTrustedPeerCertificate(CertificateFormat, std::string_view cert);
+
+ /**
* Runs join() in a background thread. Immediately returns.
*/
void start();
@@ -170,7 +181,7 @@
private:
friend sp<RpcServer>;
- explicit RpcServer(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory);
+ explicit RpcServer(std::unique_ptr<RpcTransportCtx> ctx);
void onSessionAllIncomingThreadsEnded(const sp<RpcSession>& session) override;
void onSessionIncomingThreadEnded() override;
@@ -178,7 +189,7 @@
static void establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd);
status_t setupSocketServer(const RpcSocketAddress& address);
- const std::unique_ptr<RpcTransportCtxFactory> mRpcTransportCtxFactory;
+ const std::unique_ptr<RpcTransportCtx> mCtx;
bool mAgreedExperimental = false;
size_t mMaxThreads = 1;
std::optional<uint32_t> mProtocolVersion;
@@ -193,7 +204,6 @@
std::map<RpcAddress, sp<RpcSession>> mSessions;
std::unique_ptr<FdTrigger> mShutdownTrigger;
std::condition_variable mShutdownCv;
- std::unique_ptr<RpcTransportCtx> mCtx;
};
} // namespace android
diff --git a/libs/binder/include/binder/RpcSession.h b/libs/binder/include/binder/RpcSession.h
index 6e6eb74..d92af0a 100644
--- a/libs/binder/include/binder/RpcSession.h
+++ b/libs/binder/include/binder/RpcSession.h
@@ -51,8 +51,15 @@
*/
class RpcSession final : public virtual RefBase {
public:
- static sp<RpcSession> make(
- std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory = nullptr);
+ // Create an RpcSession with default configuration (raw sockets).
+ static sp<RpcSession> make();
+
+ // Create an RpcSession with the given configuration. |serverCertificateFormat| and
+ // |serverCertificate| must have values or be nullopt simultaneously. If they have values, set
+ // server certificate.
+ static sp<RpcSession> make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory,
+ std::optional<CertificateFormat> serverCertificateFormat,
+ std::optional<std::string> serverCertificate);
/**
* Set the maximum number of threads allowed to be made (for things like callbacks).
@@ -125,6 +132,11 @@
status_t getRemoteMaxThreads(size_t* maxThreads);
/**
+ * See RpcTransportCtx::getCertificate
+ */
+ std::string getCertificate(CertificateFormat);
+
+ /**
* Shuts down the service.
*
* For client sessions, wait can be true or false. For server sessions,
@@ -159,7 +171,7 @@
friend sp<RpcSession>;
friend RpcServer;
friend RpcState;
- explicit RpcSession(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory);
+ explicit RpcSession(std::unique_ptr<RpcTransportCtx> ctx);
class EventListener : public virtual RefBase {
public:
@@ -259,7 +271,7 @@
bool mReentrant = false;
};
- const std::unique_ptr<RpcTransportCtxFactory> mRpcTransportCtxFactory;
+ const std::unique_ptr<RpcTransportCtx> mCtx;
// On the other side of a session, for each of mOutgoingConnections here, there should
// be one of mIncomingConnections on the other side (and vice versa).
diff --git a/libs/binder/include/binder/RpcTransport.h b/libs/binder/include/binder/RpcTransport.h
index 1b69519..8d08b34 100644
--- a/libs/binder/include/binder/RpcTransport.h
+++ b/libs/binder/include/binder/RpcTransport.h
@@ -29,7 +29,13 @@
class FdTrigger;
+enum class CertificateFormat {
+ PEM,
+ // TODO(b/195166979): support other formats, e.g. DER
+};
+
// Represents a socket connection.
+// No thread-safety is guaranteed for these APIs.
class RpcTransport {
public:
virtual ~RpcTransport() = default;
@@ -53,22 +59,43 @@
};
// Represents the context that generates the socket connection.
+// All APIs are thread-safe. See RpcTransportCtxRaw and RpcTransportCtxTls for details.
class RpcTransportCtx {
public:
virtual ~RpcTransportCtx() = default;
// Create a new RpcTransport object.
//
- // Implemenion details: for TLS, this function may incur I/O. |fdTrigger| may be used
+ // Implementation details: for TLS, this function may incur I/O. |fdTrigger| may be used
// to interrupt I/O. This function blocks until handshake is finished.
[[nodiscard]] virtual std::unique_ptr<RpcTransport> newTransport(
android::base::unique_fd fd, FdTrigger *fdTrigger) const = 0;
+ // Return the preconfigured certificate of this context.
+ //
+ // Implementation details:
+ // - For raw sockets, this always returns empty string.
+ // - For TLS, this returns the certificate. See RpcTransportTls for details.
+ [[nodiscard]] virtual std::string getCertificate(CertificateFormat format) const = 0;
+
+ // Add a trusted peer certificate. Peers presenting this certificate are accepted.
+ //
+ // Caller must ensure that newTransport() are called after all trusted peer certificates
+ // are added. Otherwise, RpcTransport-s created before may not trust peer certificates
+ // added later.
+ //
+ // Implementation details:
+ // - For raw sockets, this always returns OK.
+ // - For TLS, this adds trusted peer certificate. See RpcTransportTls for details.
+ [[nodiscard]] virtual status_t addTrustedPeerCertificate(CertificateFormat format,
+ std::string_view cert) = 0;
+
protected:
RpcTransportCtx() = default;
};
// A factory class that generates RpcTransportCtx.
+// All APIs are thread-safe.
class RpcTransportCtxFactory {
public:
virtual ~RpcTransportCtxFactory() = default;
diff --git a/libs/binder/ndk/ibinder.cpp b/libs/binder/ndk/ibinder.cpp
index 717beec..f88896f 100644
--- a/libs/binder/ndk/ibinder.cpp
+++ b/libs/binder/ndk/ibinder.cpp
@@ -172,7 +172,7 @@
status_t ABBinder::onTransact(transaction_code_t code, const Parcel& data, Parcel* reply,
binder_flags_t flags) {
if (isUserCommand(code)) {
- if (!data.checkInterface(this)) {
+ if (getClass()->writeHeader && !data.checkInterface(this)) {
return STATUS_BAD_TYPE;
}
@@ -354,6 +354,12 @@
clazz->onDump = onDump;
}
+void AIBinder_Class_disableInterfaceTokenHeader(AIBinder_Class* clazz) {
+ CHECK(clazz != nullptr) << "disableInterfaceTokenHeader requires non-null clazz";
+
+ clazz->writeHeader = false;
+}
+
void AIBinder_Class_setHandleShellCommand(AIBinder_Class* clazz,
AIBinder_handleShellCommand handleShellCommand) {
CHECK(clazz != nullptr) << "setHandleShellCommand requires non-null clazz";
@@ -606,7 +612,10 @@
*in = new AParcel(binder);
(*in)->get()->markForBinder(binder->getBinder());
- status_t status = (*in)->get()->writeInterfaceToken(clazz->getInterfaceDescriptor());
+ status_t status = android::OK;
+ if (clazz->writeHeader) {
+ status = (*in)->get()->writeInterfaceToken(clazz->getInterfaceDescriptor());
+ }
binder_status_t ret = PruneStatusT(status);
if (ret != STATUS_OK) {
diff --git a/libs/binder/ndk/ibinder_internal.h b/libs/binder/ndk/ibinder_internal.h
index 3b515ab..3cb95ea 100644
--- a/libs/binder/ndk/ibinder_internal.h
+++ b/libs/binder/ndk/ibinder_internal.h
@@ -116,6 +116,9 @@
const ::android::String16& getInterfaceDescriptor() const { return mWideInterfaceDescriptor; }
const char* getInterfaceDescriptorUtf8() const { return mInterfaceDescriptor.c_str(); }
+ // whether a transaction header should be written
+ bool writeHeader = true;
+
// required to be non-null, implemented for every class
const AIBinder_Class_onCreate onCreate = nullptr;
const AIBinder_Class_onDestroy onDestroy = nullptr;
diff --git a/libs/binder/ndk/include_ndk/android/binder_ibinder.h b/libs/binder/ndk/include_ndk/android/binder_ibinder.h
index 78f2d3a..c82df83 100644
--- a/libs/binder/ndk/include_ndk/android/binder_ibinder.h
+++ b/libs/binder/ndk/include_ndk/android/binder_ibinder.h
@@ -219,6 +219,21 @@
void AIBinder_Class_setOnDump(AIBinder_Class* clazz, AIBinder_onDump onDump) __INTRODUCED_IN(29);
/**
+ * This tells users of this class not to use a transaction header. By default, libbinder_ndk users
+ * read/write transaction headers implicitly (in the SDK, this must be manually written by
+ * android.os.Parcel#writeInterfaceToken, and it is read/checked with
+ * android.os.Parcel#enforceInterface). This method is provided in order to talk to legacy code
+ * which does not write an interface token. When this is disabled, type safety is reduced, so you
+ * must have a separate way of determining the binder you are talking to is the right type. Must
+ * be called before any instance of the class is created.
+ *
+ * Available since API level 32.
+ *
+ * \param clazz class to disable interface header on.
+ */
+void AIBinder_Class_disableInterfaceTokenHeader(AIBinder_Class* clazz) __INTRODUCED_IN(32);
+
+/**
* Creates a new binder object of the appropriate class.
*
* Ownership of args is passed to this object. The lifecycle is implemented with AIBinder_incStrong
diff --git a/libs/binder/ndk/libbinder_ndk.map.txt b/libs/binder/ndk/libbinder_ndk.map.txt
index 685ebb5..1975bdc 100644
--- a/libs/binder/ndk/libbinder_ndk.map.txt
+++ b/libs/binder/ndk/libbinder_ndk.map.txt
@@ -141,6 +141,11 @@
AParcel_reset;
};
+LIBBINDER_NDK32 { # introduced=32
+ global:
+ AIBinder_Class_disableInterfaceTokenHeader;
+};
+
LIBBINDER_NDK_PLATFORM {
global:
AParcel_getAllowFds;
diff --git a/libs/binder/rust/src/proxy.rs b/libs/binder/rust/src/proxy.rs
index cdd7c08..b03ed49 100644
--- a/libs/binder/rust/src/proxy.rs
+++ b/libs/binder/rust/src/proxy.rs
@@ -38,7 +38,7 @@
///
/// This struct encapsulates the generic C++ `sp<IBinder>` class. This wrapper
/// is untyped; typed interface access is implemented by the AIDL compiler.
-pub struct SpIBinder(*mut sys::AIBinder);
+pub struct SpIBinder(ptr::NonNull<sys::AIBinder>);
impl fmt::Debug for SpIBinder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -74,7 +74,7 @@
/// to an `AIBinder`, which will remain valid for the entire lifetime of the
/// `SpIBinder` (we keep a strong reference, and only decrement on drop).
pub(crate) unsafe fn from_raw(ptr: *mut sys::AIBinder) -> Option<Self> {
- ptr.as_mut().map(|p| Self(p))
+ ptr::NonNull::new(ptr).map(Self)
}
/// Extract a raw `AIBinder` pointer from this wrapper.
@@ -88,7 +88,7 @@
/// The SpIBinder object retains ownership of the AIBinder and the caller
/// should not attempt to free the returned pointer.
pub unsafe fn as_raw(&self) -> *mut sys::AIBinder {
- self.0
+ self.0.as_ptr()
}
/// Return true if this binder object is hosted in a different process than
@@ -176,13 +176,13 @@
// Safety: SpIBinder always holds a valid `AIBinder` pointer, so
// this pointer is always safe to pass to `AIBinder_lt` (null is
// also safe to pass to this function, but we should never do that).
- sys::AIBinder_lt(self.0, other.0)
+ sys::AIBinder_lt(self.0.as_ptr(), other.0.as_ptr())
};
let greater_than = unsafe {
// Safety: SpIBinder always holds a valid `AIBinder` pointer, so
// this pointer is always safe to pass to `AIBinder_lt` (null is
// also safe to pass to this function, but we should never do that).
- sys::AIBinder_lt(other.0, self.0)
+ sys::AIBinder_lt(other.0.as_ptr(), self.0.as_ptr())
};
if !less_than && !greater_than {
Ordering::Equal
@@ -202,7 +202,7 @@
impl PartialEq for SpIBinder {
fn eq(&self, other: &Self) -> bool {
- ptr::eq(self.0, other.0)
+ ptr::eq(self.0.as_ptr(), other.0.as_ptr())
}
}
@@ -214,7 +214,7 @@
// Safety: Cloning a strong reference must increment the reference
// count. We are guaranteed by the `SpIBinder` constructor
// invariants that `self.0` is always a valid `AIBinder` pointer.
- sys::AIBinder_incStrong(self.0);
+ sys::AIBinder_incStrong(self.0.as_ptr());
}
Self(self.0)
}
@@ -443,7 +443,7 @@
///
/// This struct encapsulates the generic C++ `wp<IBinder>` class. This wrapper
/// is untyped; typed interface access is implemented by the AIDL compiler.
-pub struct WpIBinder(*mut sys::AIBinder_Weak);
+pub struct WpIBinder(ptr::NonNull<sys::AIBinder_Weak>);
impl fmt::Debug for WpIBinder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -470,8 +470,7 @@
// valid pointer to an `AIBinder`.
sys::AIBinder_Weak_new(binder.as_native_mut())
};
- assert!(!ptr.is_null());
- Self(ptr)
+ Self(ptr::NonNull::new(ptr).expect("Unexpected null pointer from AIBinder_Weak_new"))
}
/// Promote this weak reference to a strong reference to the binder object.
@@ -481,7 +480,7 @@
// can pass this pointer to `AIBinder_Weak_promote`. Returns either
// null or an AIBinder owned by the caller, both of which are valid
// to pass to `SpIBinder::from_raw`.
- let ptr = sys::AIBinder_Weak_promote(self.0);
+ let ptr = sys::AIBinder_Weak_promote(self.0.as_ptr());
SpIBinder::from_raw(ptr)
}
}
@@ -496,13 +495,9 @@
//
// We get ownership of the returned pointer, so can construct a new
// WpIBinder object from it.
- sys::AIBinder_Weak_clone(self.0)
+ sys::AIBinder_Weak_clone(self.0.as_ptr())
};
- assert!(
- !ptr.is_null(),
- "Unexpected null pointer from AIBinder_Weak_clone"
- );
- Self(ptr)
+ Self(ptr::NonNull::new(ptr).expect("Unexpected null pointer from AIBinder_Weak_clone"))
}
}
@@ -513,14 +508,14 @@
// so this pointer is always safe to pass to `AIBinder_Weak_lt`
// (null is also safe to pass to this function, but we should never
// do that).
- sys::AIBinder_Weak_lt(self.0, other.0)
+ sys::AIBinder_Weak_lt(self.0.as_ptr(), other.0.as_ptr())
};
let greater_than = unsafe {
// Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
// so this pointer is always safe to pass to `AIBinder_Weak_lt`
// (null is also safe to pass to this function, but we should never
// do that).
- sys::AIBinder_Weak_lt(other.0, self.0)
+ sys::AIBinder_Weak_lt(other.0.as_ptr(), self.0.as_ptr())
};
if !less_than && !greater_than {
Ordering::Equal
@@ -551,7 +546,7 @@
unsafe {
// Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, so we
// know this pointer is safe to pass to `AIBinder_Weak_delete` here.
- sys::AIBinder_Weak_delete(self.0);
+ sys::AIBinder_Weak_delete(self.0.as_ptr());
}
}
}
@@ -716,10 +711,10 @@
/// `AIBinder`, so we can trivially extract this pointer here.
unsafe impl AsNative<sys::AIBinder> for SpIBinder {
fn as_native(&self) -> *const sys::AIBinder {
- self.0
+ self.0.as_ptr()
}
fn as_native_mut(&mut self) -> *mut sys::AIBinder {
- self.0
+ self.0.as_ptr()
}
}
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index b7ad199..13ea827 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -145,6 +145,7 @@
defaults: [
"binder_test_defaults",
"libbinder_ndk_host_user",
+ "libbinder_tls_shared_deps",
],
srcs: [
@@ -159,6 +160,7 @@
"liblog",
],
static_libs: [
+ "libbinder_tls_static",
"binderRpcTestIface-cpp",
"binderRpcTestIface-ndk",
],
@@ -188,6 +190,33 @@
}
cc_test {
+ name: "binderRpcWireProtocolTest",
+ host_supported: true,
+ target: {
+ darwin: {
+ enabled: false,
+ },
+ android: {
+ test_suites: ["vts"],
+ },
+ },
+ defaults: [
+ "binder_test_defaults",
+ ],
+ srcs: [
+ "binderRpcWireProtocolTest.cpp",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbase",
+ "libutils",
+ "libcutils",
+ "liblog",
+ ],
+ test_suites: ["general-tests"],
+}
+
+cc_test {
name: "binderThroughputTest",
defaults: ["binder_test_defaults"],
srcs: ["binderThroughputTest.cpp"],
diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp
index 15ccae9..7c405d3 100644
--- a/libs/binder/tests/binderRpcTest.cpp
+++ b/libs/binder/tests/binderRpcTest.cpp
@@ -31,6 +31,7 @@
#include <binder/RpcSession.h>
#include <binder/RpcTransport.h>
#include <binder/RpcTransportRaw.h>
+#include <binder/RpcTransportTls.h>
#include <gtest/gtest.h>
#include <chrono>
@@ -54,16 +55,18 @@
RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
const char* kLocalInetAddress = "127.0.0.1";
-enum class RpcSecurity { RAW };
+enum class RpcSecurity { RAW, TLS };
static inline std::vector<RpcSecurity> RpcSecurityValues() {
- return {RpcSecurity::RAW};
+ return {RpcSecurity::RAW, RpcSecurity::TLS};
}
static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(RpcSecurity rpcSecurity) {
switch (rpcSecurity) {
case RpcSecurity::RAW:
return RpcTransportCtxFactoryRaw::make();
+ case RpcSecurity::TLS:
+ return RpcTransportCtxFactoryTls::make();
default:
LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
}
@@ -519,7 +522,8 @@
status_t status;
for (size_t i = 0; i < options.numSessions; i++) {
- sp<RpcSession> session = RpcSession::make(newFactory(rpcSecurity));
+ sp<RpcSession> session =
+ RpcSession::make(newFactory(rpcSecurity), std::nullopt, std::nullopt);
session->setMaxThreads(options.numIncomingConnections);
switch (socketType) {
@@ -1204,7 +1208,8 @@
}
server->start();
- sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
+ sp<RpcSession> session =
+ RpcSession::make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
while (!server->shutdown()) usleep(10000);
ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
diff --git a/libs/binder/tests/binderRpcWireProtocolTest.cpp b/libs/binder/tests/binderRpcWireProtocolTest.cpp
new file mode 100644
index 0000000..46e9630
--- /dev/null
+++ b/libs/binder/tests/binderRpcWireProtocolTest.cpp
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2021 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 <android-base/hex.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+#include <binder/Parcel.h>
+#include <binder/RpcSession.h>
+#include <gtest/gtest.h>
+
+#include "../Debug.h"
+
+namespace android {
+
+static const int32_t kInt32Array[] = {-1, 0, 17};
+static const uint8_t kByteArray[] = {0, 17, 255};
+enum EnumInt8 : int8_t { Int8A, Int8B };
+enum EnumInt32 : int32_t { Int32A, Int32B };
+enum EnumInt64 : int64_t { Int64A, Int64B };
+struct AParcelable : Parcelable {
+ status_t writeToParcel(Parcel* parcel) const { return parcel->writeInt32(37); }
+ status_t readFromParcel(const Parcel*) { return OK; }
+};
+
+// clang-format off
+constexpr size_t kFillFunIndexLineBase = __LINE__ + 2;
+static const std::vector<std::function<void(Parcel* p)>> kFillFuns {
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInterfaceToken(String16(u"tok"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32(-1)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32(0)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32(17)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint32(0)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint32(1)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint32(10003)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64(-1)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64(0)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64(17)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64(0)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64(1)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64(10003)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloat(0.0f)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloat(0.1f)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloat(9.1f)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDouble(0.0)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDouble(0.1)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDouble(9.1)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCString("")); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCString("a")); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCString("baba")); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString8(String8(""))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString8(String8("a"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString8(String8("baba"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16(String16(u""))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16(String16(u"a"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16(String16(u"baba"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeStrongBinder(nullptr)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Array(arraysize(kInt32Array), kInt32Array)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteArray(arraysize(kByteArray), kByteArray)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeBool(true)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeBool(false)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeChar('a')); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeChar('?')); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeChar('\0')); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByte(-128)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByte(0)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByte(127)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::string(""))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::string("a"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::string("abab"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::nullopt)); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::optional<std::string>(""))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::optional<std::string>("a"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8AsUtf16(std::optional<std::string>("abab"))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::optional<std::vector<int8_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::optional<std::vector<int8_t>>({-1, 0, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::vector<int8_t>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::vector<int8_t>({-1, 0, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::optional<std::vector<uint8_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::optional<std::vector<uint8_t>>({0, 1, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::vector<uint8_t>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeByteVector(std::vector<uint8_t>({0, 1, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Vector(std::optional<std::vector<int32_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Vector(std::optional<std::vector<int32_t>>({-1, 0, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Vector(std::vector<int32_t>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Vector(std::vector<int32_t>({-1, 0, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64Vector(std::optional<std::vector<int64_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64Vector(std::optional<std::vector<int64_t>>({-1, 0, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64Vector(std::vector<int64_t>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeInt64Vector(std::vector<int64_t>({-1, 0, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64Vector(std::optional<std::vector<uint64_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64Vector(std::optional<std::vector<uint64_t>>({0, 1, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64Vector(std::vector<uint64_t>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUint64Vector(std::vector<uint64_t>({0, 1, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloatVector(std::optional<std::vector<float>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloatVector(std::optional<std::vector<float>>({0.0f, 0.1f, 9.1f}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloatVector(std::vector<float>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeFloatVector(std::vector<float>({0.0f, 0.1f, 9.1f}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDoubleVector(std::optional<std::vector<double>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDoubleVector(std::optional<std::vector<double>>({0.0, 0.1, 9.1}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDoubleVector(std::vector<double>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeDoubleVector(std::vector<double>({0.0, 0.1, 9.1}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeBoolVector(std::optional<std::vector<bool>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeBoolVector(std::optional<std::vector<bool>>({true, false}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeBoolVector(std::vector<bool>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeBoolVector(std::vector<bool>({true, false}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCharVector(std::optional<std::vector<char16_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCharVector(std::optional<std::vector<char16_t>>({'a', '\0', '?'}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCharVector(std::vector<char16_t>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeCharVector(std::vector<char16_t>({'a', '\0', '?'}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16Vector(std::optional<std::vector<std::optional<String16>>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16Vector(std::optional<std::vector<std::optional<String16>>>({std::nullopt, String16(), String16(u"a")}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16Vector(std::vector<std::optional<String16>>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeString16Vector(std::vector<std::optional<String16>>({std::nullopt, String16(), String16(u"a")}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8VectorAsUtf16Vector(std::optional<std::vector<std::optional<std::string>>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8VectorAsUtf16Vector(std::optional<std::vector<std::optional<std::string>>>({std::nullopt, std::string(), std::string("a")}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8VectorAsUtf16Vector(std::vector<std::optional<std::string>>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeUtf8VectorAsUtf16Vector(std::vector<std::optional<std::string>>({std::nullopt, std::string(), std::string("a")}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeStrongBinderVector(std::optional<std::vector<sp<IBinder>>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeStrongBinderVector(std::optional<std::vector<sp<IBinder>>>({nullptr}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeStrongBinderVector(std::vector<sp<IBinder>>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeStrongBinderVector(std::vector<sp<IBinder>>({nullptr}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::optional<std::vector<EnumInt8>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::optional<std::vector<EnumInt8>>({Int8A, Int8B}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::vector<EnumInt8>({Int8A, Int8B}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::optional<std::vector<EnumInt32>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::optional<std::vector<EnumInt32>>({Int32A, Int32B}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::vector<EnumInt32>({Int32A, Int32B}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::optional<std::vector<EnumInt64>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::optional<std::vector<EnumInt64>>({Int64A, Int64B}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeEnumVector(std::vector<EnumInt64>({Int64A, Int64B}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeParcelableVector(std::optional<std::vector<std::optional<AParcelable>>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeParcelableVector(std::optional<std::vector<std::optional<AParcelable>>>({AParcelable()}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeParcelableVector(std::vector<AParcelable>({AParcelable()}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeNullableParcelable(std::optional<AParcelable>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeNullableParcelable(std::optional<AParcelable>(AParcelable()))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeParcelable(AParcelable())); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeVectorSize(std::vector<int32_t>({0, 1, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeVectorSize(std::vector<AParcelable>({}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeVectorSize(std::optional<std::vector<int32_t>>(std::nullopt))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeVectorSize(std::optional<std::vector<int32_t>>({0, 1, 17}))); },
+ [](Parcel* p) { ASSERT_EQ(OK, p->writeNoException()); },
+};
+// clang-format on
+
+static void setParcelForRpc(Parcel* p, uint32_t version) {
+ auto session = RpcSession::make();
+ CHECK(session->setProtocolVersion(version));
+ CHECK_EQ(OK, session->addNullDebuggingClient());
+ p->markForRpc(session);
+}
+
+static std::string buildRepr(uint32_t version) {
+ std::string result;
+ for (size_t i = 0; i < kFillFuns.size(); i++) {
+ if (i != 0) result += "|";
+ Parcel p;
+ setParcelForRpc(&p, version);
+ kFillFuns[i](&p);
+
+ result += base::HexString(p.data(), p.dataSize());
+ }
+ return result;
+}
+
+static void checkRepr(const std::string& repr, uint32_t version) {
+ const std::string actualRepr = buildRepr(version);
+
+ auto expected = base::Split(repr, "|");
+ ASSERT_EQ(expected.size(), kFillFuns.size());
+
+ auto actual = base::Split(actualRepr, "|");
+ ASSERT_EQ(actual.size(), kFillFuns.size());
+
+ for (size_t i = 0; i < kFillFuns.size(); i++) {
+ EXPECT_EQ(expected[i], actual[i])
+ << "Format mismatch, see " __FILE__ " line " << (kFillFunIndexLineBase + i);
+ }
+
+ // same check as in the loop, but the above error is more clear to debug,
+ // and this error is more clear to be able to update the source file here.
+ EXPECT_EQ(repr, actualRepr);
+}
+
+const std::string kCurrentRepr =
+ "0300000074006f006b000000|ffffffff|00000000|11000000|00000000|01000000|13270000|"
+ "ffffffffffffffff|0000000000000000|1100000000000000|0000000000000000|0100000000000000|"
+ "1327000000000000|00000000|cdcccc3d|9a991141|0000000000000000|9a9999999999b93f|"
+ "3333333333332240|00000000|61000000|6261626100000000|0000000000000000|0100000061000000|"
+ "040000006261626100000000|0000000000000000|0100000061000000|"
+ "04000000620061006200610000000000|0000000000000000|03000000ffffffff0000000011000000|"
+ "030000000011ff00|01000000|00000000|61000000|3f000000|00000000|80ffffff|00000000|7f000000|"
+ "0000000000000000|0100000061000000|04000000610062006100620000000000|ffffffff|"
+ "0000000000000000|0100000061000000|04000000610062006100620000000000|ffffffff|"
+ "03000000ff001100|00000000|03000000ff001100|ffffffff|0300000000011100|00000000|"
+ "0300000000011100|ffffffff|03000000ffffffff0000000011000000|00000000|"
+ "03000000ffffffff0000000011000000|ffffffff|"
+ "03000000ffffffffffffffff00000000000000001100000000000000|00000000|"
+ "03000000ffffffffffffffff00000000000000001100000000000000|ffffffff|"
+ "03000000000000000000000001000000000000001100000000000000|00000000|"
+ "03000000000000000000000001000000000000001100000000000000|ffffffff|"
+ "0300000000000000cdcccc3d9a991141|00000000|0300000000000000cdcccc3d9a991141|ffffffff|"
+ "0300000000000000000000009a9999999999b93f3333333333332240|00000000|"
+ "0300000000000000000000009a9999999999b93f3333333333332240|ffffffff|"
+ "020000000100000000000000|00000000|020000000100000000000000|ffffffff|"
+ "0300000061000000000000003f000000|00000000|0300000061000000000000003f000000|ffffffff|"
+ "03000000ffffffff00000000000000000100000061000000|00000000|"
+ "03000000ffffffff00000000000000000100000061000000|ffffffff|"
+ "03000000ffffffff00000000000000000100000061000000|00000000|"
+ "03000000ffffffff00000000000000000100000061000000|ffffffff|010000000000000000000000|"
+ "00000000|010000000000000000000000|ffffffff|0200000000010000|0200000000010000|ffffffff|"
+ "020000000000000001000000|020000000000000001000000|ffffffff|"
+ "0200000000000000000000000100000000000000|0200000000000000000000000100000000000000|"
+ "ffffffff|010000000100000025000000|010000000100000025000000|00000000|0100000025000000|"
+ "0100000025000000|03000000|00000000|ffffffff|03000000|00000000";
+
+TEST(RpcWire, CurrentVersion) {
+ checkRepr(kCurrentRepr, RPC_WIRE_PROTOCOL_VERSION);
+}
+
+static_assert(RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL,
+ "you better update this test!");
+
+TEST(RpcWire, ReleaseBranchHasFrozenRpcWireProtocol) {
+ if (RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
+ EXPECT_FALSE(base::GetProperty("ro.build.version.codename", "") == "REL")
+ << "Binder RPC wire protocol must be frozen on a release branch!";
+ }
+}
+
+TEST(RpcWire, IfNotExperimentalCodeHasNoExperimentalFeatures) {
+ if (RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
+ GTEST_SKIP() << "Version is experimental, so experimental features are okay.";
+ }
+
+ // if we set the wire protocol version to experimental, none of the code
+ // should introduce a difference (if this fails, it means we have features
+ // which are enabled under experimental mode, but we aren't actually using
+ // or testing them!)
+ checkRepr(kCurrentRepr, RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
+}
+
+} // namespace android
diff --git a/libs/binder/tests/parcel_fuzzer/random_parcel.cpp b/libs/binder/tests/parcel_fuzzer/random_parcel.cpp
index 8bf04cc..7fd9f6b 100644
--- a/libs/binder/tests/parcel_fuzzer/random_parcel.cpp
+++ b/libs/binder/tests/parcel_fuzzer/random_parcel.cpp
@@ -36,7 +36,8 @@
void fillRandomParcel(Parcel* p, FuzzedDataProvider&& provider) {
if (provider.ConsumeBool()) {
- auto session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
+ auto session =
+ RpcSession::make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
CHECK_EQ(OK, session->addNullDebuggingClient());
p->markForRpc(session);
fillRandomParcelData(p, std::move(provider));
diff --git a/libs/binder/tests/rpc_fuzzer/Android.bp b/libs/binder/tests/rpc_fuzzer/Android.bp
index 1c75306..9323bd5 100644
--- a/libs/binder/tests/rpc_fuzzer/Android.bp
+++ b/libs/binder/tests/rpc_fuzzer/Android.bp
@@ -22,18 +22,19 @@
"libbase",
"libcutils",
"liblog",
- "libutils",
],
target: {
android: {
shared_libs: [
"libbinder",
+ "libutils",
],
},
host: {
static_libs: [
"libbinder",
+ "libutils",
],
},
},
diff --git a/libs/gui/BLASTBufferQueue.cpp b/libs/gui/BLASTBufferQueue.cpp
index 70f2ae7..e5a2151 100644
--- a/libs/gui/BLASTBufferQueue.cpp
+++ b/libs/gui/BLASTBufferQueue.cpp
@@ -118,12 +118,12 @@
}
void BLASTBufferItemConsumer::setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) {
- Mutex::Autolock lock(mMutex);
+ std::scoped_lock lock(mBufferQueueMutex);
mBLASTBufferQueue = blastbufferqueue;
}
void BLASTBufferItemConsumer::onSidebandStreamChanged() {
- Mutex::Autolock lock(mMutex);
+ std::scoped_lock lock(mBufferQueueMutex);
if (mBLASTBufferQueue != nullptr) {
sp<NativeHandle> stream = getSidebandStream();
mBLASTBufferQueue->setSidebandStream(stream);
diff --git a/libs/gui/include/gui/BLASTBufferQueue.h b/libs/gui/include/gui/BLASTBufferQueue.h
index ea9b1c6..6c5b2aa 100644
--- a/libs/gui/include/gui/BLASTBufferQueue.h
+++ b/libs/gui/include/gui/BLASTBufferQueue.h
@@ -62,11 +62,12 @@
uint64_t mCurrentFrameNumber = 0;
Mutex mMutex;
+ std::mutex mBufferQueueMutex;
ConsumerFrameEventHistory mFrameEventHistory GUARDED_BY(mMutex);
std::queue<uint64_t> mDisconnectEvents GUARDED_BY(mMutex);
bool mCurrentlyConnected GUARDED_BY(mMutex);
bool mPreviouslyConnected GUARDED_BY(mMutex);
- BLASTBufferQueue* mBLASTBufferQueue GUARDED_BY(mMutex);
+ BLASTBufferQueue* mBLASTBufferQueue GUARDED_BY(mBufferQueueMutex);
};
class BLASTBufferQueue
diff --git a/libs/renderengine/skia/SkiaGLRenderEngine.cpp b/libs/renderengine/skia/SkiaGLRenderEngine.cpp
index 052c61f..cb686a6 100644
--- a/libs/renderengine/skia/SkiaGLRenderEngine.cpp
+++ b/libs/renderengine/skia/SkiaGLRenderEngine.cpp
@@ -424,14 +424,28 @@
return fenceFd;
}
-bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
+void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
+ if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
+ ATRACE_NAME("SkiaGLRenderEngine::waitFence");
+ sync_wait(fenceFd.get(), -1);
+ }
+}
+
+bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
!gl::GLExtensions::getInstance().hasWaitSync()) {
return false;
}
+ // Duplicate the fence for passing to eglCreateSyncKHR.
+ base::unique_fd fenceDup(dup(fenceFd.get()));
+ if (fenceDup.get() < 0) {
+ ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
+ return false;
+ }
+
// release the fd and transfer the ownership to EGLSync
- EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
+ EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
if (sync == EGL_NO_SYNC_KHR) {
ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
@@ -727,14 +741,6 @@
return;
}
- if (bufferFence.get() >= 0) {
- // Duplicate the fence for passing to waitFence.
- base::unique_fd bufferFenceDup(dup(bufferFence.get()));
- if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
- ATRACE_NAME("Waiting before draw");
- sync_wait(bufferFence.get(), -1);
- }
- }
if (buffer == nullptr) {
ALOGE("No output buffer provided. Aborting GPU composition.");
resultPromise->set_value({BAD_VALUE, base::unique_fd()});
@@ -760,6 +766,9 @@
true, mTextureCleanupMgr);
}
+ // wait on the buffer to be ready to use prior to using it
+ waitFence(bufferFence);
+
const ui::Dataspace dstDataspace =
mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
@@ -995,6 +1004,12 @@
false, mTextureCleanupMgr);
}
+ // if the layer's buffer has a fence, then we must must respect the fence prior to using
+ // the buffer.
+ if (layer->source.buffer.fence != nullptr) {
+ waitFence(layer->source.buffer.fence->get());
+ }
+
// isOpaque means we need to ignore the alpha in the image,
// replacing it with the alpha specified by the LayerSettings. See
// https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
diff --git a/libs/renderengine/skia/SkiaGLRenderEngine.h b/libs/renderengine/skia/SkiaGLRenderEngine.h
index 0b46705..e010c35 100644
--- a/libs/renderengine/skia/SkiaGLRenderEngine.h
+++ b/libs/renderengine/skia/SkiaGLRenderEngine.h
@@ -99,7 +99,10 @@
inline GrDirectContext* getActiveGrContext() const;
base::unique_fd flush();
- bool waitFence(base::unique_fd fenceFd);
+ // waitFence attempts to wait in the GPU, and if unable to waits on the CPU instead.
+ void waitFence(base::borrowed_fd fenceFd);
+ bool waitGpuFence(base::borrowed_fd fenceFd);
+
void initCanvas(SkCanvas* canvas, const DisplaySettings& display);
void drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
const ShadowSettings& shadowSettings);
diff --git a/libs/renderengine/threaded/RenderEngineThreaded.cpp b/libs/renderengine/threaded/RenderEngineThreaded.cpp
index 9a8201f..a549672 100644
--- a/libs/renderengine/threaded/RenderEngineThreaded.cpp
+++ b/libs/renderengine/threaded/RenderEngineThreaded.cpp
@@ -292,7 +292,7 @@
{
std::lock_guard lock(mThreadMutex);
mFunctionCalls.push([=](renderengine::RenderEngine& instance) {
- ATRACE_NAME("REThreaded::unmapExternalTextureBuffer");
+ ATRACE_NAME("REThreaded::cleanupPostRender");
instance.cleanupPostRender();
});
}
diff --git a/services/inputflinger/reader/EventHub.cpp b/services/inputflinger/reader/EventHub.cpp
index 68d5e7c..0f0ad0a 100644
--- a/services/inputflinger/reader/EventHub.cpp
+++ b/services/inputflinger/reader/EventHub.cpp
@@ -1209,6 +1209,15 @@
return false;
}
+bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
+ std::scoped_lock _l(mLock);
+ Device* device = getDeviceLocked(deviceId);
+ if (device != nullptr) {
+ return device->hasKeycodeLocked(keyCode);
+ }
+ return false;
+}
+
bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
std::scoped_lock _l(mLock);
Device* device = getDeviceLocked(deviceId);
diff --git a/services/inputflinger/reader/InputDevice.cpp b/services/inputflinger/reader/InputDevice.cpp
index 1e9ec54..36344b5 100644
--- a/services/inputflinger/reader/InputDevice.cpp
+++ b/services/inputflinger/reader/InputDevice.cpp
@@ -559,7 +559,13 @@
}
void InputDevice::updateMetaState(int32_t keyCode) {
- for_each_mapper([keyCode](InputMapper& mapper) { mapper.updateMetaState(keyCode); });
+ first_in_mappers<bool>([keyCode](InputMapper& mapper) {
+ if (sourcesMatchMask(mapper.getSources(), AINPUT_SOURCE_KEYBOARD) &&
+ mapper.updateMetaState(keyCode)) {
+ return std::make_optional(true);
+ }
+ return std::optional<bool>();
+ });
}
void InputDevice::bumpGeneration() {
diff --git a/services/inputflinger/reader/InputReader.cpp b/services/inputflinger/reader/InputReader.cpp
index 10c04f6..e71a9e9 100644
--- a/services/inputflinger/reader/InputReader.cpp
+++ b/services/inputflinger/reader/InputReader.cpp
@@ -555,6 +555,7 @@
}
if (device->isIgnored()) {
+ ALOGW("Ignoring toggleCapsLock for ignored deviceId %" PRId32 ".", deviceId);
return;
}
diff --git a/services/inputflinger/reader/include/EventHub.h b/services/inputflinger/reader/include/EventHub.h
index 3c3f88e..7a00bac 100644
--- a/services/inputflinger/reader/include/EventHub.h
+++ b/services/inputflinger/reader/include/EventHub.h
@@ -312,6 +312,7 @@
uint8_t* outFlags) const = 0;
virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0;
+ virtual bool hasKeyCode(int32_t deviceId, int32_t keyCode) const = 0;
/* LED related functions expect Android LED constants, not scan codes or HID usages */
virtual bool hasLed(int32_t deviceId, int32_t led) const = 0;
@@ -489,6 +490,7 @@
std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) override final;
bool hasScanCode(int32_t deviceId, int32_t scanCode) const override final;
+ bool hasKeyCode(int32_t deviceId, int32_t keyCode) const override final;
bool hasLed(int32_t deviceId, int32_t led) const override final;
void setLedState(int32_t deviceId, int32_t led, bool on) override final;
diff --git a/services/inputflinger/reader/include/InputDevice.h b/services/inputflinger/reader/include/InputDevice.h
index f32472d..518aaa0 100644
--- a/services/inputflinger/reader/include/InputDevice.h
+++ b/services/inputflinger/reader/include/InputDevice.h
@@ -323,6 +323,7 @@
inline bool hasScanCode(int32_t scanCode) const {
return mEventHub->hasScanCode(mId, scanCode);
}
+ inline bool hasKeyCode(int32_t keyCode) const { return mEventHub->hasKeyCode(mId, keyCode); }
inline bool hasLed(int32_t led) const { return mEventHub->hasLed(mId, led); }
inline void setLedState(int32_t led, bool on) { return mEventHub->setLedState(mId, led, on); }
inline void getVirtualKeyDefinitions(std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
diff --git a/services/inputflinger/reader/mapper/InputMapper.cpp b/services/inputflinger/reader/mapper/InputMapper.cpp
index df1acd4..b9aef54 100644
--- a/services/inputflinger/reader/mapper/InputMapper.cpp
+++ b/services/inputflinger/reader/mapper/InputMapper.cpp
@@ -84,7 +84,9 @@
return 0;
}
-void InputMapper::updateMetaState(int32_t keyCode) {}
+bool InputMapper::updateMetaState(int32_t keyCode) {
+ return false;
+}
void InputMapper::updateExternalStylusState(const StylusState& state) {}
diff --git a/services/inputflinger/reader/mapper/InputMapper.h b/services/inputflinger/reader/mapper/InputMapper.h
index 15cff1c..d9adc0f 100644
--- a/services/inputflinger/reader/mapper/InputMapper.h
+++ b/services/inputflinger/reader/mapper/InputMapper.h
@@ -83,7 +83,11 @@
virtual std::optional<int32_t> getLightPlayerId(int32_t lightId) { return std::nullopt; }
virtual int32_t getMetaState();
- virtual void updateMetaState(int32_t keyCode);
+ /**
+ * Process the meta key and update the global meta state when changed.
+ * Return true if the meta key could be handled by the InputMapper.
+ */
+ virtual bool updateMetaState(int32_t keyCode);
virtual void updateExternalStylusState(const StylusState& state);
diff --git a/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp b/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
index 104d087..52af38d 100644
--- a/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
@@ -384,8 +384,13 @@
return mMetaState;
}
-void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
+bool KeyboardInputMapper::updateMetaState(int32_t keyCode) {
+ if (!android::isMetaKey(keyCode) || !getDeviceContext().hasKeyCode(keyCode)) {
+ return false;
+ }
+
updateMetaStateIfNeeded(keyCode, false);
+ return true;
}
bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
diff --git a/services/inputflinger/reader/mapper/KeyboardInputMapper.h b/services/inputflinger/reader/mapper/KeyboardInputMapper.h
index ca41712..fc92320 100644
--- a/services/inputflinger/reader/mapper/KeyboardInputMapper.h
+++ b/services/inputflinger/reader/mapper/KeyboardInputMapper.h
@@ -40,7 +40,7 @@
const int32_t* keyCodes, uint8_t* outFlags) override;
virtual int32_t getMetaState() override;
- virtual void updateMetaState(int32_t keyCode) override;
+ virtual bool updateMetaState(int32_t keyCode) override;
virtual std::optional<int32_t> getAssociatedDisplayId() override;
virtual void updateLedState(bool reset);
diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp
index 43f14bd..c76ed38 100644
--- a/services/inputflinger/tests/InputReader_test.cpp
+++ b/services/inputflinger/tests/InputReader_test.cpp
@@ -205,7 +205,7 @@
std::condition_variable mDevicesChangedCondition;
InputReaderConfiguration mConfig;
- std::unordered_map<int32_t, std::shared_ptr<FakePointerController>> mPointerControllers;
+ std::shared_ptr<FakePointerController> mPointerController;
std::vector<InputDeviceInfo> mInputDevices GUARDED_BY(mLock);
bool mInputDevicesChanged GUARDED_BY(mLock){false};
std::vector<DisplayViewport> mViewports;
@@ -291,8 +291,8 @@
void removeDisabledDevice(int32_t deviceId) { mConfig.disabledDevices.erase(deviceId); }
- void setPointerController(int32_t deviceId, std::shared_ptr<FakePointerController> controller) {
- mPointerControllers.insert_or_assign(deviceId, std::move(controller));
+ void setPointerController(std::shared_ptr<FakePointerController> controller) {
+ mPointerController = std::move(controller);
}
const InputReaderConfiguration* getReaderConfiguration() const {
@@ -357,8 +357,9 @@
*outConfig = mConfig;
}
- std::shared_ptr<PointerControllerInterface> obtainPointerController(int32_t deviceId) override {
- return mPointerControllers[deviceId];
+ std::shared_ptr<PointerControllerInterface> obtainPointerController(
+ int32_t /*deviceId*/) override {
+ return mPointerController;
}
void notifyInputDevicesChanged(const std::vector<InputDeviceInfo>& inputDevices) override {
@@ -870,6 +871,24 @@
return false;
}
+ bool hasKeyCode(int32_t deviceId, int32_t keyCode) const override {
+ Device* device = getDevice(deviceId);
+ if (!device) {
+ return false;
+ }
+ for (size_t i = 0; i < device->keysByScanCode.size(); i++) {
+ if (keyCode == device->keysByScanCode.valueAt(i).keyCode) {
+ return true;
+ }
+ }
+ for (size_t j = 0; j < device->keysByUsageCode.size(); j++) {
+ if (keyCode == device->keysByUsageCode.valueAt(j).keyCode) {
+ return true;
+ }
+ }
+ return false;
+ }
+
bool hasLed(int32_t deviceId, int32_t led) const override {
Device* device = getDevice(deviceId);
return device && device->leds.indexOfKey(led) >= 0;
@@ -2132,8 +2151,12 @@
sp<FakeInputReaderPolicy> mFakePolicy;
sp<InputReaderInterface> mReader;
+ std::shared_ptr<FakePointerController> mFakePointerController;
+
void SetUp() override {
mFakePolicy = new FakeInputReaderPolicy();
+ mFakePointerController = std::make_shared<FakePointerController>();
+ mFakePolicy->setPointerController(mFakePointerController);
mTestListener = new TestInputListener(2000ms /*eventHappenedTimeout*/,
30ms /*eventDidNotHappenTimeout*/);
@@ -3729,6 +3752,25 @@
mapper2.getMetaState());
}
+TEST_F(KeyboardInputMapperTest, Process_toggleCapsLockState) {
+ mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
+ mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
+ mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
+
+ // Suppose we have two mappers. (DPAD + KEYBOARD)
+ addMapperAndConfigure<KeyboardInputMapper>(AINPUT_SOURCE_DPAD,
+ AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC);
+ KeyboardInputMapper& mapper =
+ addMapperAndConfigure<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
+ AINPUT_KEYBOARD_TYPE_ALPHABETIC);
+ // Initialize metastate to AMETA_NUM_LOCK_ON.
+ ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper.getMetaState());
+ mapper.updateMetaState(AKEYCODE_NUM_LOCK);
+
+ mReader->toggleCapsLockState(DEVICE_ID);
+ ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
+}
+
// --- KeyboardInputMapperTest_ExternalDevice ---
class KeyboardInputMapperTest_ExternalDevice : public InputMapperTest {
@@ -3825,7 +3867,7 @@
InputMapperTest::SetUp();
mFakePointerController = std::make_shared<FakePointerController>();
- mFakePolicy->setPointerController(mDevice->getId(), mFakePointerController);
+ mFakePolicy->setPointerController(mFakePointerController);
}
void testMotionRotation(CursorInputMapper& mapper, int32_t originalX, int32_t originalY,
@@ -7614,7 +7656,7 @@
fakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
fakePointerController->setPosition(100, 200);
fakePointerController->setButtonState(0);
- mFakePolicy->setPointerController(mDevice->getId(), fakePointerController);
+ mFakePolicy->setPointerController(fakePointerController);
mFakePolicy->setDefaultPointerDisplayId(SECONDARY_DISPLAY_ID);
prepareSecondaryDisplay(ViewportType::EXTERNAL);
@@ -7767,8 +7809,7 @@
// Setup PointerController.
std::shared_ptr<FakePointerController> fakePointerController =
std::make_shared<FakePointerController>();
- mFakePolicy->setPointerController(mDevice->getId(), fakePointerController);
- mFakePolicy->setPointerController(SECOND_DEVICE_ID, fakePointerController);
+ mFakePolicy->setPointerController(fakePointerController);
// Setup policy for associated displays and show touches.
const uint8_t hdmi1 = 0;
@@ -8590,7 +8631,7 @@
mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
mFakePolicy->setPointerCapture(true);
- mFakePolicy->setPointerController(mDevice->getId(), fakePointerController);
+ mFakePolicy->setPointerController(fakePointerController);
MultiTouchInputMapper& mapper = addMapperAndConfigure<MultiTouchInputMapper>();
// captured touchpad should be a touchpad source
@@ -8740,7 +8781,7 @@
prepareAxes(POSITION | ID | SLOT);
mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
- mFakePolicy->setPointerController(mDevice->getId(), fakePointerController);
+ mFakePolicy->setPointerController(fakePointerController);
MultiTouchInputMapper& mapper = addMapperAndConfigure<MultiTouchInputMapper>();
// run uncaptured pointer tests - pushes out generic events
// FINGER 0 DOWN
@@ -8780,7 +8821,7 @@
prepareDisplay(DISPLAY_ORIENTATION_0);
prepareAxes(POSITION | ID | SLOT);
mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
- mFakePolicy->setPointerController(mDevice->getId(), fakePointerController);
+ mFakePolicy->setPointerController(fakePointerController);
mFakePolicy->setPointerCapture(false);
MultiTouchInputMapper& mapper = addMapperAndConfigure<MultiTouchInputMapper>();
diff --git a/services/surfaceflinger/CompositionEngine/src/Output.cpp b/services/surfaceflinger/CompositionEngine/src/Output.cpp
index 1747294..31b699e 100644
--- a/services/surfaceflinger/CompositionEngine/src/Output.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Output.cpp
@@ -778,6 +778,9 @@
if (compState->sidebandStream != nullptr) {
return nullptr;
}
+ if (compState->isOpaque) {
+ continue;
+ }
if (compState->backgroundBlurRadius > 0 || compState->blurRegions.size() > 0) {
layerRequestingBgComposition = layer;
}
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
index a904c7d..e1c9aaa 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
@@ -3618,6 +3618,7 @@
: public OutputComposeSurfacesTest_SetsExpensiveRendering {
OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur() {
mLayer.layerFEState.backgroundBlurRadius = 10;
+ mLayer.layerFEState.isOpaque = false;
mOutput.editState().isEnabled = true;
EXPECT_CALL(mLayer.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
@@ -4191,6 +4192,37 @@
kDisplayDataspace));
}
+TEST_F(OutputUpdateAndWriteCompositionStateTest, noBackgroundBlurWhenOpaque) {
+ InjectedLayer layer1;
+ InjectedLayer layer2;
+
+ uint32_t z = 0;
+ // Layer requesting blur, or below, should request client composition, unless opaque.
+ EXPECT_CALL(*layer1.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_0));
+ EXPECT_CALL(*layer1.outputLayer,
+ writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
+ /*zIsOverridden*/ false, /*isPeekingThrough*/ false));
+ EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_0));
+ EXPECT_CALL(*layer2.outputLayer,
+ writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
+ /*zIsOverridden*/ false, /*isPeekingThrough*/ false));
+
+ layer2.layerFEState.backgroundBlurRadius = 10;
+ layer2.layerFEState.isOpaque = true;
+
+ injectOutputLayer(layer1);
+ injectOutputLayer(layer2);
+
+ mOutput->editState().isEnabled = true;
+
+ CompositionRefreshArgs args;
+ args.updatingGeometryThisFrame = false;
+ args.devOptForceClientComposition = false;
+ mOutput->updateCompositionState(args);
+ mOutput->planComposition();
+ mOutput->writeCompositionState(args);
+}
+
TEST_F(OutputUpdateAndWriteCompositionStateTest, handlesBackgroundBlurRequests) {
InjectedLayer layer1;
InjectedLayer layer2;
@@ -4212,6 +4244,7 @@
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
layer2.layerFEState.backgroundBlurRadius = 10;
+ layer2.layerFEState.isOpaque = false;
injectOutputLayer(layer1);
injectOutputLayer(layer2);
@@ -4249,6 +4282,7 @@
BlurRegion region;
layer2.layerFEState.blurRegions.push_back(region);
+ layer2.layerFEState.isOpaque = false;
injectOutputLayer(layer1);
injectOutputLayer(layer2);
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index b872c85..804cf9a 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -2016,8 +2016,8 @@
if (buffer != nullptr) {
LayerProtoHelper::writeToProto(buffer,
[&]() { return layerInfo->mutable_active_buffer(); });
- LayerProtoHelper::writeToProto(ui::Transform(getBufferTransform()),
- layerInfo->mutable_buffer_transform());
+ LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
+ layerInfo->mutable_buffer_transform());
}
layerInfo->set_invalidate(contentDirty);
layerInfo->set_is_protected(isProtected());
@@ -2031,7 +2031,7 @@
layerInfo->set_corner_radius(getRoundedCornerState().radius);
layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
layerInfo->set_is_trusted_overlay(isTrustedOverlay());
- LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
+ LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
[&]() { return layerInfo->mutable_position(); });
LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
@@ -2106,8 +2106,8 @@
[&]() { return layerInfo->mutable_requested_color(); });
layerInfo->set_flags(state.flags);
- LayerProtoHelper::writeToProto(requestedTransform,
- layerInfo->mutable_requested_transform());
+ LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
+ layerInfo->mutable_requested_transform());
auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
if (parent != nullptr) {
diff --git a/services/surfaceflinger/LayerProtoHelper.cpp b/services/surfaceflinger/LayerProtoHelper.cpp
index 79f7b1f..1062126 100644
--- a/services/surfaceflinger/LayerProtoHelper.cpp
+++ b/services/surfaceflinger/LayerProtoHelper.cpp
@@ -98,8 +98,8 @@
}
}
-void LayerProtoHelper::writeToProto(const ui::Transform& transform,
- TransformProto* transformProto) {
+void LayerProtoHelper::writeToProtoDeprecated(const ui::Transform& transform,
+ TransformProto* transformProto) {
const uint32_t type = transform.getType() | (transform.getOrientation() << 8);
transformProto->set_type(type);
@@ -114,6 +114,22 @@
}
}
+void LayerProtoHelper::writeTransformToProto(const ui::Transform& transform,
+ TransformProto* transformProto) {
+ const uint32_t type = transform.getType() | (transform.getOrientation() << 8);
+ transformProto->set_type(type);
+
+ // Rotations that are 90/180/270 have their own type so the transform matrix can be
+ // reconstructed later. All other rotation have the type UNKNOWN so we need to save the
+ // transform values in that case.
+ if (type & (ui::Transform::SCALE | ui::Transform::UNKNOWN)) {
+ transformProto->set_dsdx(transform.dsdx());
+ transformProto->set_dtdx(transform.dtdx());
+ transformProto->set_dtdy(transform.dtdy());
+ transformProto->set_dsdy(transform.dsdy());
+ }
+}
+
void LayerProtoHelper::writeToProto(const sp<GraphicBuffer>& buffer,
std::function<ActiveBufferProto*()> getActiveBufferProto) {
if (buffer->getWidth() != 0 || buffer->getHeight() != 0 || buffer->getStride() != 0 ||
@@ -154,7 +170,7 @@
proto->set_has_wallpaper(inputInfo.hasWallpaper);
proto->set_global_scale_factor(inputInfo.globalScaleFactor);
- LayerProtoHelper::writeToProto(inputInfo.transform, proto->mutable_transform());
+ LayerProtoHelper::writeToProtoDeprecated(inputInfo.transform, proto->mutable_transform());
proto->set_replace_touchable_region_with_crop(inputInfo.replaceTouchableRegionWithCrop);
auto cropLayer = touchableRegionBounds.promote();
if (cropLayer != nullptr) {
diff --git a/services/surfaceflinger/LayerProtoHelper.h b/services/surfaceflinger/LayerProtoHelper.h
index 187ce3d..36e0647 100644
--- a/services/surfaceflinger/LayerProtoHelper.h
+++ b/services/surfaceflinger/LayerProtoHelper.h
@@ -37,7 +37,12 @@
std::function<FloatRectProto*()> getFloatRectProto);
static void writeToProto(const Region& region, std::function<RegionProto*()> getRegionProto);
static void writeToProto(const half4 color, std::function<ColorProto*()> getColorProto);
- static void writeToProto(const ui::Transform& transform, TransformProto* transformProto);
+ // This writeToProto for transform is incorrect, but due to backwards compatibility, we can't
+ // update Layers to use it. Use writeTransformToProto for any new transform proto data.
+ static void writeToProtoDeprecated(const ui::Transform& transform,
+ TransformProto* transformProto);
+ static void writeTransformToProto(const ui::Transform& transform,
+ TransformProto* transformProto);
static void writeToProto(const sp<GraphicBuffer>& buffer,
std::function<ActiveBufferProto*()> getActiveBufferProto);
static void writeToProto(const gui::WindowInfo& inputInfo,
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 534efee..c64ccd1 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -395,6 +395,14 @@
return;
}
+ // If the mode is not the current mode, this means that a
+ // mode change is in progress. In that case we shouldn't dispatch an event
+ // as it will be dispatched when the current mode changes.
+ if (std::scoped_lock lock(mRefreshRateConfigsLock);
+ mRefreshRateConfigs->getCurrentRefreshRate().getMode() != mFeatures.mode) {
+ return;
+ }
+
// If there is no change from cached mode, there is no need to dispatch an event
if (mFeatures.mode == mFeatures.cachedModeChangedParams->mode) {
return;
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 15db2ed..21b889e 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -109,11 +109,13 @@
#include "DisplayRenderArea.h"
#include "EffectLayer.h"
#include "Effects/Daltonizer.h"
+#include "FlagManager.h"
#include "FpsReporter.h"
#include "FrameTimeline/FrameTimeline.h"
#include "FrameTracer/FrameTracer.h"
#include "HdrLayerInfoReporter.h"
#include "Layer.h"
+#include "LayerProtoHelper.h"
#include "LayerRenderArea.h"
#include "LayerVector.h"
#include "MonitoredProducer.h"
@@ -672,6 +674,7 @@
const nsecs_t duration = now - mBootTime;
ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
+ mFlagManager = std::make_unique<android::FlagManager>();
mFrameTracer->initialize();
mFrameTimeline->onBootFinished();
@@ -2419,23 +2422,28 @@
}
}
-FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
- return displayDevice.getLayerStackSpaceRect().toFloatRect();
-}
-
void SurfaceFlinger::computeLayerBounds() {
+ // Find the largest width and height among all the displays.
+ int32_t maxDisplayWidth = 0;
+ int32_t maxDisplayHeight = 0;
for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
const auto& displayDevice = pair.second;
- const auto display = displayDevice->getCompositionDisplay();
- for (const auto& layer : mDrawingState.layersSortedByZ) {
- // Only consider the layers on this display.
- if (!display->includesLayer(layer->getOutputFilter())) {
- continue;
- }
-
- layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
- 0.f /* shadowRadius */);
+ int32_t width = displayDevice->getWidth();
+ int32_t height = displayDevice->getHeight();
+ if (width > maxDisplayWidth) {
+ maxDisplayWidth = width;
}
+ if (height > maxDisplayHeight) {
+ maxDisplayHeight = height;
+ }
+ }
+
+ // Ignore display bounds for now since they will be computed later. Use a large Rect bound
+ // to ensure it's bigger than an actual display will be.
+ FloatRect maxBounds(-maxDisplayWidth * 10, -maxDisplayHeight * 10, maxDisplayWidth * 10,
+ maxDisplayHeight * 10);
+ for (const auto& layer : mDrawingState.layersSortedByZ) {
+ layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
}
}
@@ -4636,9 +4644,14 @@
}
if (dumpLayers) {
- const LayersProto layersProto = dumpProtoFromMainThread();
+ LayersTraceFileProto traceFileProto = SurfaceTracing::createLayersTraceFileProto();
+ LayersTraceProto* layersTrace = traceFileProto.add_entry();
+ LayersProto layersProto = dumpProtoFromMainThread();
+ layersTrace->mutable_layers()->Swap(&layersProto);
+ dumpDisplayProto(*layersTrace);
+
if (asProto) {
- result.append(layersProto.SerializeAsString());
+ result.append(traceFileProto.SerializeAsString());
} else {
// Dump info that we need to access from the main thread
const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
@@ -4910,6 +4923,22 @@
return layersProto;
}
+void SurfaceFlinger::dumpDisplayProto(LayersTraceProto& layersTraceProto) const {
+ for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
+ DisplayProto* displayProto = layersTraceProto.add_displays();
+ displayProto->set_id(display->getId().value);
+ displayProto->set_name(display->getDisplayName());
+ displayProto->set_layer_stack(display->getLayerStack().id);
+ LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
+ [&]() { return displayProto->mutable_size(); });
+ LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
+ return displayProto->mutable_layer_stack_space_rect();
+ });
+ LayerProtoHelper::writeTransformToProto(display->getTransform(),
+ displayProto->mutable_transform());
+ }
+}
+
void SurfaceFlinger::dumpHwc(std::string& result) const {
getHwComposer().dump(result);
}
@@ -5129,6 +5158,11 @@
const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
alloc.dump(result);
+ /*
+ * Dump flag/property manager state
+ */
+ mFlagManager->dump(result);
+
result.append(mTimeStats->miniDump());
result.append("\n");
}
@@ -5645,6 +5679,7 @@
return nullptr;
}();
+ mDebugDisplayModeSetByBackdoor = false;
const status_t result = setActiveMode(display, modeId);
mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
return result;
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 33bc17b..407907d 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -89,6 +89,7 @@
class Client;
class EventThread;
+class FlagManager;
class FpsReporter;
class TunnelModeEnabledReporter;
class HdrLayerInfoReporter;
@@ -353,13 +354,6 @@
std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks)
REQUIRES(mStateLock);
- // Used internally by computeLayerBounds() to gets the clip rectangle to use for the
- // root layers on a particular display in layer-coordinate space. The
- // layers (and effectively their children) will be clipped against this
- // rectangle. The base behavior is to clip to the visible region of the
- // display.
- virtual FloatRect getLayerClipBoundsForDisplay(const DisplayDevice&) const;
-
virtual void processDisplayAdded(const wp<IBinder>& displayToken, const DisplayDeviceState&)
REQUIRES(mStateLock);
@@ -1174,6 +1168,8 @@
LayersProto dumpDrawingStateProto(uint32_t traceFlags) const;
void dumpOffscreenLayersProto(LayersProto& layersProto,
uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
+ void dumpDisplayProto(LayersTraceProto& layersTraceProto) const;
+
// Dumps state from HW Composer
void dumpHwc(std::string& result) const;
LayersProto dumpProtoFromMainThread(uint32_t traceFlags = SurfaceTracing::TRACE_ALL)
@@ -1519,6 +1515,8 @@
wp<IBinder> mActiveDisplayToken GUARDED_BY(mStateLock);
const sp<WindowInfosListenerInvoker> mWindowInfosListenerInvoker;
+
+ std::unique_ptr<FlagManager> mFlagManager;
};
} // namespace android
diff --git a/services/surfaceflinger/SurfaceTracing.cpp b/services/surfaceflinger/SurfaceTracing.cpp
index b4d8a9a..5963737 100644
--- a/services/surfaceflinger/SurfaceTracing.cpp
+++ b/services/surfaceflinger/SurfaceTracing.cpp
@@ -137,14 +137,19 @@
return writeToFile();
}
+LayersTraceFileProto SurfaceTracing::createLayersTraceFileProto() {
+ LayersTraceFileProto fileProto;
+ fileProto.set_magic_number(uint64_t(LayersTraceFileProto_MagicNumber_MAGIC_NUMBER_H) << 32 |
+ LayersTraceFileProto_MagicNumber_MAGIC_NUMBER_L);
+ return fileProto;
+}
+
status_t SurfaceTracing::Runner::writeToFile() {
ATRACE_CALL();
- LayersTraceFileProto fileProto;
+ LayersTraceFileProto fileProto = createLayersTraceFileProto();
std::string output;
- fileProto.set_magic_number(uint64_t(LayersTraceFileProto_MagicNumber_MAGIC_NUMBER_H) << 32 |
- LayersTraceFileProto_MagicNumber_MAGIC_NUMBER_L);
mBuffer.flush(&fileProto);
mBuffer.reset(mConfig.bufferSize);
@@ -186,7 +191,7 @@
entry.set_excludes_composition_state(true);
}
entry.set_missed_entries(mMissedTraceEntries);
-
+ mFlinger.dumpDisplayProto(entry);
return entry;
}
diff --git a/services/surfaceflinger/SurfaceTracing.h b/services/surfaceflinger/SurfaceTracing.h
index 42a16c6..cea1a33 100644
--- a/services/surfaceflinger/SurfaceTracing.h
+++ b/services/surfaceflinger/SurfaceTracing.h
@@ -73,6 +73,7 @@
};
void setTraceFlags(uint32_t flags) { mConfig.flags = flags; }
bool flagIsSet(uint32_t flags) { return (mConfig.flags & flags) == flags; }
+ static LayersTraceFileProto createLayersTraceFileProto();
private:
class Runner;
diff --git a/services/surfaceflinger/layerproto/Android.bp b/services/surfaceflinger/layerproto/Android.bp
index c8a2b5e..973a439 100644
--- a/services/surfaceflinger/layerproto/Android.bp
+++ b/services/surfaceflinger/layerproto/Android.bp
@@ -13,8 +13,7 @@
srcs: [
"LayerProtoParser.cpp",
- "layers.proto",
- "layerstrace.proto",
+ "*.proto",
],
shared_libs: [
diff --git a/services/surfaceflinger/layerproto/common.proto b/services/surfaceflinger/layerproto/common.proto
new file mode 100644
index 0000000..1c73a9f
--- /dev/null
+++ b/services/surfaceflinger/layerproto/common.proto
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+syntax = "proto3";
+option optimize_for = LITE_RUNTIME;
+package android.surfaceflinger;
+
+message RectProto {
+ int32 left = 1;
+ int32 top = 2;
+ int32 right = 3;
+ int32 bottom = 4;
+}
+
+message SizeProto {
+ int32 w = 1;
+ int32 h = 2;
+}
+
+message TransformProto {
+ float dsdx = 1;
+ float dtdx = 2;
+ float dsdy = 3;
+ float dtdy = 4;
+ int32 type = 5;
+}
\ No newline at end of file
diff --git a/services/surfaceflinger/layerproto/display.proto b/services/surfaceflinger/layerproto/display.proto
new file mode 100644
index 0000000..ee8830e
--- /dev/null
+++ b/services/surfaceflinger/layerproto/display.proto
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+syntax = "proto3";
+option optimize_for = LITE_RUNTIME;
+
+import "frameworks/native/services/surfaceflinger/layerproto/common.proto";
+
+package android.surfaceflinger;
+
+message DisplayProto {
+ uint64 id = 1;
+
+ string name = 2;
+
+ uint32 layer_stack = 3;
+
+ SizeProto size = 4;
+
+ RectProto layer_stack_space_rect = 5;
+
+ TransformProto transform = 6;
+}
diff --git a/services/surfaceflinger/layerproto/layers.proto b/services/surfaceflinger/layerproto/layers.proto
index 9f4e7d2..057eabb 100644
--- a/services/surfaceflinger/layerproto/layers.proto
+++ b/services/surfaceflinger/layerproto/layers.proto
@@ -2,6 +2,9 @@
syntax = "proto3";
option optimize_for = LITE_RUNTIME;
+
+import "frameworks/native/services/surfaceflinger/layerproto/common.proto";
+
package android.surfaceflinger;
// Contains a list of all layers.
@@ -140,31 +143,11 @@
float y = 2;
}
-message SizeProto {
- int32 w = 1;
- int32 h = 2;
-}
-
-message TransformProto {
- float dsdx = 1;
- float dtdx = 2;
- float dsdy = 3;
- float dtdy = 4;
- int32 type = 5;
-}
-
message RegionProto {
reserved 1; // Previously: uint64 id
repeated RectProto rect = 2;
}
-message RectProto {
- int32 left = 1;
- int32 top = 2;
- int32 right = 3;
- int32 bottom = 4;
-}
-
message FloatRectProto {
float left = 1;
float top = 2;
diff --git a/services/surfaceflinger/layerproto/layerstrace.proto b/services/surfaceflinger/layerproto/layerstrace.proto
index 990f3cf..13647b6 100644
--- a/services/surfaceflinger/layerproto/layerstrace.proto
+++ b/services/surfaceflinger/layerproto/layerstrace.proto
@@ -18,6 +18,7 @@
option optimize_for = LITE_RUNTIME;
import "frameworks/native/services/surfaceflinger/layerproto/layers.proto";
+import "frameworks/native/services/surfaceflinger/layerproto/display.proto";
package android.surfaceflinger;
@@ -57,4 +58,6 @@
/* Number of missed entries since the last entry was recorded. */
optional uint32 missed_entries = 6;
+
+ repeated DisplayProto displays = 7;
}
diff --git a/services/surfaceflinger/tests/EffectLayer_test.cpp b/services/surfaceflinger/tests/EffectLayer_test.cpp
index 1361ded..9fa0452 100644
--- a/services/surfaceflinger/tests/EffectLayer_test.cpp
+++ b/services/surfaceflinger/tests/EffectLayer_test.cpp
@@ -176,6 +176,15 @@
}
}
+TEST_F(EffectLayerTest, EffectLayerWithColorNoCrop) {
+ const auto display = SurfaceComposerClient::getInternalDisplayToken();
+ ui::DisplayMode mode;
+ ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getActiveDisplayMode(display, &mode));
+ const ui::Size& resolution = mode.resolution;
+ auto shot = screenshot();
+ shot->expectColor(Rect(0, 0, resolution.getWidth(), resolution.getHeight()), Color::RED);
+}
+
} // namespace android
// TODO(b/129481165): remove the #pragma below and fix conversion issues
diff --git a/vulkan/libvulkan/swapchain.cpp b/vulkan/libvulkan/swapchain.cpp
index 2715587..3ed3eba 100644
--- a/vulkan/libvulkan/swapchain.cpp
+++ b/vulkan/libvulkan/swapchain.cpp
@@ -1231,6 +1231,12 @@
return VK_ERROR_SURFACE_LOST_KHR;
}
+ // In shared mode the num_images must be one regardless of how many
+ // buffers were allocated for the buffer queue.
+ if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
+ num_images = 1;
+ }
+
int32_t legacy_usage = 0;
if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
uint64_t consumer_usage, producer_usage;